1 labelme 转 yolov8 格式
import json
import cv2
import numpy as np
import os
def json2yolo(path):
dic={'N_shaoxi':'0', 'N_qiaoqi':'1', 'N_qiaojie':'2', 'N_pianyi':'3', 'N_yiwu': '4', \
'NV_shaoxi': '5', 'NV_qiaoqi': '6', 'NV_qiaojie': '7', 'NV_pianyi': '8', 'NV_yiwu': '9',\
'R_shaoxi': '10', 'R_qiaoqi': '11', 'R_qiaojie': '12', 'R_pianyi': '13', 'R_yiwu': '14',\
'XS_shaoxi': '15', "XS_qiaoqi": '16', 'XS_qiaojie': '17', 'XS_pianyi': '18', 'XS_yiwu': '19',
'XP_shaoxi': '15', "XP_qiaoqi": '16', 'XP_qiaojie': '17', 'XP_pianyi': '18', 'XP_yiwu': '19'}
if ".json" in path:
data = json.load(open(path,encoding="utf-8"))
w=data["imageWidth"]
h=data["imageHeight"]
all_line=''
for i in data["shapes"]:
[[x1,y1],[x2,y2]]=i['points']
x1,x2=x1/w,x2/w
y1,y2=y1/h,y2/h
cx=(x1+x2)/2
cy=(y1+y2)/2
wi=abs(x2-x1)
hi=abs(y2-y1)
line="%s %.4f %.4f %.4f %.4f\n"%(dic[i['label']],cx,cy,wi,hi)
all_line+=line
filename = path.replace('json','txt')
fh = open(filename,'w',encoding='utf-8')
fh.write(all_line)
fh.close()
else:
filename = path.replace('.jpg', '.txt')
fh = open(filename, 'w', encoding='utf-8')
fh.close()
path= "E:/_0904/"
path_list_sub = os.listdir(path)
print("path_list_sub", path_list_sub)
for path_sub in path_list_sub:
json_path_list =os.listdir(path+path_sub)
path_list2=[x for x in json_path_list]
print("len of path_list2 ",path_sub,len(path_list2))
for p in path_list2:
absolute_path= (path+path_sub+'/'+p)
print("abs path",absolute_path)
json2yolo(path+path_sub+'/'+p)
2 分为训练集&验证集合
import json
import cv2
import numpy as np
import os
import shutil
root_root_path = "。/0904/"
root_paths = os.listdir(root_root_path)
for root_path in root_paths:
root_path = root_root_path+root_path+'/'
class_path_list = os.listdir(root_path)
print("path_list_sub", class_path_list)
all_file_path=[]
index=0
for class_path in class_path_list:
all_path_list =os.listdir(root_path+class_path)
for file in all_path_list:
all_file_path.append((root_path + class_path + '/' + file))
print("file len ",len(all_file_path))
txt_file_path=[]
for file_path in all_file_path:
if file_path[-3:]=="txt":
print("file_path",file_path)
txt_file_path.append(file_path)
print("txt file len ",len(txt_file_path))
train_index = 0
valid_index = 0
split_index = 0
for tf in txt_file_path:
if os.path.exists(tf[:-3]+'jpg'):
if split_index % 5 != 0:
shutil.copy(tf,fr'.\X_DATA\train\labels')
shutil.copy(tf[:-3]+'jpg', fr'.\train\images')
train_index += 1
else:
shutil.copy(tf,fr'.\X_DATA\valid\labels')
shutil.copy(tf[:-3]+'jpg', fr'.\X_DATA\valid\images')
valid_index += 1
split_index += 1
print("train_index image num:", train_index)
print("valid_index image num:", valid_index)
print("split_index image num:", split_index)