File size: 3,067 Bytes
f89df01 |
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 |
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):
# data path
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) |