代码写的很简洁,可以直接复制粘贴使用
from ultralytics import YOLO
import glob,json
import cv2,time
from pathlib import Path
from tqdm import tqdm
# yolov8将模型结果转到json,生成自动化文件
# imgs_path,model_path,label_names
def model2json(imgs_path,modelPath):
model = YOLO(modelPath)
imgs_list = glob.glob(imgs_path + '/*.jpg')
print('images path:',imgs_path)
time.sleep(1)
for img_path in tqdm(imgs_list,desc='模型推理中images-->>json'):
img_Path = Path(img_path)
img = cv2.imread(img_path)
h,w,_ = img.shape
results = model.predict(str(img_path), imgsz=1280, show=False, line_width=1, half=False, conf=0.25,verbose=True)
used_label = results[0].names
json_data = results[0].boxes.data.tolist()
print(used_label)
res_list = []
if json_data:
for i in json_data:
bbox = [[round(i[0], 2), round(i[1],2)], [round(i[2],2),round(i[3],2)]]
res_list.append({"label": used_label[int(i[5])], "socre": round(i[4], 4), "location": bbox})
str_json_txt = {"version": "4.6.0", "flags": {}, "shapes": {}, "imagePath": {}, "imageData": {},
"imageHeight": {}, "imageWidth": {}}
res_list = sorted(res_list, key=lambda x: x['label'], reverse=False) # 多标签名称进行排序
# print(res_list)
with open(img_Path.with_suffix('.json'), "w+", encoding='UTF-8') as out_file:
bbox =[]
for obj in res_list:
shape_dict = {
"id": 1234567890,
"name": obj['label'],
"label": obj['label'],
"points": obj['location'],
"group_id":int(obj['socre']*100),
"shape_type": "rectangle",
"flags": ""
}
bbox.append(shape_dict)
str_json_txt['shapes'] = bbox
str_json_txt['imagePath'] = img_Path.name
str_json_txt['imageHeight'] =h
str_json_txt['imageWidth'] =w
str_json_txt['imageData'] =None
js = json.dumps(str_json_txt, indent=4, separators=(',', ':'))
out_file.write(js)
if __name__ == '__main__':
modelPath =r'D:\working\yolov8\models\train23\weights\best.pt'
imagesPath =r'D:\working\yolov8\images'
model2json(imagesPath, modelPath)