自建数据集json标签转yolo格式

发布于:2023-10-25 ⋅ 阅读:(81) ⋅ 点赞:(0)
import json
import os
from tqdm import tqdm

# 映射box到类别
box_to_id = {
    "Bodybox": 0,
    "Facebox": 1,
    "L_handbox": 2,
    "R_handbox": 2
}

def convert_to_yolo_format(data):
    width = 1280
    height = 720
    yolo_data = []

    for instance in data['instances']:
        boundingbox = instance['boundingbox']
        for box_name, box in boundingbox.items():
            if box:
                x_center = (box[0] + box[2]) / 2.0
                y_center = (box[1] + box[3]) / 2.0
                w = box[2] - box[0]
                h = box[3] - box[1]

                # Normalize
                x_center /= width
                y_center /= height
                w /= width
                h /= height

                yolo_data.append((box_to_id[box_name], x_center, y_center, w, h))

    return yolo_data

# Ensure 'yolo' folder exists
if not os.path.exists('yolo'):
    os.mkdir('yolo')

base_dir = "new_box"
# Count total JSON files for the progress bar
total_json_files = sum([len([f for f in os.listdir(os.path.join(base_dir, str(i), subfolder)) if f.endswith('.json')]) 
                        for i in range(1, 33) for subfolder in ["InterHand", "SingleHand"]])

# Using tqdm to create a progress bar for all JSON files
with tqdm(total=total_json_files) as pbar:
    for i in range(1, 33):
        folder_path = os.path.join(base_dir, str(i))
        for subfolder in ["InterHand", "SingleHand"]:
            initial = subfolder[0]
            json_files = [f for f in os.listdir(os.path.join(folder_path, subfolder)) if f.endswith('.json')]
            for json_file in json_files:
                with open(os.path.join(folder_path, subfolder, json_file), 'r') as f:
                    data = json.load(f)
                    yolo_data = convert_to_yolo_format(data)
                    output_filename = f"{i}_{initial}_{json_file.replace('.json', '.txt')}"
                    with open(os.path.join('yolo', output_filename), 'w') as yolo_file:
                        for item in yolo_data:
                            yolo_file.write(" ".join(map(str, item)) + "\n")
                pbar.update(1)

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到