COCO-wholebody标签json转yolo格式
我只保存了人体,面部,双手(区分)
# -*- coding: utf-8 -*-
import os
import json
from tqdm import tqdm
# 修改为您的COCO WholeBody标注文件路径
coco_annotation_file = 'coco_wholebody_train_v1.0.json'
output_folder = ''# 输出路径
# 读取COCO标注文件
with open(coco_annotation_file, 'r') as f:
data = json.load(f)
# 从categories字段获取person类别的ID
person_category_id = next(cat['id'] for cat in data['categories'] if cat['name'] == 'person')
# 定义子类别ID
BODY_SUBCLASS_ID = 0
FACE_SUBCLASS_ID = 1
LEFT_HAND_SUBCLASS_ID = 2
RIGHT_HAND_SUBCLASS_ID = 3
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 使用tqdm包装循环以显示进度条
for annotation in tqdm(data['annotations'], desc="Processing annotations", dynamic_ncols=True):
if annotation['category_id'] != person_category_id:
continue
img_id = annotation['image_id']
# 获取边界框信息
body_bbox = annotation['bbox']
face_bbox = annotation["face_box"]
left_hand_bbox = annotation["lefthand_box"]
right_hand_bbox = annotation["righthand_box"]
# 获取图像信息以获得宽度和高度
img_data = next(filter(lambda i: i['id'] == img_id, data['images']))
img_width, img_height = img_data['width'], img_data['height']
# 转换并保存YOLO格式的标注
filename = str(img_id).zfill(12) + '.txt'# 按图片名命名,其余用0填充
with open(os.path.join(output_folder, filename), 'a') as file:
for subclass_id, bbox in zip(
[BODY_SUBCLASS_ID, FACE_SUBCLASS_ID, LEFT_HAND_SUBCLASS_ID, RIGHT_HAND_SUBCLASS_ID],
[body_bbox, face_bbox, left_hand_bbox, right_hand_bbox]):
x_center = bbox[0] + bbox[2] / 2
y_center = bbox[1] + bbox[3] / 2
# 归一化坐标
x_center /= img_width
y_center /= img_height
normalized_width = bbox[2] / img_width
normalized_height = bbox[3] / img_height
# 检查归一化的宽度和高度是否大于0,如果是,再保存
if normalized_width > 0 and normalized_height > 0:
file.write(f"{subclass_id} {x_center} {y_center} {normalized_width} {normalized_height}\n")
本人测试没问题,可以进行训练