labelme标注的json文件转voc格式xml

用labelme标注图片,得到的是json格式文件,偶尔我们需要voc格式的数据标注,以下是转换脚本,只需把文件路径替换即可。

#标签路径
labelme_path = "/home/user/Database/Toolbox/data/空气开关/"              #原始labelme标注数据路径
saved_path = "/home/user/Database/Toolbox/data/空气开关/"                #保存路径
#获取待处理文件
files = glob(labelme_path + "*.json")
files = [i.split("/")[-1].split(".json")[0] for i in files]

#读取标注信息并写入 xml
for json_file_ in files:
    json_filename = labelme_path + json_file_ + ".json"
    json_file = json.load(open(json_filename, "r", encoding="utf-8"))
    height, width, channels = cv2.imread(labelme_path + json_file_ +".jpg").shape
    with codecs.open(saved_path + json_file_ + ".xml", "w", "utf-8") as xml:
        xml.write('\n')
        xml.write('\t' + 'UAV_data' + '\n')
        xml.write('\t' + json_file_ + ".jpg" + '\n')
        xml.write('\t\n')
        xml.write('\t\tThe UAV autolanding\n')
        xml.write('\t\tUAV AutoLanding\n')
        xml.write('\t\tflickr\n')
        xml.write('\t\tNULL\n')
        xml.write('\t\n')
        xml.write('\t\n')
        xml.write('\t\tNULL\n')
        xml.write('\t\tChaojieZhu\n')
        xml.write('\t\n')
        xml.write('\t\n')
        xml.write('\t\t'+ str(width) + '\n')
        xml.write('\t\t'+ str(height) + '\n')
        xml.write('\t\t' + str(channels) + '\n')
        xml.write('\t\n')
        xml.write('\t\t0\n')
        for multi in json_file["shapes"]:
            points = np.array(multi["points"])
            xmin = min(points[:,0])
            xmax = max(points[:,0])
            ymin = min(points[:,1])
            ymax = max(points[:,1])
            label = multi["label"]
            if xmax <= xmin:
                pass
            elif ymax <= ymin:
                pass
            else:
                xml.write('\t\n')
                xml.write('\t\t'+label+'\n')
                xml.write('\t\tUnspecified\n')
                xml.write('\t\t0\n')
                xml.write('\t\t0\n')
                xml.write('\t\t\n')
                xml.write('\t\t\t' + str(int(round(xmin))) + '\n')
                xml.write('\t\t\t' + str(int(round(ymin))) + '\n')
                xml.write('\t\t\t' + str(int(round(xmax))) + '\n')
                xml.write('\t\t\t' + str(int(round(ymax))) + '\n')
                xml.write('\t\t\n')
                xml.write('\t\n')
                print(json_filename, xmin, ymin, xmax, ymax, label)
        xml.write('')

 

你可能感兴趣的:(代码工具,深度学习)