以下教程用于将使用Labelme软件标注生成的json格式文件转成YOLO使用的txt格式,适用场景:多边形框
使用方法:将json文件夹路径填到jsonfilePath后, 将保存转化后txt的路径填入resultDirPath后,运行即可转化。
import json
import os
from tqdm import tqdm
import glob
import os.path as osp
# 参考链接 https://blog.csdn.net/m0_63330473/article/details/135079898
# 适应场景:lableme标注软件生成的json实例分割标签转yolo适用的txt格式
def json_to_txt(jsonfilePath, resultDirPath, ):
"""
jsonfilePath: labelme标注好的*.json文件所在文件夹
resultDirPath: 转换好后的*.txt保存文件夹
classList: 数据集中的类别标签
"""
class_names=[]
jsonfileList = glob.glob(osp.join(jsonfilePath, "*.json"))
# for jsonfile in jsonfileList:
# for jsonfile in jsonfileList:
for jsonfile in tqdm(jsonfileList, desc='Processing'):
with open(jsonfile, "r", encoding='UTF-8') as f:
file_in = json.load(f)
# 4. 读取文件中记录的所有标注目标
shapes = file_in["shapes"]
# 5. 使用图像名称创建一个txt文件,用来保存数据
with open(resultDirPath + "\\" + jsonfile.split("\\")[-1].replace(".json", ".txt"), "w") as file_handle:
# 6. 遍历shapes中的每个目标的轮廓
for shape in shapes:
if shape["label"] not in class_names:
class_names.append(shape["label"])
# 7.根据json中目标的类别标签,从classList中寻找类别的ID,然后写入txt文件中
file_handle.writelines(str(class_names.index(shape["label"])) + " ")
# 8. 遍历shape轮廓中的每个点,每个点要进行图像尺寸的缩放,即x/width, y/height
for point in shape["points"]:
x = point[0] / file_in["imageWidth"] # mask轮廓中一点的X坐标
y = point[1] / file_in["imageHeight"] # mask轮廓中一点的Y坐标
file_handle.writelines(str(x) + " " + str(y) + " ") # 写入mask轮廓点
file_handle.writelines("\n")
file_handle.close()
f.close()
with open(resultDirPath + '\\' + 'classes.txt', 'w') as f:
for i in class_names:
f.write(i + '\n')
if __name__ == "__main__":
jsonfilePath = r"O:\DeepLearningTool\dataset\segment\image" # 要转换的json文件所在目录
resultDirPath = r"O:\DeepLearningTool\dataset\segment\label" # 要生成的txt文件夹
json_to_txt(jsonfilePath=jsonfilePath, resultDirPath=resultDirPath,)