本文主要是介绍【目标检测】COCO格式数据集转换为YOLO格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
COCO2YOLO, 修改category_mapping:
import json
import osdef coco_to_yolo(coco_annotation_file, output_dir):# Load COCO annotationswith open(coco_annotation_file, 'r') as f:coco_data = json.load(f)# Create a dictionary to map category_id to class_id# Reorder categories to match the desired YOLO indicescategory_mapping = {1: 0, # class 12: 1, # class 23: 2 # class 3}# Ensure output directory existsos.makedirs(output_dir, exist_ok=True)# Iterate through imagesfor img in coco_data['images']:img_id = img['id']img_width = img['width']img_height = img['height']annotations = [ann for ann in coco_data['annotations'] if ann['image_id'] == img_id]# Prepare the YOLO annotation contentyolo_annotations = []for ann in annotations:x, y, w, h = ann['bbox']x_center = (x + w / 2) / img_widthy_center = (y + h / 2) / img_heightw = w / img_widthh = h / img_heightcategory_id = ann['category_id']class_id = category_mapping[category_id]yolo_annotations.append(f"{class_id} {x_center} {y_center} {w} {h}")# Save YOLO annotations to a fileoutput_file = os.path.join(output_dir, f"{img['file_name'].split('.')[0]}.txt")with open(output_file, 'w') as f:f.write('\n'.join(yolo_annotations))# Usage example
coco_annotation_file = '/data/instances_val2017.json'
output_dir = '/data/yolo_annotations'
coco_to_yolo(coco_annotation_file, output_dir)
这篇关于【目标检测】COCO格式数据集转换为YOLO格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!