add progress bars

This commit is contained in:
2025-05-26 07:41:28 +02:00
parent 3ca288a299
commit e29cc9c819
2 changed files with 42 additions and 29 deletions
+10 -14
View File
@@ -3,7 +3,7 @@ import numpy as np
class Analyzer:
def __init__(self):
def __init__(self, debug_mode=False):
self.gray_prev = None
self.motion_accumulator = None
self.bg_subtractor = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=50, detectShadows=False)
@@ -12,6 +12,7 @@ class Analyzer:
self.init = False
self.frame_count = 0
self.mask = None
self.debug = debug_mode
def analyze_frame(self, frame):
if not self.init:
@@ -30,7 +31,6 @@ class Analyzer:
fg_mask = self.bg_subtractor.apply(frame)
# --- Optical flow computation ---
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(
self.gray_prev, gray, None,
@@ -41,11 +41,7 @@ class Analyzer:
magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
motion_mask = (magnitude > 1.0).astype(np.uint8) * 255
# --- Combine background and optical flow masks ---
combined_mask = cv2.bitwise_and(fg_mask, motion_mask)
# --- Update motion accumulator (temporal smoothing) ---
self.motion_accumulator = cv2.add(self.motion_accumulator, combined_mask.astype(np.uint16))
self.motion_accumulator = cv2.subtract(self.motion_accumulator, 1) # decay by 1
self.motion_accumulator = np.clip(self.motion_accumulator, 0, 255)
@@ -64,14 +60,14 @@ class Analyzer:
self.mask = np.clip(self.mask, 0, 1)
_, self.mask = cv2.threshold(self.mask, 0.1, 1, cv2.THRESH_TOZERO)
output = frame.copy().astype(np.float32) / 255.0
alpha_mask = cv2.merge([self.mask, self.mask, self.mask])
overlay_color = np.array([0.0, 1.0, 0.0], dtype=np.float32)
overlay = np.ones_like(output) * overlay_color
output = (1.0 - alpha_mask) * output + alpha_mask * overlay
cv2.imshow("Detected Motion", output)
cv2.imshow("Final Mask", final_mask)
if self.debug:
output = frame.copy().astype(np.float32) / 255.0
alpha_mask = cv2.merge([self.mask, self.mask, self.mask])
overlay_color = np.array([0.0, 1.0, 0.0], dtype=np.float32)
overlay = np.ones_like(output) * overlay_color
output = (1.0 - alpha_mask) * output + alpha_mask * overlay
cv2.imshow("Detected Motion", output)
cv2.imshow("Final Mask", final_mask)
def get_roads(self):
return self.mask
+32 -15
View File
@@ -2,45 +2,56 @@ import datetime
import os.path
import random
import munch
import numpy as np
from tqdm import tqdm
from analyzer import Analyzer
from vidgear.gears.stabilizer import Stabilizer
import cv2
analyzer = Analyzer()
DEBUG_MODE = True
analyzer = Analyzer(DEBUG_MODE)
def calibrate_video(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]))
print(f"Video recorded on {date}")
cap = cv2.VideoCapture(f)
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
stabilizer = Stabilizer()
analyzer.reset()
if not cap.isOpened():
raise RuntimeError("Error opening video stream or file")
while cap.isOpened():
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)
cv2.imshow('Frame', frame)
if DEBUG_MODE:
cv2.imshow('Frame', frame)
if stab_frame is not None:
cv2.imshow('Stabilized Frame', stab_frame)
if DEBUG_MODE:
cv2.imshow('Stabilized Frame', stab_frame)
analyzer.analyze_frame(stab_frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
if key == 27:
raise KeyboardInterrupt()
if DEBUG_MODE:
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
if key == 27:
raise KeyboardInterrupt()
pbar.update(1)
cap.release()
cv2.destroyAllWindows()
pbar.close()
def calibrate_camera():
cameras = os.listdir(os.path.join("recordings", "San Francisco"))
camera = random.choice(cameras)
print("Calibrating camera: " + camera)
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))]
days = sorted(days)
@@ -48,9 +59,15 @@ def calibrate_camera():
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]
for d in days[0:3]:
for f in video_files[d]:
calibrate_video(f)
videos_to_process = [f for d in days for f in video_files[d]][10:11]
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)
cv2.waitKey()
def main():