数据标注的时候太虎了,LabelImg一直是处于createML格式的,我要的是Yolo的格式,遂在网上找转化脚本,但没有现成的,于是自己写了一个,希望能帮助到其他人。四个有解释的地方是需要根据你自身的情况改动的。
import json
import os
from PIL import Image
picture_path = r"" //图片地址
label_path = r""//createML格标签的地址
label_path_new = r""//即将生成的YOLO格式标签的地址
annotation_labels = [] //这里插入YOLO标注文件夹的classes.txt里面的内容
label_list = os.listdir(label_path)
for i in range(len(label_list)):
with open(label_path + '\\' + label_list[i]) as file:
img_pillow = Image.open(picture_path + '\\' + label_list[i].split(".")[0] + '.jpg')
img_width = img_pillow.width # 图片宽度
img_height = img_pillow.height
c_list = json.load(file)[0]["annotations"]
# print(c_list[0]['annotations'][0]['label'])
for j in range(len(c_list)):
label_id = c_list[j]["label"]
label_x = c_list[j]["coordinates"]['x']
label_y = c_list[j]["coordinates"]['y']
label_width = c_list[j]["coordinates"]['width']
label_height = c_list[j]["coordinates"]['height']
with open(label_path_new + "\\" + label_list[i].split(".")[0] + '.txt', 'a', encoding='utf-8') as file1:
file1.write(
str(annotation_labels.index(label_id)) + " " + "{:.6f}".format(
label_x / img_width) + " " + "{:.6f}".format(label_y / img_height) + " " + "{:.6f}".format(
label_width / img_width) + " " + "{:.6f}".format(label_height / img_height) + "\n")
# print(img_height)
# print(img_width)