Datasets:

Modalities:
Image
Text
Formats:
webdataset
ArXiv:
Libraries:
Datasets
WebDataset
License:
zxooh46@uni-tuebingen.de commited on
Commit
fd7d805
·
1 Parent(s): 0268768

Init video visualization

Browse files
visualization/videos/plot_frames.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import webdataset as wds
3
+ import io
4
+ import decord
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import glob
8
+ import cv2
9
+ from pathlib import Path
10
+ import concurrent.futures
11
+ import os
12
+ import argparse
13
+ import sys
14
+ from huggingface_hub import HfFileSystem, get_token, hf_hub_url
15
+
16
+ executor = concurrent.futures.ThreadPoolExecutor(
17
+ max_workers=None,
18
+ thread_name_prefix="JPG_Saver"
19
+ )
20
+
21
+ fs = HfFileSystem()
22
+ files = [fs.resolve_path(path) for path in fs.glob("hf://datasets/CVML-TueAI/grounding-YT-dataset/videos/*.tar")]
23
+ urls = [hf_hub_url(file.repo_id, file.path_in_repo, repo_type="dataset") for file in files]
24
+ urls = f"pipe: curl -s -L -H 'Authorization:Bearer {get_token()}' {'::'.join(urls)}"
25
+ PRED_FILE = 'random_preds.json'
26
+ OUTPUT_DIR = Path('./output_annotations')
27
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
28
+
29
+ def extract_frames_from_bytes(video_bytes, indices):
30
+ """
31
+ Parses video bytes and extracts a batch of frames.
32
+
33
+ """
34
+
35
+
36
+ try:
37
+ video_stream = io.BytesIO(video_bytes)
38
+ vr = decord.VideoReader(video_stream, ctx=decord.cpu(0))
39
+
40
+
41
+ frames = vr.get_batch(indices)
42
+
43
+
44
+ frames = frames.asnumpy()
45
+
46
+ return frames #(num_frames, H, W, 3)
47
+
48
+ except Exception as e:
49
+ print(f"Error decoding video with indices {indices}: {e}")
50
+ return None
51
+
52
+ def save_annotated_frame(image_array_rgb, bbox, point, gt_action, pred_action, output_path):
53
+
54
+ COLOR_GT = (0, 150, 0) # Green
55
+ COLOR_PRED = (0, 0, 255) # Red
56
+ COLOR_BOX = (255, 0, 0) # Blue
57
+ COLOR_POINT = (0, 0, 255) # Red
58
+
59
+ if gt_action == pred_action:
60
+ COLOR_PRED = (0, 150, 0) # Make prediction green if correct
61
+
62
+ TOP_PADDING = 70 # Pixels to add for the title header
63
+ TEXT_OFFSET_X = 10
64
+
65
+ image_bgr = cv2.cvtColor(image_array_rgb, cv2.COLOR_RGB2BGR)
66
+ h, w = image_bgr.shape[:2]
67
+
68
+ final_image = np.full((h + TOP_PADDING, w, 3), 255, dtype=np.uint8)
69
+ final_image[TOP_PADDING : h + TOP_PADDING, 0:w] = image_bgr
70
+
71
+ cv2.putText(
72
+ final_image,
73
+ f"Ground Truth: {gt_action}",
74
+ (TEXT_OFFSET_X, 30), # Position (x, y)
75
+ cv2.FONT_HERSHEY_SIMPLEX, # Font
76
+ 0.8, # Font scale
77
+ COLOR_GT, # Color
78
+ 2 # Thickness
79
+ )
80
+ cv2.putText(
81
+ final_image,
82
+ f"Prediction: {str(pred_action)}", #Because pred_action can be None if not present
83
+ (TEXT_OFFSET_X, 60), # Position (x, y)
84
+ cv2.FONT_HERSHEY_SIMPLEX,
85
+ 0.8,
86
+ COLOR_PRED,
87
+ 2
88
+ )
89
+
90
+ # Bounding Box
91
+ x_min, y_min, x_max, y_max = [int(coord) for coord in bbox] # Get coordinates
92
+
93
+ # Top-left corner (x1, y1)
94
+ pt1 = (x_min, y_min + TOP_PADDING)
95
+ # Bottom-right corner (x2, y2)
96
+ pt2 = (x_max, y_max + TOP_PADDING)
97
+
98
+ cv2.rectangle(
99
+ final_image,
100
+ pt1,
101
+ pt2,
102
+ COLOR_BOX,
103
+ thickness=2
104
+ )
105
+
106
+ # Point
107
+ a, b = point
108
+ pt_center = (a, b + TOP_PADDING)
109
+
110
+ #Dot
111
+ cv2.circle(
112
+ final_image,
113
+ pt_center,
114
+ radius=3,
115
+ color=COLOR_POINT,
116
+ thickness=-1
117
+ )
118
+
119
+ #Outer cirlce
120
+ cv2.circle(
121
+ final_image,
122
+ pt_center,
123
+ radius=10,
124
+ color=(255, 255, 255),
125
+ thickness=2
126
+ )
127
+
128
+ cv2.imwrite(output_path, final_image, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
129
+ print(f"Saved annotated image to {output_path}")
130
+
131
+
132
+ def main():
133
+ dataset = (
134
+ wds.WebDataset(urls, shardshuffle=False)
135
+ .decode()
136
+ .to_tuple("__key__","mp4", "json")
137
+ )
138
+
139
+ parser = argparse.ArgumentParser()
140
+
141
+ parser.add_argument(
142
+ "--predictions", type=str, required=True, help="Path to json file with predictions for each video"
143
+ )
144
+
145
+ args = parser.parse_args()
146
+
147
+ with open(args.predictions, 'r', encoding='utf-8') as f:
148
+ preds = json.load(f)
149
+
150
+ for key, video_bytes, meta in dataset:
151
+ if preds.get(key) is not None: #video predictions present
152
+ anno_frames = list(preds[key].keys()) #list of strings, convert to int when using
153
+ video_frames = extract_frames_from_bytes(video_bytes, [int(f) for f in anno_frames])
154
+ assert(len(anno_frames) == video_frames.shape[0])
155
+ #print(meta)
156
+ #print(meta['actions'][0].keys())
157
+ #print(video_frames.shape)
158
+
159
+ for idx, frame_no in enumerate(anno_frames): #frame_no is string
160
+
161
+ GT = next((anno for anno in meta['actions'] if anno.get('frame') == int(frame_no)), None)
162
+ #print(GT) #{'step_name': 'crack eggs', 'box': [209, 0, 413, 203], 'frame': 1427}
163
+
164
+ if GT is None:
165
+ print(f'Ground truth annotation not found for frame {frame_no}')
166
+ continue
167
+
168
+ pred_point = preds[key].get(str(frame_no)).get('point')
169
+ pred_action = preds[key].get(str(frame_no)).get('action')
170
+
171
+ output_dir = OUTPUT_DIR / 'videos' / key
172
+ output_dir.mkdir(parents=True, exist_ok=True)
173
+ output_img = output_dir / f'{key}_{frame_no}.jpg'
174
+
175
+ #image_array_rgb, bbox, point, gt_action, pred_action, output_path
176
+ executor.submit(
177
+ save_annotated_frame,
178
+ image_array_rgb=video_frames[idx],
179
+ bbox=GT['box'],
180
+ point = pred_point,
181
+ gt_action=GT['step_name'],
182
+ pred_action = pred_action,
183
+ output_path = output_img
184
+ )
185
+
186
+ print("Main loop finished. Waiting for file saving to complete...")
187
+ executor.shutdown(wait=True)
188
+ print("All files saved.")
189
+
190
+ if __name__ == '__main__':
191
+ main()
192
+
193
+
visualization/videos/random_preds.json ADDED
The diff for this file is too large to render. See raw diff