YOLO V8半自动标注工具设计

前提:

对于某些边界不明确的小目标,要是目标由比较多的话,标注起来就会非常麻烦。

如何利用已有训练模型,生成框,进行预标注。再通过调节预标注框的方式,提高标注的效率。

1 通过预先训练的模型生成yolo 格式的框

python 复制代码
image_absolute_path = "yyy_test/img/L206_20240516101319_2_20240516101319_N49_2.jpg"
# Load the YOLOv8 model#
model = YOLO('./runs/detect/train4080/26/last.pt')  # 4080
# Open the video file
image = cv.imread(image_absolute_path, 1)
results = model.predict(image_absolute_path, imgsz=640, show=True)
shape = image.shape
# float_rect[0] *= shape[1]
# float_rect[1] *= shape[0]
# float_rect[2] *= shape[1]
# float_rect[3] *= shape[0]
filename = image_absolute_path.replace('jpg', 'txt')  # 将path里的json替换成txt,生成txt里相对应的文件路径
w = shape[1]
h = shape[0]
fh = open(filename, 'w', encoding='utf-8')
all_line = ''
results[0].plot()
for result in results:
    for r in result.boxes.data.tolist():
        x1, y1, x2, y2, score, class_id = r
        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" % (class_id, cx, cy, wi, hi)  # 生成txt文件里每行的内容
        all_line += line
fh.write(all_line)

yolo .txt 格式的框

2 将yolo 格式 转换为labelme 格式

python 复制代码
import cv2
import os
import json
import shutil
import numpy as np
from pathlib import Path

dic = {0: 'NVshaoxi', 1: "Nqiaoqi", 2: 'Nqiaojie',3: 'N_pianyi',4: "N_yiwu" ,\
       5: 'NVshaoxi', 6: "NVqiaoqi", 7: 'NVqiaojie',8: 'NV_pianyi',9: "NV_yiwu"}
def xyxy2labelme(labels, w, h, image_path, save_dir='res/'):
    save_dir = str(Path(save_dir)) + '/'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    label_dict = {}
    label_dict['version'] = '5.0.1'
    label_dict['flags'] = {}
    label_dict['imageData'] = None
    label_dict['imagePath'] = image_path
    label_dict['imageHeight'] = h
    label_dict['imageWidth'] = w
    label_dict['shapes'] = []
    for l in labels:
        tmp = {}
        tmp['label'] = dic[int(l[0])]
        tmp['points'] = [[l[1], l[2]], [l[3], l[4]]]
        tmp['group_id'] = None
        tmp['shape_type'] = 'rectangle'
        tmp['flags'] = {}
        label_dict['shapes'].append(tmp)
    fn = save_dir + image_path.rsplit('.', 1)[0] + '.json'
    with open(fn, 'w') as f:
        json.dump(label_dict, f)


def yolo2labelme(yolo_image_dir, yolo_label_dir, save_dir='res/'):
    yolo_image_dir = str(Path(yolo_image_dir)) + '/'
    yolo_label_dir = str(Path(yolo_label_dir)) + '/'
    save_dir = str(Path(save_dir)) + '/'
    image_files = os.listdir(yolo_image_dir)
    for iimgf, imgf in enumerate(image_files):
        print(iimgf + 1, '/', len(image_files), imgf)
        fn = imgf.rsplit('.', 1)[0]
        shutil.copy(yolo_image_dir + imgf, save_dir + imgf)
        image = cv2.imread(yolo_image_dir + imgf)
        h, w = image.shape[:2]
        if not os.path.exists(yolo_label_dir + fn + '.txt'):
            continue
        labels = np.loadtxt(yolo_label_dir + fn + '.txt').reshape(-1, 5)
        if len(labels) < 1:
            continue
        labels[:, 1::2] = w * labels[:, 1::2]
        labels[:, 2::2] = h * labels[:, 2::2]
        labels_xyxy = np.zeros(labels.shape)
        labels_xyxy[:, 0] = np.clip(labels[:, 0], 0, 20)
        labels_xyxy[:, 1] = np.clip(labels[:, 1] - labels[:, 3] / 2, 0, w)
        labels_xyxy[:, 2] = np.clip(labels[:, 2] - labels[:, 4] / 2, 0, h)
        labels_xyxy[:, 3] = np.clip(labels[:, 1] + labels[:, 3] / 2, 0, w)
        labels_xyxy[:, 4] = np.clip(labels[:, 2] + labels[:, 4] / 2, 0, h)
        xyxy2labelme(labels_xyxy, w, h, imgf, save_dir)
    print('Completed!')


if __name__ == '__main__':
    yolo_image_dir = 'E:/pythonCode/pythonProject1/yyy_test/img/'
    yolo_label_dir = 'E:/pythonCode/pythonProject1/yyy_test/txt/'
    save_dir ='E:/pythonCode/pythonProject1/res/'
    yolo2labelme(yolo_image_dir, yolo_label_dir, save_dir)

labelme 的 .json格式

3 用labelme 微调标注框

将刚才生成的与图片名称相同的后缀为.json 的文件和图片放在同一个目录下,然后用labelme 打开该dir。

4 再将labelme 格式的数据变为yolo 格式,加入训练

python 复制代码
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',
    #      '1': '0'}
    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'}
    #dic = {'N_shaoxi': '0', 'N_shaoxi': '1','N_qiaojie': '2','N_pianyi':'3','N_yiwu:'4'}  # 类别字典

    if ".json" in path:
        data = json.load(open(path,encoding="utf-8"))#读取带有中文的文件
        w=data["imageWidth"]#获取jaon文件里图片的宽高
        h=data["imageHeight"]
        all_line=''
        for i in  data["shapes"]:
            #归一化坐标点。并得到cx,cy,w,h
            [[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)

            #将数据组装成yolo格式
            line="%s %.4f %.4f %.4f %.4f\n"%(dic[i['label']],cx,cy,wi,hi)#生成txt文件里每行的内容
            all_line+=line
       # print(all_line)
        filename = path.replace('json','txt')#将path里的json替换成txt,生成txt里相对应的文件路径
        fh = open(filename,'w',encoding='utf-8')
        fh.write(all_line)
        fh.close()
    else:
        filename = path.replace('.jpg', '.txt')  # 将path里的json替换成txt,生成txt里相对应的文件路径
        fh = open(filename, 'w', encoding='utf-8')
        fh.close()

path= "E:/919XP/" # /
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]#获取所有json文件的路径
   # path_list2 = [x for x in json_path_list if ".json" in x]  # 获取所有json文件的路径
    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)
相关推荐
Teln_小凯4 分钟前
nodejs - puppeteer 无头浏览器截图 JAVA后端调用
java·前端·python
Chen Hao .1 小时前
Python虚拟环境进阶:掌握可复制性,提升量化交易稳定性
开发语言·python
川泽曦星1 小时前
【第十四周】PyTorch深度学习实践1
人工智能·pytorch·深度学习
汪子熙1 小时前
如何评价 Python 语言的运行速度
开发语言·python
是Dream呀1 小时前
Python从0到100(六十):机器学习-模型选择与交叉验证
开发语言·python
Q186000000002 小时前
macOS 系统中python的安装步骤
开发语言·python·macos
IT北辰2 小时前
python为姓名注音实战案例
开发语言·python
余生H2 小时前
前端大模型入门:实战篇之Vue3+Antdv+transformers+本地模型实现增强搜索
前端·javascript·vue.js·深度学习·transformer·深度搜索·webml
杰哥在此2 小时前
Python知识点:如何使用Python进行卫星数据分析
开发语言·python·面试·数据分析·编程