Datasets:

Modalities:
Image
Text
Formats:
webdataset
ArXiv:
Libraries:
Datasets
WebDataset
License:
File size: 5,933 Bytes
feeac65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import json
import webdataset as wds
import io
import decord
import numpy as np
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/clips/*.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 extract_frames_from_bytes(video_bytes, indices):
    """
    Parses video bytes and extracts a batch of frames.
    
    """


    try:
        video_stream = io.BytesIO(video_bytes)
        vr = decord.VideoReader(video_stream, ctx=decord.cpu(0))

        
        frames = vr.get_batch(indices)

        
        frames = frames.asnumpy()
        
        return frames #(num_frames, H, W, 3)

    except Exception as e:
        print(f"Error decoding video with indices {indices}: {e}")
        return None

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()
    .to_tuple("__key__","mp4", "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, video_bytes, meta in dataset: 
        if preds.get(key) is not None: #video predictions present
            anno_frames = list(preds[key].keys()) #list of strings, convert to int when using
            video_frames = extract_frames_from_bytes(video_bytes, [int(f) for f in anno_frames])
            assert(len(anno_frames) == video_frames.shape[0])
            #print(meta)
            #print(meta['actions'][0].keys())
            #print(video_frames.shape)
            video_name = meta[0].get('video')
    
            for idx, frame_no in enumerate(anno_frames): #frame_no is string
                
                GT = next((anno for anno in meta if anno.get('frame') == int(frame_no)), None)
                #print(GT) #{'step_name': 'crack eggs', 'box': [209, 0, 413, 203], 'frame': 1427}
                
                if GT is None:
                    print(f'Ground truth annotation not found for frame {frame_no}')
                    continue
                    
                pred_point = preds[key].get(str(frame_no)).get('point')
                pred_action = preds[key].get(str(frame_no)).get('action')
    
                output_dir = OUTPUT_DIR / 'clips' / video_name
                output_dir.mkdir(parents=True, exist_ok=True)
                output_img = output_dir / f'{key}_{frame_no}.jpg'
    
                #image_array_rgb, bbox, point, gt_action, pred_action, output_path
                executor.submit(
                    save_annotated_frame,
                    image_array_rgb=video_frames[idx],
                    bbox=GT['box'],
                    point = pred_point,
                    gt_action=GT['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()