labelme的json文件转YOLO的xml文件

前言

无论是模型只能标注还是labelme的标注, 生成的都是json文件.
但是在YOLO训练中, 使用的却是xml文件, 为此我们需要转换一下.

凯哥英语视频

labelme的json文件转YOLO的xml文件

一 转化代码

代码我自己跑过的, 绝对ok

# -*- coding: utf-8 -*-
import os
import numpy as np
import codecs
import json
import glob
import cv2
import shutil
from sklearn.model_selection import train_test_split

# 1.标签路径
labelme_path = "F:/rizhifuzhu/2021/202105/edit/j1_/j1_/"  # 原始labelme标注数据路径(存放了图片和json文件)
saved_path = "F:/rizhifuzhu/2021/202105/edit/j1_/VOC2007/"  # 保存路径

# 2.创建要求文件夹
dst_annotation_dir = os.path.join(saved_path, 'Annotations')
if not os.path.exists(dst_annotation_dir):
    os.makedirs(dst_annotation_dir)
dst_image_dir = os.path.join(saved_path, "JPEGImages")
if not os.path.exists(dst_image_dir):
    os.makedirs(dst_image_dir)
dst_main_dir = os.path.join(saved_path, "ImageSets", "Main")
if not os.path.exists(dst_main_dir):
    os.makedirs(dst_main_dir)

# 3.获取待处理文件
org_json_files = sorted(glob.glob(os.path.join(labelme_path, '*.json')))
org_json_file_names = [i.split("\\")[-1].split(".json")[0] for i in org_json_files]
org_img_files = sorted(glob.glob(os.path.join(labelme_path, '*.jpg')))
org_img_file_names = [i.split("\\")[-1].split(".jpg")[0] for i in org_img_files]

# 4.labelme file to voc dataset
for i, json_file_ in enumerate(org_json_files):
    json_file = json.load(open(json_file_, "r", encoding="utf-8"))
    image_path = os.path.join(labelme_path, org_json_file_names[i]+'.jpg')
    print(image_path)
    img = cv2.imread(image_path)
    height, width, channels = img.shape
    dst_image_path = os.path.join(dst_image_dir, "{:06d}.jpg".format(i))
    cv2.imwrite(dst_image_path, img)
    dst_annotation_path = os.path.join(dst_annotation_dir, '{:06d}.xml'.format(i))
    with codecs.open(dst_annotation_path, "w", "utf-8") as xml:
        xml.write('<annotation>\n')
        xml.write('\t<folder>' + 'Pin_detection' + '</folder>\n')
        xml.write('\t<filename>' + "{:06d}.jpg".format(i) + '</filename>\n')
        # xml.write('\t<source>\n')
        # xml.write('\t\t<database>The UAV autolanding</database>\n')
        # xml.write('\t\t<annotation>UAV AutoLanding</annotation>\n')
        # xml.write('\t\t<image>flickr</image>\n')
        # xml.write('\t\t<flickrid>NULL</flickrid>\n')
        # xml.write('\t</source>\n')
        # xml.write('\t<owner>\n')
        # xml.write('\t\t<flickrid>NULL</flickrid>\n')
        # xml.write('\t\t<name>ChaojieZhu</name>\n')
        # xml.write('\t</owner>\n')
        xml.write('\t<size>\n')
        xml.write('\t\t<width>' + str(width) + '</width>\n')
        xml.write('\t\t<height>' + str(height) + '</height>\n')
        xml.write('\t\t<depth>' + str(channels) + '</depth>\n')
        xml.write('\t</size>\n')
        xml.write('\t\t<segmented>0</segmented>\n')
        for multi in json_file["shapes"]:
            points = np.array(multi["points"])
            # 图片的像素中不存在小数, 强制int
            xmin = int(min(points[:, 0]))
            xmax = int(max(points[:, 0]))
            ymin = int(min(points[:, 1]))
            ymax = int(max(points[:, 1]))
            label = multi["label"]
            if xmax <= xmin:
                pass
            elif ymax <= ymin:
                pass
            else:
                xml.write('\t<object>\n')
                xml.write('\t\t<name>' + label + '</name>\n')
                xml.write('\t\t<pose>Unspecified</pose>\n')
                xml.write('\t\t<truncated>1</truncated>\n')
                xml.write('\t\t<difficult>0</difficult>\n')
                xml.write('\t\t<bndbox>\n')
                xml.write('\t\t\t<xmin>' + str(xmin) + '</xmin>\n')
                xml.write('\t\t\t<ymin>' + str(ymin) + '</ymin>\n')
                xml.write('\t\t\t<xmax>' + str(xmax) + '</xmax>\n')
                xml.write('\t\t\t<ymax>' + str(ymax) + '</ymax>\n')
                xml.write('\t\t</bndbox>\n')
                xml.write('\t</object>\n')
                print(json_file_, xmin, ymin, xmax, ymax, label)
        xml.write('</annotation>')

# 5.split files for txt
train_file = os.path.join(dst_main_dir, 'train.txt')
trainval_file = os.path.join(dst_main_dir, 'trainval.txt')
val_file = os.path.join(dst_main_dir, 'val.txt')
test_file = os.path.join(dst_main_dir, 'test.txt')

ftrain = open(train_file, 'w')
ftrainval = open(trainval_file, 'w')
fval = open(val_file, 'w')
ftest = open(test_file, 'w')

total_annotation_files = glob.glob(os.path.join(dst_annotation_dir, "*.xml"))
total_annotation_names = [i.split("\\")[-1].split(".xml")[0] for i in total_annotation_files]

# test_filepath = ""
for file in total_annotation_names:
    ftrainval.writelines(file + '\n')
# test
# for file in os.listdir(test_filepath):
#    ftest.write(file.split(".jpg")[0] + "\n")
# split
train_files, val_files = train_test_split(total_annotation_names, test_size=0.2)
# train
for file in train_files:
    ftrain.write(file + '\n')
# val
for file in val_files:
    fval.write(file + '\n')

ftrainval.close()
ftrain.close()
fval.close()
# ftest.close()


别的也没啥说的, 如果觉得 ok 就给我一键三连吧!

欢迎各位大佬留言吐槽,也可以深入交流~

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
要将labelme标注的数据换成yolo格式,可以按照以下步骤进行操作: 1. 确保已经安装好labelImg和labelme工具。 2. 打开labelImg工具,选择要标注的图像文件,并进行标注。标注完成后,会生成与图像文件同名的XML文件。 3. 使用labelme工具,将XML文件换成labelmejson文件。在labelme工具中,选择"File" -> "Open",然后选择XML文件,点击"Open"按钮。接着,选择"File" -> "Save As",将json文件保存在相同的目录下。 4. 下载并安装yolov5工具。 5. 创建一个文件夹,用于存放换后的数据。 6. 打开命令行终端,并进入到yolov5的代码目录。 7. 运行以下命令,将labelmejson文件换成yolo格式: ``` python labelme2yolo.py --json_path /path/to/json --output_path /path/to/output ``` 其中,/path/to/jsonjson文件所在的路径,/path/to/output是换后数据的输出路径。 8. 换完成后,会在输出路径下生成images和labels两个文件夹,分别存放换后的图像和标签文件。 现在,你已经成功将labelme标注的数据换成了yolo格式。你可以使用labelImg工具打开查看和编辑换后的数据。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [labelmeyolo工具使用教程jsontxt的yolo格式](https://blog.csdn.net/FL1623863129/article/details/129901336)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [labelme生成的标注数据换成yolov5格式](https://blog.csdn.net/athrunsunny/article/details/122132518)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

justwaityou1314

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值