Spaces:
Running
Running
| import cv2 | |
| import multiprocessing as mp | |
| BASE_IMG_SIZE = 640 | |
| REF_PIXELS = 640 * 640 | |
| REF_FPS_CPU = 13.0 | |
| TRACK_STABILITY_STRIDE = 3 | |
| def _cpu_score(): | |
| return mp.cpu_count() | |
| def _video_meta(path): | |
| cap = cv2.VideoCapture(path) | |
| fps = cap.get(cv2.CAP_PROP_FPS) | |
| frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
| h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
| cap.release() | |
| duration = frames / fps if fps else 0 | |
| pixels = w * h | |
| return fps, frames, duration, w, h, pixels | |
| def _estimate_fps(imgsz, cpu_score): | |
| scale = (imgsz * imgsz) / REF_PIXELS | |
| return (REF_FPS_CPU * cpu_score / 12) / scale | |
| def _select_imgsz(pixels): | |
| if pixels >= 3840 * 2160: | |
| return 640 | |
| if pixels >= 2560 * 1440: | |
| return 704 | |
| if pixels >= 1920 * 1080: | |
| return 736 | |
| if pixels >= 1280 * 720: | |
| return 800 | |
| return 960 | |
| def _select_stride(video_fps, model_fps): | |
| if model_fps >= video_fps: | |
| return 1 | |
| ratio = video_fps / model_fps | |
| stride = int(round(ratio)) | |
| return max(1, min(stride, TRACK_STABILITY_STRIDE)) | |
| def get_optimal_config(video_path): | |
| fps, frames, duration, w, h, pixels = _video_meta(video_path) | |
| cpu_score = _cpu_score() | |
| imgsz = _select_imgsz(pixels) | |
| model_fps = _estimate_fps(imgsz, cpu_score) | |
| detect_stride = _select_stride(fps, model_fps) | |
| effective_fps = model_fps / detect_stride | |
| realtime_possible = effective_fps >= fps | |
| return { | |
| "video_fps": fps, | |
| "frames": frames, | |
| "duration": round(duration, 2), | |
| "resolution": [w, h], | |
| "pixels": pixels, | |
| "cpu_score": cpu_score, | |
| "imgsz": imgsz, | |
| "detect_stride": detect_stride, | |
| "model_fps_est": round(model_fps, 2), | |
| "effective_fps_est": round(effective_fps, 2), | |
| "realtime_possible": realtime_possible | |
| } | |