Open1

COCO-Hand データセットのアノテーションデータをMS-COCOフォーマットへ変換

PINTOPINTO
  • COCO-Hand
# フォーマット
[image_name, xmin, xmax, ymin, ymax, x1, y1, x2, y2, x3, y3, x4, y4]

# 実際の値
000000001098.jpg,134,190,160,188,138,160,134,178,186,188,190,169,hand
000000001098.jpg,234,288,187,242,265,187,234,200,257,242,288,230,hand
000000000036.jpg,215,257,208,257,230,257,257,254,242,208,215,210,hand
import json

# アノテーションファイルからデータを読み込む
with open("COCO-Hand-S_annotations.txt", "r") as f:
    lines = f.readlines()

# 画像の情報とアノテーションの情報を格納するリスト
images = []
annotations = []

# 画像IDとアノテーションIDのトラッキングのための変数
image_id_counter = 0
annotation_id_counter = 0
image_id_map = {}

for line in lines:
    line = line.strip()
    image_name, xmin, xmax, ymin, ymax, x1, y1, x2, y2, x3, y3, x4, y4, label = line.split(',')
    
    # 画像IDを取得または生成
    if image_name not in image_id_map:
        image_id_map[image_name] = image_id_counter
        image_id_counter += 1
        images.append({
            "id": image_id_map[image_name],
            "file_name": image_name,
            # 画像の実際のwidthとheightが不明なので、とりあえずプレースホルダーを設定
            "width": 0,
            "height": 0
        })
        
    # アノテーション情報を格納
    annotations.append({
        "id": annotation_id_counter,
        "image_id": image_id_map[image_name],
        "bbox": [int(xmin), int(ymin), int(xmax) - int(xmin), int(ymax) - int(ymin)],
        "keypoints": [
            int(x1), int(y1), 2, 
            int(x2), int(y2), 2, 
            int(x3), int(y3), 2, 
            int(x4), int(y4), 2
        ],
        "num_keypoints": 4,
        "category_id": 1  # "hand"に対応するカテゴリID
    })
    annotation_id_counter += 1

# カテゴリ情報を格納
categories = [{"id": 1, "name": "hand"}]

coco_format = {
    "images": images,
    "annotations": annotations,
    "categories": categories
}

with open("COCO-Hand-S_annotations.json", "w") as output:
    json.dump(coco_format, output)