yolov8预标注图片,减少人工标注,提高生产力

代码写的很简洁,可以直接复制粘贴使用

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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值