From 9a0b224ffb37e0716e0f1084d1f1cd90e30cd5c5 Mon Sep 17 00:00:00 2001 From: Peter Roch Date: Tue, 3 Jun 2025 15:17:26 +0200 Subject: [PATCH] WIP for speed estimation --- analyzer.py | 67 +++++++++++++++++++++++++++++++++++++++- main.py | 88 ++++++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 137 insertions(+), 18 deletions(-) diff --git a/analyzer.py b/analyzer.py index 8125b38..895e358 100644 --- a/analyzer.py +++ b/analyzer.py @@ -69,12 +69,77 @@ class Analyzer: cv2.imshow("Detected Motion", output) cv2.imshow("Final Mask", final_mask) - def get_roads(self): + def get_confidence_map(self): return self.mask + def get_roads(self): + if self.mask is None: + return None + mask = (self.mask.copy() * 255).astype(np.uint8) + contour_image = np.zeros_like(mask, dtype=np.uint8) + contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + a = [cv2.contourArea(c) for c in contours] + avg = sum(a) / len(a) + t = avg * 0.75 + contours = [c for c in contours if cv2.contourArea(c) > t] + cv2.drawContours(contour_image, contours, -1, (255, 255, 255), cv2.FILLED) + return contour_image + def reset(self): self.bg_subtractor = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=50, detectShadows=False) self.gray_prev = None self.motion_accumulator = None self.stable_mask = None self.init = False + + def estimate_speed(self, frame, roads): + if not self.init: + self.init = True + if self.gray_prev is None: + self.gray_prev = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + if self.motion_accumulator is None: + self.motion_accumulator = np.zeros_like(self.gray_prev, dtype=np.uint16) + if self.stable_mask is None: + self.stable_mask = np.zeros_like(self.gray_prev, dtype=np.uint8) + if self.confidence is None: + self.confidence = np.zeros_like(self.gray_prev, dtype=np.float32) + if self.mask is None: + self.mask = np.zeros_like(self.gray_prev, dtype=np.float32) + self.frame_count += 1 + + fg_mask = self.bg_subtractor.apply(frame) + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + flow = cv2.calcOpticalFlowFarneback( + self.gray_prev, gray, None, + pyr_scale=0.5, levels=3, winsize=15, + iterations=3, poly_n=5, poly_sigma=1.2, flags=0 + ) + self.gray_prev = gray.copy() + + magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1]) + motion_mask = (magnitude > 1.0).astype(np.uint8) * 255 + combined_mask = cv2.bitwise_and(fg_mask, motion_mask) + self.motion_accumulator = cv2.add(self.motion_accumulator, combined_mask.astype(np.uint16)) + self.motion_accumulator = cv2.subtract(self.motion_accumulator, 50) # decay by 1 + self.motion_accumulator = np.clip(self.motion_accumulator, 0, 255) + + final_mask = (self.motion_accumulator > 20).astype(np.uint8) * 255 + final_mask = cv2.morphologyEx(final_mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8)) + m = cv2.bitwise_and(final_mask, roads) + + contours, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + if len(contours) > 0: + a = [cv2.contourArea(k) for k in contours] + avg = sum(a) / len(a) + m_a = avg * 0.25 + contours = [k for k in contours if cv2.contourArea(k) > m_a] + + if self.debug: + output = frame.copy().astype(np.float32) / 255.0 + alpha_channel = roads.copy().astype(np.float32) / 1024.0 + alpha_mask = cv2.merge([alpha_channel, alpha_channel, alpha_channel]) + overlay_color = np.array([1.0, 0.0, 0.0], dtype=np.float32) + overlay = np.ones_like(output) * overlay_color + output = (1.0 - alpha_mask) * output + alpha_mask * overlay + output = cv2.drawContours(output, contours, -1, (0, 255, 0), 2) + cv2.imshow("roads", output) diff --git a/main.py b/main.py index 6ae86ee..f66ced6 100644 --- a/main.py +++ b/main.py @@ -1,9 +1,7 @@ import datetime import os.path -import random -import munch -import numpy as np +import diskcache from tqdm import tqdm from analyzer import Analyzer @@ -14,6 +12,8 @@ import cv2 DEBUG_MODE = True analyzer = Analyzer(DEBUG_MODE) +cache = diskcache.Cache("./cache") + def calibrate_video(f): name = os.path.basename(f) @@ -49,32 +49,86 @@ def calibrate_video(f): pbar.close() -def calibrate_camera(): - cameras = os.listdir(os.path.join("recordings", "San Francisco")) - camera = random.choice(cameras) - days = [d for d in os.listdir(os.path.join("recordings", "San Francisco", camera)) - if os.path.isdir(os.path.join("recordings", "San Francisco", camera, d))] +def get_videos(): + city = "Sacramento" + cameras = os.listdir(os.path.join("recordings", city)) + camera = cameras[1] # random.choice(cameras) + days = [d for d in os.listdir(os.path.join("recordings", city, camera)) + if os.path.isdir(os.path.join("recordings", city, camera, d))] days = sorted(days) video_files = dict() for d in days: - videos = sorted(os.listdir(os.path.join("recordings", "San Francisco", camera, d))) - video_files[d] = [os.path.join("recordings", "San Francisco", camera, d, f) for f in videos] - videos_to_process = [f for d in days for f in video_files[d]][10:11] + videos = sorted(os.listdir(os.path.join("recordings", city, camera, d))) + video_files[d] = [os.path.join("recordings", city, camera, d, f) for f in videos] + return camera, [f for d in days for f in video_files[d]] + + +def calibrate_roads(): + camera, videos = get_videos() + if camera in cache: + return + videos_to_process = videos[10:12] with tqdm(total=len(videos_to_process), desc="Calibrating camera: " + camera, position=0, ncols=125) as outer_bar: for video in videos_to_process: calibrate_video(video) outer_bar.update(1) - mask = analyzer.get_roads() - mask = (mask.copy() * 255).astype(np.uint8) - cv2.imshow('Confidence Mask', mask) + roads = analyzer.get_roads() + if roads is not None: + cv2.imshow('roads', roads) + cache[camera] = roads cv2.waitKey() +def estimate_max_speed(camera, f): + name = os.path.basename(f) + date = datetime.datetime(int(name[0:4]), int(name[4:6]), int(name[6:8]), int(name[8:10]), int(name[10:12]), + int(name[12:14])) + cap = cv2.VideoCapture(f) + length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + stabilizer = Stabilizer() + analyzer.reset() + roads = cache[camera] + if not cap.isOpened(): + raise RuntimeError("Error opening video stream or file") + limit = min(1000, length) + pbar = tqdm(total=limit, desc=f"Processing video recorded on {date}", position=1, + leave=False, ncols=125) + while cap.isOpened() and pbar.n < limit: + ret, frame = cap.read() + if not ret: + break + stab_frame = stabilizer.stabilize(frame) + if DEBUG_MODE: + cv2.imshow('Frame', frame) + if stab_frame is not None: + if DEBUG_MODE: + cv2.imshow('Stabilized Frame', stab_frame) + analyzer.estimate_speed(stab_frame, roads) + if DEBUG_MODE: + key = cv2.waitKey(1) & 0xFF + if key == ord('q'): + break + if key == 27: + raise KeyboardInterrupt() + pbar.update(1) + cap.release() + pbar.close() + + +def calibrate_speed(): + camera, videos = get_videos() + videos_to_process = videos[15:20] + if camera not in cache: + raise RuntimeError("Camera not found") + for video in videos_to_process: + estimate_max_speed(camera, video) + + def main(): - calibrate_camera() - # analyze_videos() + calibrate_roads() + calibrate_speed() + # analyze_video() # analyze_livestream() - pass if __name__ == '__main__':