Datasets:
Download visualization/videos/plot_frames.py from CVML-TueAI/grounding-YT-dataset: direct link, hf CLI and curl.
- Browser
- Download file 5.88 kB
-
https://huggingface.co/datasets/CVML-TueAI/grounding-YT-dataset/resolve/main/visualization/videos/plot_frames.py
- Command line
-
hf download hf://datasets/CVML-TueAI/grounding-YT-dataset/visualization/videos/plot_frames.py
-
curl -L -o plot_frames.py https://huggingface.co/datasets/CVML-TueAI/grounding-YT-dataset/resolve/main/visualization/videos/plot_frames.py
5.88 kB
| 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/videos/*.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 video" | |
| ) | |
| 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) | |
| for idx, frame_no in enumerate(anno_frames): #frame_no is string | |
| GT = next((anno for anno in meta['actions'] 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 / 'videos' / key | |
| 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() | |