TiBuDB / tools /conversion /obb2coco.py
anonymous-submission-dataset-code's picture
Upload folder using huggingface_hub
9f22904 verified
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"
)