1、yolov8seg数据集txt文件的格式

格式:<class-index> <x1> <y1> <x2> <y2> ... <xn> <yn>

说明:每一行为一个目标,第一个数为类别索引,后面是每两个数为一组的点坐标。

2、json转txt

import json
import os


# 定义归一化函数
def normalize_points(points, image_width, image_height):
    normalized = []
    for x, y in points:
        normalized_x = x / image_width
        normalized_y = y / image_height
        normalized.append((normalized_x, normalized_y))
    return normalized


# 设置输入和输出文件夹路径
input_folder_path = r"C:\Users\admin\Desktop\segdatamake\json" # 请替换为你的输入文件夹路径
output_folder_path = r"C:\Users\admin\Desktop\segdatamake\txt"  # 请替换为你的输出文件夹路径

# 创建输出文件夹(如果不存在)
os.makedirs(output_folder_path, exist_ok=True)

# 遍历输入文件夹中的所有文件
for filename in os.listdir(input_folder_path):
    if filename.endswith('.json'):
        json_path = os.path.join(input_folder_path, filename)

        # 读取JSON文件
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        # 类别索引定义
        class_index = {
            "ChineseIDcard": 0  # 假设 "ChineseIDcard" 的类别索引为 0
        }

        # 获取图像的宽度和高度
        image_width = data['imageWidth']
        image_height = data['imageHeight']

        # 获取输出TXT文件的路径
        txt_filename = filename.replace('.json', '.txt')
        txt_path = os.path.join(output_folder_path, txt_filename)

        # 打开一个TXT文件用于写入
        with open(txt_path, 'w', encoding='utf-8') as f:
            for shape in data['shapes']:
                label = shape['label']
                points = shape['points']

                # 获取类别索引
                index = class_index.get(label, -1)  # 若未找到类别,返回 -1

                # 如果类别索引有效,写入TXT
                if index != -1:
                    # 归一化点坐标
                    normalized_points = normalize_points(points, image_width, image_height)

                    # 将类别索引和点坐标写入TXT文件
                    line = f"{index} " + " ".join([f"{x:.6f} {y:.6f}" for x, y in normalized_points]) + "\n"
                    f.write(line)

print("转换完成!")

###我主页的另一篇博客做了 制作和训练 自定义的yolov8seg数据集的全过程。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐