File size: 3,130 Bytes
9f22904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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"
)