import json
def convert_coco_to_yolo(coco_data, image_width, image_height):
yolo_data = {}
yolo_data['categories'] = coco_data['categories']
image_annos = {}
for anno in coco_data['annotations']:
image_id = anno['image_id']
if image_id not in image_annos:
image_annos[image_id] = []
image_annos[image_id].append(anno)
yolo_data['annotations'] = []
for image_id, annos in image_annos.items():
file_name = f'{image_id}.txt'
with open(file_name, 'w') as f:
for anno in annos:
x, y, w, h = anno['bbox']
# x_center = x + w / 2
# y_center = y + h / 2
# width = w
# height = h
# category_id = anno['category_id']
# line = f'{category_id} {x_center} {y_center} {width} {height}\n'
# f.write(line)
x_center = (x + w / 2) / image_width
y_center = (y + h / 2) / image_height
width = w / image_width
height = h / image_height
category_id = anno['category_id']
line = f'{category_id} {x_center} {y_center} {width} {height}\n'
f.write(line)
yolo_data['annotations'].append({'image_id': image_id, 'file_name': file_name})
return yolo_data
image_width = 640
image_height = 640
# 使用示例
with open(r'D:\yolov5-seg\coco_dataset.json', 'r') as f:
coco_data = json.load(f)
yolo_data = convert_coco_to_yolo(coco_data, image_width, image_height)
print(json.dumps(yolo_data, indent=4))
import json
import os
yolo_dataset = {
"categories": [
{"id": 0, "name": "body", "supercategory": "mark"},
{"id": 1, "name": "head", "supercategory": "mark"}
],
"annotations": [],
"images": []
}
def convert_yolo_to_coco(data_folder):
image_id = 0
image_folder = os.path.join(data_folder, 'images')
label_folder = os.path.join(data_folder, 'labels')
image_files = os.listdir(image_folder)
label_files = os.listdir(label_folder)
for image_file in image_files:
if image_file.endswith(".jpg"):
image_id += 1
label_file = os.path.join(label_folder, f"{image_file.split('.')[0]}.txt")
with open(label_file, 'r') as f:
for line in f.readlines():
data = line.strip().split(' ')
category_id = int(data[0])
x, y, w, h = map(float, data[1:])
xmin = int((x - w / 2) * 640)
ymin = int((y - h / 2) * 640)
xmax = int((x + w / 2) * 640)
ymax = int((y + h / 2) * 640)
print(x, y, w, h, xmin, ymin)
width = xmax - xmin
height = ymax - ymin
area = width * height
annotation = {
"id": len(yolo_dataset["annotations"]),
"image_id": image_id,
"category_id": category_id,
"bbox": [xmin, ymin, width, height],
"area": area,
"iscrowd": 0,
"segmentation": [[xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax]]
}
yolo_dataset["annotations"].append(annotation)
coco_image_file = os.path.join(image_folder, image_file)
image = {
"id": image_id,
"file_name": coco_image_file,
"width": 640, # 替换为实际图像宽度
"height": 640 # 替换为实际图像高度
}
yolo_dataset["images"].append(image)
# 示例用法
convert_yolo_to_coco(r'E:\cfdata\test')
# 保存COCO数据集为JSON文件
with open('coco_dataset.json', 'w') as f:
json.dump(yolo_dataset, f)