Datasets:

Modalities:
Image
Text
Formats:
webdataset
ArXiv:
Libraries:
Datasets
WebDataset
License:
File size: 4,859 Bytes
b67123c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import json
import webdataset as wds
import io
import decord
import numpy as np
import torch
import matplotlib.pyplot as plt
import glob
import cv2
from pathlib import Path
import concurrent.futures
import os
import argparse
import sys
from huggingface_hub import HfFileSystem, get_token, hf_hub_url

executor = concurrent.futures.ThreadPoolExecutor(
    max_workers=None, 
    thread_name_prefix="JPG_Saver"
)

fs = HfFileSystem()
files = [fs.resolve_path(path) for path in fs.glob("hf://datasets/CVML-TueAI/grounding-YT-dataset/frames/*.tar")]
urls = [hf_hub_url(file.repo_id, file.path_in_repo, repo_type="dataset") for file in files]
urls = f"pipe: curl -s -L -H 'Authorization:Bearer {get_token()}' {'::'.join(urls)}"
PRED_FILE = 'random_preds.json'
OUTPUT_DIR = Path('./output_annotations')
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

def save_annotated_frame(image_array_rgb, bbox, point, gt_action, pred_action, output_path):

    COLOR_GT = (0, 150, 0)      # Green
    COLOR_PRED = (0, 0, 255)    # Red 
    COLOR_BOX = (255, 0, 0)     # Blue
    COLOR_POINT = (0, 0, 255)   # Red

    if gt_action == pred_action:
        COLOR_PRED = (0, 150, 0) # Make prediction green if correct

    TOP_PADDING = 70  # Pixels to add for the title header
    TEXT_OFFSET_X = 10

    image_bgr = cv2.cvtColor(image_array_rgb, cv2.COLOR_RGB2BGR)
    h, w = image_bgr.shape[:2]

    final_image = np.full((h + TOP_PADDING, w, 3), 255, dtype=np.uint8)
    final_image[TOP_PADDING : h + TOP_PADDING, 0:w] = image_bgr

    cv2.putText(
        final_image,
        f"Ground Truth: {gt_action}",
        (TEXT_OFFSET_X, 30),             # Position (x, y)
        cv2.FONT_HERSHEY_SIMPLEX,        # Font
        0.8,                             # Font scale
        COLOR_GT,                        # Color
        2                                # Thickness
    )
    cv2.putText(
        final_image,
        f"Prediction: {str(pred_action)}", #Because pred_action can be None if not present
        (TEXT_OFFSET_X, 60),             # Position (x, y)
        cv2.FONT_HERSHEY_SIMPLEX,
        0.8,
        COLOR_PRED,
        2
    )
    
    # Bounding Box
    x_min, y_min, x_max, y_max = [int(coord) for coord in bbox] # Get coordinates
    
    # Top-left corner (x1, y1)
    pt1 = (x_min, y_min + TOP_PADDING)
    # Bottom-right corner (x2, y2)
    pt2 = (x_max, y_max + TOP_PADDING)
    
    cv2.rectangle(
        final_image, 
        pt1, 
        pt2, 
        COLOR_BOX, 
        thickness=2
    )
    
    # Point
    a, b = point
    pt_center = (a, b + TOP_PADDING)

    #Dot
    cv2.circle(
        final_image,
        pt_center,
        radius=3,
        color=COLOR_POINT,
        thickness=-1 
    )

    #Outer cirlce
    cv2.circle(
        final_image,
        pt_center,
        radius=10,       
        color=(255, 255, 255),
        thickness=2        
    )

    cv2.imwrite(output_path, final_image, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
    print(f"Saved annotated image to {output_path}")
    
    
def main():
    
    dataset = (
    wds.WebDataset(urls, shardshuffle=False)
    .decode('torchrgb')
    .to_tuple("__key__","jpg", "json")
    )

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--predictions", type=str, required=True, help="Path to json file with predictions for each clip"
    )

    args = parser.parse_args()

    with open(args.predictions, 'r', encoding='utf-8') as f:
        preds = json.load(f)
    
    for key, image_tensor, meta in dataset: 
    
        frame_no = meta['frame'] #int
        video_name = meta['video']
        if preds.get(key) is not None: #frame prediction present
    
            image_hwc = image_tensor.permute(1,2,0) #image_tensor is [C,H,W] -> change to [H,W,C]
            image_scaled = image_hwc * 255.0 #int pixel values
            image_numpy_uint8 = image_scaled.numpy().astype(np.uint8) #change from tensor to numpy 
                
            pred_point = preds[key].get(str(frame_no)).get('point')
            pred_action = preds[key].get(str(frame_no)).get('action')
    
            output_dir = OUTPUT_DIR / 'frames' / video_name
            output_dir.mkdir(parents=True, exist_ok=True)
            output_img = output_dir / f'{key}.jpg'
    
            #image_array_rgb, bbox, point, gt_action, pred_action, output_path
            executor.submit(
                save_annotated_frame,
                image_array_rgb=image_numpy_uint8,
                bbox=meta['box'],
                point = pred_point,
                gt_action=meta['step_name'],
                pred_action = pred_action,
                output_path = output_img
            )
    
    print("Main loop finished. Waiting for file saving to complete...")
    executor.shutdown(wait=True)
    print("All files saved.")




if __name__ == '__main__':
    main()