File size: 3,913 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import json
import numpy as np
import os
import cv2
from datetime import datetime

def convert_to_coco(yolo_obb_dir, image_dir, save_json, categories, split="Train", author="None", version="1.0"):
    """
    yolo_obb_dir: Path to .txt files (class_id x1 y1 x2 y2 x3 y3 x4 y4)
    image_dir: Path to corresponding images
    save_json: Path to output coco file
    categories: List of strings ['bubble', ...]
    """
    
    coco_output = {
        "info": {
            "description": "TinyBubble Dataset",
            "version": version,
            "year": datetime.now().year,
            "split": split
        },
        "images": [],
        "annotations": [],
        "categories": [
            {"id": i, "name": cat, "supercategory": "none"} 
            for i, cat in enumerate(categories)
        ]
    }

    ann_id = 0
    img_id = 0

    if not os.path.exists(yolo_obb_dir):
        print(f"Directory {yolo_obb_dir} not found.")
        return

    for filename in os.listdir(yolo_obb_dir):
        if not filename.endswith(".txt"): continue
        
        img_base = os.path.splitext(filename)[0]
        image_name = None
        width, height = 0, 0
        
        for ext in ['.png', '.jpg', '.jpeg']:
            temp_path = os.path.join(image_dir, img_base + ext)
            if os.path.exists(temp_path):
                img = cv2.imread(temp_path)
                if img is not None:
                    height, width, _ = img.shape
                    image_name = img_base + ext
                    break
        
        if image_name is None:
            print(f"Warning: Image for {filename} not found in {image_dir}. Skipping.")
            continue

        coco_output["images"].append({
            "id": img_id,
            "file_name": image_name,
            "width": width,  
            "height": height 
        })

        with open(os.path.join(yolo_obb_dir, filename), "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])
                obb_coords = parts[1:]
                
                abs_coords = []
                for i in range(0, len(obb_coords), 2):
                    abs_coords.append(float(obb_coords[i] * width))
                    abs_coords.append(float(obb_coords[i+1] * height))

                points = np.array(abs_coords).reshape(4, 2)
                x_min, y_min = np.min(points, axis=0)
                x_max, y_max = np.max(points, axis=0)
                
                side_a = np.linalg.norm(points[0] - points[1])
                side_b = np.linalg.norm(points[1] - points[2])

                ann = {
                    "id": ann_id,
                    "image_id": img_id,
                    "category_id": class_id,
                    "segmentation": [abs_coords],
                    "area": float(side_a * side_b),
                    "bbox": [float(x_min), float(y_min), float(x_max - x_min), float(y_max - y_min)],
                    "iscrowd": 0
                }
                coco_output["annotations"].append(ann)
                ann_id += 1
        
        img_id += 1

    with open(save_json, "w") as f:
        json.dump(coco_output, f, indent=4)
    
    print(f"Successfully cleaned and saved {ann_id-1} annotations to {save_json}")

convert_to_coco(
    '../../../tinybubble/yolo_obb/train/labels', 
    '../../../tinybubble/yolo_obb/train/images', 
    '../../../tinybubble/coco/annotations/1.0_train_coco_obb.json', 
    ['bubble'],
    split="Train",
    version="1.0"
)

convert_to_coco(
    '../../../tinybubble/yolo_obb/val/labels', 
    '../../../tinybubble/yolo_obb/val/images', 
    '../../../tinybubble/coco/annotations/1.0_val_coco_obb.json', 
    ['bubble'],
    split="Val",
    version="1.0"
)