import os import json import cv2 import numpy as np # Paths FRAMES_DIR = "test_frame" GT_DIR = "GT" OUT_PATH = "annotations" os.makedirs(OUT_PATH, exist_ok=True) # Output COCO-style JSON out_file = os.path.join(OUT_PATH, "train.json") out = { "images": [], "annotations": [], "videos": [], "categories": [ {"id": 1, "name": "pedestrian"} # You can expand with more classes if needed ] } image_cnt = 0 ann_cnt = 0 video_cnt = 0 tid_curr = 0 tid_last = -1 # Loop over sequences (one per video) for seq in sorted(os.listdir(FRAMES_DIR)): seq_path = os.path.join(FRAMES_DIR, seq) if not os.path.isdir(seq_path): continue video_cnt += 1 out["videos"].append({"id": video_cnt, "file_name": seq}) # Frames images = sorted([f for f in os.listdir(seq_path) if f.endswith(".jpg")]) num_images = len(images) for i, img_name in enumerate(images): img_path = os.path.join(seq_path, img_name) img = cv2.imread(img_path) if img is None: continue height, width = img.shape[:2] image_info = { "file_name": f"{seq}/{img_name}", "id": image_cnt + i + 1, "frame_id": i + 1, "prev_image_id": image_cnt + i if i > 0 else -1, "next_image_id": image_cnt + i + 2 if i < num_images - 1 else -1, "video_id": video_cnt, "height": height, "width": width } out["images"].append(image_info) # Load GT file gt_path = os.path.join(GT_DIR, seq, "gt", "gt.txt") if not os.path.exists(gt_path): print(f" No GT found for {seq}, skipping annotations.") image_cnt += num_images continue anns = np.loadtxt(gt_path, dtype=np.float32, delimiter=",") for i in range(anns.shape[0]): frame_id = int(anns[i][0]) track_id = int(anns[i][1]) x, y, w, h = anns[i][2:6] conf = anns[i][6] class_id = int(anns[i][7]) visibility = anns[i][8] ann_cnt += 1 if track_id != tid_last: tid_curr += 1 tid_last = track_id ann = { "id": ann_cnt, "category_id": class_id, "image_id": image_cnt + frame_id, "track_id": tid_curr, "bbox": [float(x), float(y), float(w), float(h)], "conf": float(conf), "iscrowd": 0, "area": float(w * h), } out["annotations"].append(ann) image_cnt += num_images print(f" Loaded {len(out['images'])} images and {len(out['annotations'])} annotations.") # Save JSON with open(out_file, "w") as f: json.dump(out, f) print(f" Saved COCO-style annotations to {out_file}")