| | import os |
| | import json |
| | import torch |
| | import numpy as np |
| | from tqdm import tqdm |
| |
|
| | from typing import List |
| |
|
| | from utils import heatmap_interpolation, video_interpolation |
| |
|
| |
|
| | class HeatmapAnalyzer: |
| | def __init__(self, data_root: str, model: str, heatmap_thresholds: List, benchmark_path: str, \ |
| | height: int=360, width: int=640, frame_sample_rate: int=8, video: bool=True): |
| | |
| | |
| | self.data_root = data_root |
| | self.model = model |
| | self.benchmark_path = benchmark_path |
| | |
| | self.height = height |
| | self.width = width |
| | self.frame_sample_rate = frame_sample_rate |
| | self.heatmap_thresholds = heatmap_thresholds |
| |
|
| | self.video = video |
| |
|
| |
|
| | def compute(self): |
| | data_path = os.path.join(self.data_root, self.model, "heatmap") |
| | save_path = os.path.join(self.data_root, self.model, "heatmap_threshold.json") |
| | |
| | print(f"Calculating {'Video' if self.video else 'Image'} Heatmap") |
| | total_val = self.compute_for_video(data_path) if self.video else self.compute_for_image(data_path) |
| |
|
| | heatmap_threshold = self.cal_heatmap_threshold(np.array(total_val)) |
| | self.save_heatmap_threshold(save_path, heatmap_threshold) |
| |
|
| |
|
| | def compute_for_image(self, data_path): |
| | total_val = [] |
| |
|
| | for data_file in tqdm(os.listdir(data_path)): |
| | if not data_file.endswith(".npy"): |
| | continue |
| | |
| | infer = torch.tensor(np.load(os.path.join(data_path, data_file))).unsqueeze(0).unsqueeze(0) |
| | infer = heatmap_interpolation(infer, self.height, self.width) |
| | total_val.append(infer) |
| | |
| | return total_val |
| |
|
| | |
| | def compute_for_video(self, data_path): |
| | total_val = [] |
| |
|
| | for data_file in tqdm(os.listdir(data_path)): |
| | if not data_file.endswith(".npy"): |
| | continue |
| | |
| | video_id = data_file.split(".")[0] |
| | metadata_path = os.path.join(self.benchmark_path, video_id) |
| | |
| | infer = torch.tensor(np.load(os.path.join(data_path, data_file))) |
| | infer = video_interpolation(infer, self.frame_sample_rate) |
| | |
| | for frame_data in os.listdir(metadata_path): |
| | if frame_data.endswith(".jpg"): |
| | continue |
| |
|
| | frame_num = int(frame_data.split(".")[0].split("_")[-1]) |
| | infer_map = infer[frame_num].unsqueeze(0) |
| | infer_map = heatmap_interpolation(infer_map, self.height, self.width) |
| | total_val.append(infer_map) |
| |
|
| | return total_val |
| |
|
| | |
| | def cal_heatmap_threshold(self, total_heatmap: np.ndarray): |
| | sorted_data = np.sort(total_heatmap, axis=None)[::-1] |
| | result = dict() |
| | for thr in self.heatmap_thresholds: |
| | result[thr] = float(sorted_data[int(len(sorted_data) * thr)]) |
| | return result |
| | |
| |
|
| | def save_heatmap_threshold(self, save_path: str, result: dict): |
| | with open(save_path, 'w') as f: |
| | json.dump(result, f, indent=4) |