| import json |
| import os |
| import cv2 |
| import numpy as np |
| from datetime import datetime |
|
|
| def yolo_to_coco(image_dir, label_dir, output_json, split="Train", author="Noone", version="1.0"): |
| coco = { |
| "info": { |
| "description": "TinyBubble Dataset", |
| "url": "", |
| "version": version, |
| "split": split, |
| "year": datetime.now().year, |
| }, |
| "images": [], |
| "annotations": [], |
| "categories": [{"id": 0, "name": "bubble", "supercategory": "none"}] |
| } |
|
|
| ann_id = 0 |
| image_id = 0 |
|
|
| for img_file in os.listdir(image_dir): |
| if not img_file.endswith(('.png', '.jpg', '.jpeg','.tiff','.tif')): |
| continue |
|
|
| img_path = os.path.join(image_dir, img_file) |
| img = cv2.imread(img_path) |
| if img is None: continue |
| height, width, _ = img.shape |
|
|
| coco["images"].append({ |
| "id": image_id, |
| "file_name": img_file, |
| "width": width, |
| "height": height |
| }) |
|
|
| label_file = os.path.splitext(img_file)[0] + ".txt" |
| label_path = os.path.join(label_dir, label_file) |
|
|
| if os.path.exists(label_path): |
| with open(label_path, 'r') as f: |
| lines = list(dict.fromkeys([line.strip() for line in f.readlines() if line.strip()])) |
| |
| for line in lines: |
| parts = list(map(float, line.split())) |
| class_id = int(parts[0]) |
| coords = parts[1:] |
|
|
| abs_coords = [] |
| for i in range(0, len(coords), 2): |
| abs_coords.append(coords[i] * width) |
| abs_coords.append(coords[i+1] * height) |
|
|
| xs = abs_coords[0::2] |
| ys = abs_coords[1::2] |
| x1, y1, x2, y2 = min(xs), min(ys), max(xs), max(ys) |
| bbox = [x1, y1, x2 - x1, y2 - y1] |
| |
| area = cv2.contourArea(np.array(abs_coords).reshape(-1, 2).astype(np.float32)) |
|
|
| coco["annotations"].append({ |
| "id": ann_id, |
| "image_id": image_id, |
| "category_id": class_id, |
| "segmentation": [abs_coords], |
| "area": area, |
| "bbox": bbox, |
| "iscrowd": 0 |
| }) |
| ann_id += 1 |
| |
| image_id += 1 |
|
|
| with open(output_json, 'w') as f: |
| json.dump(coco, f, indent=4) |
| print(f"COCO annotation saved as: {output_json}") |
|
|
|
|
| yolo_to_coco( |
| image_dir="../../../tinybubble/yolo_seg/train/images", |
| label_dir="../../../tinybubble/yolo_seg/train/labels", |
| output_json="../../../tinybubble/coco/annotations/1.0_train_coco.json", |
| split="Train", |
| version="1.0" |
| ) |
|
|
| yolo_to_coco( |
| image_dir="../../../tinybubble/yolo_seg/val/images", |
| label_dir="../../../tinybubble/yolo_seg/val/labels", |
| output_json="../../../tinybubble/coco/annotations/1.0_val_coco.json", |
| split="Val", |
| version="1.0" |
| ) |