当前位置: 首页 > article >正文

YOLO V8半自动标注工具设计

前提:
对于某些边界不明确的小目标,要是目标由比较多的话,标注起来就会非常麻烦。
如何利用已有训练模型,生成框,进行预标注。再通过调节预标注框的方式,提高标注的效率。

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


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 格式

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 格式,加入训练

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)

http://www.kler.cn/a/324939.html

相关文章:

  • git创建远程仓库,以gitee码云为例GitHub同理
  • Springboot采用jasypt加密配置
  • sqli-labs靶场17-20关(每日四关)持续更新!!!
  • 丑数动态规划
  • [产品管理-82]:《产品经理从入门到精通》产品经理的基本思维与核心思想
  • Python学习------第八天
  • macOS 开发环境配置与应用开发
  • Selenium与数据库结合:数据爬取与存储的技术实践
  • 项目管理系统中的风险管理:如何识别和应对项目风险?
  • three.js----快速上手,如何用vue在web页面中导入 gltf/glb , fbx , obj 模型
  • JavaScript动态数据可视化
  • 微信小程序环境下的相亲交友系统源码优化
  • Java必修课——Spring框架
  • 深度学习:残差网络(ResNet)的原理及优缺点
  • OpenCV-图像透视变换
  • Web 3.0 介绍
  • Docker实践与应用举例
  • MPI程序实例:自适应数值积分
  • k8s中,pod生命周期,初始化容器,容器探针,事件处理函数,理解其设计思路及作用
  • 字段映射和数据转换为什么是数据集成的关键?
  • 数据结构:栈 及其应用
  • 汽车总线之---- LIN总线
  • 一文上手SpringSecurity【二】
  • Flink 结合kafka 实现端到端的一致性原理
  • 一文说完c++全部基础知识,IO流(二)
  • 2、Java 基础 - 面向对象基础