用labelme polygons标出四个点生成的json文件和原图一起放到data文件夹中,同级目录下运行下面的python文件生成txt
import os
import numpy as np
import json
from glob import glob
import cv2
import math
from sklearn.model_selection import train_test_split
from os import getcwd
classes = ["0", "1"]#写自己数据集的标签
labelme_path = "data/" #数据集路径
isUseTest = True # 是否创建test集
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
train_files, val_files = train_test_split(trainval_files, test_size=0.1, random_state=55)
contours=[]
rects=[]
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x1 = ((box[0] + box[1]) / 2.0 - 1)*dw#归一化
y1 = ((box[2] + box[3]) / 2.0 - 1)*dh
for rect in rects:
x, y = rect[0]
width,height=rect[1]
angle=rect[2]
if width<height:
t=width
width=height
height=t
return (x1, y1,width,height,angle)
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')#w
for json_file_ in files:
json_filename = labelme_path + json_file_ + ".json"
imagePath = labelme_path + json_file_ + ".png"
list_file.write('%s/%s\n' % (wd, imagePath))
out_file = open('%s/%s.txt' % (labelme_path, json_file_), 'a')#w
json_file = json.load(open(json_filename, "r", encoding="utf-8"))
height, width, channels = cv2.imread(labelme_path + json_file_ + ".png").shape
for multi in json_file["shapes"]:
points = np.array(multi["points"])
contour=np.array(points,np.int32)
contours.append(contour)
rect = cv2.minAreaRect(contour)
rects.append(rect)
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"]
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')
ChangeToYolo5(train_files, "train")
ChangeToYolo5(val_files, "val")
ChangeToYolo5(test_files, "test")
生成txt格式:x,y,w,h,angle
参考文章链接:Win10 Labelme标注数据转为YOLOV5 训练的数据集_AI浩-CSDN博客_labelme转yolo
版权声明:本文为CSDN博主「shelly_you」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/shelly_you/article/details/122500602
暂无评论