YOLO分割数据集转化(json转TXT)

一、数据集转化

python 复制代码
import json
import os
from tqdm import tqdm
import glob
import os.path as osp

def json_to_txt(jsonfilePath, resultDirPath):
    """
    jsonfilePath: labelme标注好的*.json文件所在文件夹
    resultDirPath: 转换好后的*.txt保存文件夹
    """

    class_names = []
    jsonfileList = glob.glob(osp.join(jsonfilePath, "*.json"))

    for jsonfile in tqdm(jsonfileList, desc='Processing'):
        with open(jsonfile, "r", encoding='UTF-8') as f:
            file_in = json.load(f)
            shapes = file_in["shapes"]
            txt_file = osp.join(resultDirPath, osp.basename(jsonfile).replace(".json", ".txt"))

            with open(txt_file, "w") as file_handle:
                for shape in shapes:
                    class_name = shape["label"]
                    if class_name not in class_names:
                        class_names.append(class_name)
                    class_id = class_names.index(class_name)

                    points = shape["points"]
                    normalized_points = [
                        f"{point[0] / file_in['imageWidth']} {point[1] / file_in['imageHeight']}"
                        for point in points
                    ]

                    file_handle.write(f"{class_id} {' '.join(normalized_points)}\n")

    with open(osp.join(resultDirPath, 'classes.txt'), 'w') as f:
        f.write('\n'.join(class_names))

if __name__ == "__main__":
    jsonfilePath = r"E:\241231数据扩充图片\标签"  # 要转换的json文件所在目录
    resultDirPath = r"D:\TXT"  # 要生成的txt文件夹
    json_to_txt(jsonfilePath=jsonfilePath, resultDirPath=resultDirPath)

二、TXT标签验证

验证转化后的的标签是否正确,代码如下:

python 复制代码
import os
import numpy as np
import cv2

IMG_FORMATS = ['.jpg', '.png', '.jpeg']
COLORS = [(0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128),
          (128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0), (192, 128, 0), (64, 0, 128), (192, 0, 128),
          (64, 128, 128), (192, 128, 128), (0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128),
          (128, 64, 12)]

def get_files(img_path, label_path):
    """
    获取图像和标签文件列表
    """
    img_list = [i for i in os.listdir(img_path) if os.path.splitext(i)[-1].lower() in IMG_FORMATS]
    label_list = [i.replace('.txt', '') for i in os.listdir(label_path) if i.endswith('.txt')]

    assert img_list, f"在 {img_path} 中未找到图像文件"
    assert label_list, f"在 {label_path} 中未找到标签文件"

    img_without_label = set(i.rsplit('.', 1)[0] for i in img_list) - set(label_list)
    if img_without_label:
        print(f"没有对应标签的图像: {list(img_without_label)}")

    ok_img = list(set(i.rsplit('.', 1)[0] for i in img_list) - img_without_label)
    return ok_img, os.path.splitext(img_list[0])[-1].lower()

def convert_and_draw(x, w, h, img):
    """
    转换坐标并绘制多边形和标签
    """
    label, *points = x
    points = np.array(points, dtype=np.float32).reshape(-1, 2) * [w, h]
    points = points.astype(np.int32)

    color = COLORS[int(label) % len(COLORS)]
    cv2.fillPoly(img, [points], color=color)
    cv2.putText(img, text=str(int(label)), org=tuple(points[0]), fontFace=cv2.FONT_HERSHEY_COMPLEX,
                fontScale=1, color=color, thickness=3)

    return img

def main(img_path, label_path, outfile, if_show, show_num):
    if os.path.isdir(img_path):
        ok_img, img_ext = get_files(img_path, label_path)
        for i, img_name in enumerate(ok_img, 1):
            img = cv2.imread(os.path.join(img_path, img_name + img_ext))
            h, w = img.shape[:2]
            with open(os.path.join(label_path, img_name + '.txt'), 'r') as f:
                labels = [x.split() for x in f.read().strip().splitlines()]
            for label in labels:
                img = convert_and_draw(label, w, h, img)
            if if_show:
                cv2.namedWindow('Image with label', cv2.WINDOW_NORMAL)
                cv2.imshow('Image with label', img)
                cv2.waitKey(0)
            if i == show_num:
                break
    else:
        img = cv2.imread(img_path)
        h, w = img.shape[:2]
        with open(label_path, 'r') as f:
            labels = [x.split() for x in f.read().strip().splitlines()]
        for label in labels:
            img = convert_and_draw(label, w, h, img)
        if if_show:
            cv2.namedWindow('Image with label', cv2.WINDOW_NORMAL)
            cv2.imshow('Image with label', img)
            cv2.waitKey(0)

if __name__ == '__main__':
    # 修改输入图片文件夹
    img_path = r"C:\Users\Admin\Desktop\ultralytics-8.2.87\datasets\coco8-seg\images\train/000000000034.jpg"
    # 修改输入标签文件夹
    label_path = r"C:\Users\Admin\Desktop\ultralytics-8.2.87\datasets\coco8-seg\labels\train/000000000034.txt"
    # 输出文件夹
    outfile = './'
    # 是否展示绘制的图片
    if_show = True
    # 最大展示图片的数量(按空格切换)
    show_num = 3

    main(img_path, label_path, outfile, if_show, show_num)

三、结果显示

收工!!

相关推荐
Coding茶水间22 分钟前
基于深度学习的花朵识别系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
开发语言·人工智能·深度学习·yolo·目标检测·机器学习
LeeeX!1 小时前
YOLOv13全面解析与安卓平台NCNN部署实战:超图视觉重塑实时目标检测的精度与效率边界
android·深度学习·yolo·目标检测·边缘计算
2501_941322031 小时前
叉车人员检测识别实战:基于YOLOv8-BiFPN的高精度目标检测方案
python·yolo·目标检测
li三河2 小时前
yolo进行剪枝、蒸馏、量化研究
算法·yolo·剪枝
Faker66363aaa3 小时前
煤矿杂质识别与分类---基于YOLOv5-FasterNet的目标检测系统实现
yolo·目标检测·分类
极智视界3 小时前
无人机场景 - 目标检测数据集 - 垂直视角车辆检测数据集下载
yolo·数据集·无人机·车辆检测·voc·coco·垂直视角
智驱力人工智能3 小时前
无人机目标检测 低空安全治理的工程实践与价值闭环 无人机缺陷识别 农业无人机作物长势分析系统 森林防火无人机火点实时识别
人工智能·opencv·安全·yolo·目标检测·无人机·边缘计算
2501_941652773 小时前
高速公路车辆检测与识别——基于YOLOv8与RFPN网络的智能监控系统_3
网络·yolo
wfeqhfxz25887823 小时前
基于YOLOv10n-CSP-PMSFA的大象检测与识别系统实践与优化
yolo
无人装备硬件开发爱好者3 小时前
RV1126B 边缘端 AI 实战:YOLOv8+DNTR 微小目标跟踪监测全栈实现 2
人工智能·yolo·目标跟踪