Win10 Labelme标注数据转为YOLOV5 训练的数据集

举报
AI浩 发表于 2021/12/23 01:44:04 2021/12/23
【摘要】 将Labelme标注的数据复制到工程的根目录,并将其命名为LabelmeData。我的工程根目录是yolov5-master,如下图:   打开工程,在根目录新建LabelmeToYolov5.py。写入下面的代码 import osimport numpy as npimport jsonfrom glob import ...
  • 将Labelme标注的数据复制到工程的根目录,并将其命名为LabelmeData。我的工程根目录是yolov5-master,如下图:

 

  • 打开工程,在根目录新建LabelmeToYolov5.py。写入下面的代码

      import os
      import numpy as np
      import json
      from glob import glob
      import cv2
      from sklearn.model_selection import train_test_split
      from os import getcwd
      classes = ["aircraft", "oiltank"]
      # 1.标签路径
      labelme_path = "LabelmeData/"
      isUseTest = True  # 是否创建test集
      # 3.获取待处理文件
      files = glob(labelme_path + "*.json")
      files = [i.replace("\\", "/").split("/")[-1].split(".json")[0] for i in files]
      print(files)
      if isUseTest:
          trainval_files, test_files = train_test_split(files, test_size=0.1, random_state=55)
      else:
          trainval_files = files
      # split
      train_files, val_files = train_test_split(trainval_files, test_size=0.1, random_state=55)
      def convert(size, box):
          dw = 1. / (size[0])
          dh = 1. / (size[1])
          x = (box[0] + box[1]) / 2.0 - 1
          y = (box[2] + box[3]) / 2.0 - 1
          w = box[1] - box[0]
          h = box[3] - box[2]
          x = x * dw
          w = w * dw
          y = y * dh
          h = h * dh
         return (x, y, w, h)
      wd = getcwd()
      print(wd)
      def ChangeToYolo5(files, txt_Name):
         if not os.path.exists('tmp/'):
              os.makedirs('tmp/')
          list_file = open('tmp/%s.txt' % (txt_Name), 'w')
         for json_file_ in files:
              json_filename = labelme_path + json_file_ + ".json"
              imagePath = labelme_path + json_file_ + ".jpg"
              list_file.write('%s/%s\n' % (wd, imagePath))
              out_file = open('%s/%s.txt' % (labelme_path, json_file_), 'w')
              json_file = json.load(open(json_filename, "r", encoding="utf-8"))
              height, width, channels = cv2.imread(labelme_path + json_file_ + ".jpg").shape
             for multi in json_file["shapes"]:
                  points = np.array(multi["points"])
                  xmin = min(points[:, 0]) if min(points[:, 0]) > 0 else 0
                  xmax = max(points[:, 0]) if max(points[:, 0]) > 0 else 0
                  ymin = min(points[:, 1]) if min(points[:, 1]) > 0 else 0
                  ymax = max(points[:, 1]) if max(points[:, 1]) > 0 else 0
                  label = multi["label"]
                 if xmax <= xmin:
                     pass
                 elif ymax <= ymin:
                     pass
                 else:
                      cls_id = classes.index(label)
                      b = (float(xmin), float(xmax), float(ymin), float(ymax))
                      bb = convert((width, height), b)
                      out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
                     print(json_filename, xmin, ymin, xmax, ymax, cls_id)
      ChangeToYolo5(train_files, "train")
      ChangeToYolo5(val_files, "val")
      ChangeToYolo5(test_files, "test")
      '''
      file1 = open("tmp/train.txt", "r")
      file2 = open("tmp/val.txt", "r")
      file_list1 = file1.readlines() # 将所有变量读入列表file_list1
      file_list2 = file2.readlines() # 将所有变量读入列表file_list2
      file3 = open("tmp/trainval.txt", "w")
      for line in file_list1:
       print(line)
       file3.write(line)
      for line in file_list2:
       print(line)
       file3.write(line)
      '''
  
 

这段代码执行完成会在LabelmeData生成每个图片的txt标注数据,同时在tmp文件夹下面生成训练集、验证集和测试集的txt,txt记录的是图片的路径,为下一步生成YoloV5训练和测试用的数据集做准备。

  • 在tmp文件夹新建makedata.py。执行完成后会在工程的根目录生成VOC数据集。

      import shutil
      import os
      file_List = ["train", "val", "test"]
      for file in file_List:
         if not os.path.exists('../VOC/images/%s' % file):
              os.makedirs('../VOC/images/%s' % file)
         if not os.path.exists('../VOC/labels/%s' % file):
              os.makedirs('../VOC/labels/%s' % file)
         print(os.path.exists('../tmp/%s.txt' % file))
          f = open('../tmp/%s.txt' % file, 'r')
          lines = f.readlines()
         for line in lines:
             print(line)
              line = "/".join(line.split('/')[-5:]).strip()
              shutil.copy(line, "../VOC/images/%s" % file)
              line = line.replace('jpg', 'txt')
              shutil.copy(line, "../VOC/labels/%s/" % file)
  
 

运行结果如下:

文章来源: wanghao.blog.csdn.net,作者:AI浩,版权归原作者所有,如需转载,请联系作者。

原文链接:wanghao.blog.csdn.net/article/details/108865894

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。