From 3f13b09813fbabc9dcc6dd3c72b35c9fda82cf8f Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Wed, 6 Aug 2025 20:12:46 +0200 Subject: [PATCH 1/5] Saving max-cars per camera in Cache. Jam-Score Prototype. --- calibration.py | 30 ++++++++++-- jam_detection.py | 116 +++++++++++++++++++++++++---------------------- plot_log.py | 50 ++++++++++++++++++++ 3 files changed, 136 insertions(+), 60 deletions(-) create mode 100644 plot_log.py diff --git a/calibration.py b/calibration.py index d81bc50..1afa170 100644 --- a/calibration.py +++ b/calibration.py @@ -9,7 +9,7 @@ from tqdm import tqdm from vidgear.gears.stabilizer import Stabilizer from norfair import Detection, Tracker -from detection import CombinedDetector +from detection import CombinedDetector, YoloDetector from jam_detection import Jam_Detection import diskcache # For camera mask @@ -28,19 +28,31 @@ class Calibration: self.road_mask = None self.speed_mask = None self.fps = 1 - self.detector = CombinedDetector() + self.detector = YoloDetector() self.tracker = Tracker(distance_function="euclidean", distance_threshold=100) - self.jamDetection = Jam_Detection(self.mask) + self.jamDetection = Jam_Detection(self.mask, 0) + self.cache = diskcache.Cache("./cache") + + def save_camera_car_max(self, camera: str): + cache = diskcache.Cache("./cache") + all_max = cache.get("max_cars", {}) + all_max[camera] = self.jamDetection.max_cars + cache["max_cars"] = all_max + print(f"max_cars für Kamera {camera} gespeichert: {self.jamDetection.max_cars}") + + def load_max_cars(self, camera_id: str): + all_max = self.cache.get("max_cars", {}) + return all_max.get(camera_id, None) # oder Defaultwert wie 0 def calibrate_roads(self, camera, road_calibration_videos): if self.road_mask is not None: return self.road_mask self.calibrate(road_calibration_videos, f"Searching for roads in camera: {camera}", self.track_roads) + self.save_camera_car_max(camera) return self.get_roads() def detect_traffic_jam(self, camera): - cache = diskcache.Cache("./cache") - mask_dict = cache.get("roads", dict()) + mask_dict = self.cache.get("roads", dict()) self.mask = mask_dict.get(camera) if self.mask is None: raise ValueError(f"Keine Maske für Kamera '{camera}' gefunden.") @@ -48,6 +60,9 @@ class Calibration: self.jamDetection.setMask(self.mask) self.jamDetection.saveMask() + all_max = self.cache.get("max_cars", {}) + self.jamDetection.max_cars = all_max.get(camera, None) + def calibrate_speed(self, camera, speed_calibration_videos): if self.speed_mask is not None: return self.speed_mask @@ -117,6 +132,11 @@ class Calibration: self.speed_mask = np.zeros_like(frame, dtype=np.float32, shape=(frame.shape[0], frame.shape[1], 3)) self.frame_count += 1 cars = self.detector.detect(frame) + + if len(cars) > self.jamDetection.max_cars: + self.jamDetection.max_cars = len(cars) + print(f"New max_cars: {self.jamDetection.max_cars}") + track(cars, frame) def track_roads(self, cars_list, frame): diff --git a/jam_detection.py b/jam_detection.py index a071ccd..bb059f9 100644 --- a/jam_detection.py +++ b/jam_detection.py @@ -1,78 +1,84 @@ +import os + import numpy as np import cv2 from detection import CombinedDetector class Jam_Detection: - def __init__(self, road_mask): + def __init__(self, road_mask, max_cars): self.detector = CombinedDetector() self.road_mask = road_mask - self.detector.flow.road_mask = self.road_mask # Direkt setzen + self.max_cars = max_cars + #self.detector.flow.road_mask = self.road_mask # Direkt setzen - def compute_jam_score(self, flow_ratio, car_ratio, only_flow = True): - - if only_flow: - jam_score = flow_ratio + def compute_jam_score(self, car_ratio, detections): + # TODO: Write Jam_Score logic + if self.max_cars == 0: + jam_score = 0 else: - # TODO: Change jam_score calculation - jam_score = flow_ratio * car_ratio + scaler = 0.85 + exponent = detections / self.max_cars + jam_score = min(1.0, (np.exp(exponent*scaler)-1)) + #jam_score = math.exp(exponent)-1 + + # Pfad zur Log-Datei + log_path = "jam_log.csv" + + # Prüfen, ob Datei existiert und leer ist + file_exists = os.path.exists(log_path) + file_empty = not file_exists or os.stat(log_path).st_size == 0 # Log-Daten in Datei schreiben - with open("jam_log.csv", "a") as f: - f.write(f"{flow_ratio},{car_ratio},{jam_score}\n") + with open(log_path, "a") as f: + if file_empty: + f.write("car_ratio,jam_score,number_of_detections\n") + f.write(f"{car_ratio},{jam_score},{detections}\n") return jam_score - def detect_frame(self, frame): - _ = self.detector.flow.detect(frame) + # YOLO-Detektion + detections = self.detector.yolo.detect(frame) - final_mask = (self.detector.flow.motion_accumulator > 10).astype(np.uint8) * 255 - final_mask = cv2.morphologyEx(final_mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8)) + # Maske für erkannte Autos erstellen + car_mask = np.zeros(frame.shape[:2], dtype=np.uint8) + for det in detections: + x1, y1, x2, y2 = map(int, det[:4]) + car_mask[y1:y2, x1:x2] = 255 + # Road-Maske vorbereiten road_mask = self.road_mask - if road_mask.shape != final_mask.shape: - road_mask = cv2.resize(road_mask, (final_mask.shape[1], final_mask.shape[0]), - interpolation=cv2.INTER_NEAREST) + if road_mask.shape != car_mask.shape: + road_mask = cv2.resize(road_mask, (car_mask.shape[1], car_mask.shape[0]), interpolation=cv2.INTER_NEAREST) + # Analyse: Autos auf der Straße road_area = (road_mask == 255) - motion_on_road = np.logical_and(road_area, final_mask == 255) + car_on_road = np.logical_and(road_area, car_mask == 255) total_road_pixels = np.sum(road_area) - moving_pixels_on_road = np.sum(motion_on_road) + car_pixels = np.sum(car_on_road) + car_ratio = car_pixels / total_road_pixels if total_road_pixels > 0 else 0 if total_road_pixels == 0: - print("❗ Road mask hat keine 255-Werte") + print("Road mask hat keine 255-Werte") return - flow_ratio = moving_pixels_on_road / total_road_pixels + # Da Flow raus ist, setzen wir flow_ratio auf 0 + flow_ratio = 0 - # Schwelle für Stillstand festlegen (z.B. wenn weniger als 5% Bewegung) - stillstand_threshold = 0.05 + car_count = len(detections) - if flow_ratio > stillstand_threshold: - car_ratio = 0 - jam_score = self.compute_jam_score(flow_ratio, car_ratio, only_flow = True) - self.visualize_overlay(frame, final_mask, flow_ratio, car_ratio, jam_score, yolo_used=False, - detections=None) - else: - detections = self.detector.yolo.detect(frame) + # Berechne den Stau-Score nur anhand von Autos + jam_score = self.compute_jam_score(car_ratio, car_count) - car_mask = np.zeros_like(final_mask) - for det in detections: - x1, y1, x2, y2 = map(int, det[:4]) - car_mask[y1:y2, x1:x2] = 255 - car_on_road = np.logical_and(road_area, car_mask == 255) - car_pixels = np.sum(car_on_road) - car_ratio = car_pixels / total_road_pixels if total_road_pixels > 0 else 0 + # Visualisierung + self.visualize_overlay(frame, np.zeros_like(car_mask), car_ratio, car_count, jam_score, detections=detections) - jam_score = self.compute_jam_score(flow_ratio, car_ratio, only_flow = False) - self.visualize_overlay(frame, final_mask, flow_ratio, car_ratio, jam_score, yolo_used=True, - detections=detections) - def visualize_overlay(self, frame, final_mask, coverage_ratio, car_ratio, jam_score, yolo_used=False, detections=None): + def visualize_overlay(self, frame, final_mask, car_coverage_ratio, car_count, jam_score, detections=None): overlay = frame.copy() if self.road_mask.shape != frame.shape[:2]: @@ -89,24 +95,24 @@ class Jam_Detection: motion_mask[final_mask == 255] = (0, 255, 0) # Grün für Bewegung overlay = cv2.addWeighted(overlay, 1.0, motion_mask, 1.0, 0) - flow_ratio = f"{coverage_ratio * 100:.1f}% Flow_ratio" - car_ratio = f"{car_ratio * 100:.1f}% Car_ratio" - jam_text = f"Stau-Score: {jam_score:.2f}" + car_ratio = f"Coverage: {car_coverage_ratio * 100:.1f}%" + jam_text = f"Jam-score: {jam_score * 100:.2f}" + car_count_text = f"Count: {car_count:.2f}" + max_cars = f"Max: {self.max_cars:.2f}" - if yolo_used: - cv2.putText(overlay, "YOLO aktiv", (20, 120), cv2.FONT_HERSHEY_SIMPLEX, - 1.0, (0, 0, 255), 3, cv2.LINE_AA) - cv2.putText(overlay, "YOLO aktiv", (20, 120), cv2.FONT_HERSHEY_SIMPLEX, - 1.0, (255, 255, 255), 1, cv2.LINE_AA) - cv2.putText(overlay, flow_ratio, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 3, cv2.LINE_AA) - cv2.putText(overlay, flow_ratio, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1, cv2.LINE_AA) + cv2.putText(overlay, car_ratio, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 3, cv2.LINE_AA) + cv2.putText(overlay, car_ratio, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA) - cv2.putText(overlay, car_ratio, (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 3, cv2.LINE_AA) - cv2.putText(overlay, car_ratio, (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1, cv2.LINE_AA) + cv2.putText(overlay, jam_text, (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 3, cv2.LINE_AA) + cv2.putText(overlay, jam_text, (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA) + + cv2.putText(overlay, car_count_text, (20, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 3, cv2.LINE_AA) + cv2.putText(overlay, car_count_text, (20, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA) + + cv2.putText(overlay, max_cars, (20, 160), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 3, cv2.LINE_AA) + cv2.putText(overlay, max_cars, (20, 160), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA) - cv2.putText(overlay, jam_text, (20, 120), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 3, cv2.LINE_AA) - cv2.putText(overlay, jam_text, (20, 120), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1, cv2.LINE_AA) if detections is not None: for det in detections: diff --git a/plot_log.py b/plot_log.py new file mode 100644 index 0000000..ddc23a8 --- /dev/null +++ b/plot_log.py @@ -0,0 +1,50 @@ +import matplotlib.pyplot as plt +import pandas as pd +import os + +def plot_jam_log_combined(csv_path="jam_log.csv"): + """ + Liest jam_log.csv ein und plottet car_ratio und number_of_detections + gemeinsam in einem Plot mit zwei Y-Achsen. + """ + # Datei-Check + if not os.path.exists(csv_path): + print(f"Datei '{csv_path}' nicht gefunden.") + return + + # CSV laden + df = pd.read_csv(csv_path) + print("loaded csv") + + # Spalten prüfen + required_cols = {'car_ratio', 'jam_score', 'number_of_detections'} + if not required_cols.issubset(df.columns): + print(f"CSV muss folgende Spalten enthalten: {required_cols}") + return + + x = df.index + car_ratio = df["car_ratio"] + detections = df["number_of_detections"] + + # Plot mit zwei Y-Achsen + fig, ax1 = plt.subplots(figsize=(12, 6)) + + color1 = "tab:green" + ax1.set_xlabel("Frame") + ax1.set_ylabel("Car Ratio", color=color1) + ax1.plot(x, car_ratio, color=color1, label="Car Ratio", marker='o') + ax1.tick_params(axis='y', labelcolor=color1) + + ax2 = ax1.twinx() # zweite Y-Achse + color2 = "tab:blue" + ax2.set_ylabel("Number of Detections", color=color2) + ax2.plot(x, detections, color=color2, label="Detections", marker='x') + ax2.tick_params(axis='y', labelcolor=color2) + + # Titel und Legenden + plt.title("Car Ratio & Number of YOLO Detections over Time") + fig.tight_layout() + plt.grid(True) + plt.show() + +plot_jam_log_combined() From a7965b02ab729b8b6e5d80b23ac6d0e08c1cb1c0 Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Thu, 7 Aug 2025 16:41:26 +0200 Subject: [PATCH 2/5] - Saving results in csv with timestamp - Frameing results through snapshot timer var --- calibration.py | 2 ++ jam_detection.py | 91 +++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 80 insertions(+), 13 deletions(-) diff --git a/calibration.py b/calibration.py index 1afa170..6e87e2e 100644 --- a/calibration.py +++ b/calibration.py @@ -74,6 +74,7 @@ class Calibration: with tqdm(total=len(calibration_videos), desc=desc, position=0, ncols=self.progress_bar_cols) as outer_bar: for video in calibration_videos: + self.jamDetection.setCameraVideo(desc, video) self.calibrate_video(video, track) outer_bar.update(1) @@ -133,6 +134,7 @@ class Calibration: self.frame_count += 1 cars = self.detector.detect(frame) + # Set new max if needed if len(cars) > self.jamDetection.max_cars: self.jamDetection.max_cars = len(cars) print(f"New max_cars: {self.jamDetection.max_cars}") diff --git a/jam_detection.py b/jam_detection.py index bb059f9..a912240 100644 --- a/jam_detection.py +++ b/jam_detection.py @@ -1,7 +1,10 @@ import os +from datetime import datetime, timedelta import numpy as np import cv2 +from fontTools.pens.basePen import NullPen + from detection import CombinedDetector @@ -11,18 +14,18 @@ class Jam_Detection: self.road_mask = road_mask self.max_cars = max_cars #self.detector.flow.road_mask = self.road_mask # Direkt setzen + self.score_list = [] + self.camera = None + self.video = None + self.frame = 0 + self.fps = 0 + self.timestamp = None + self.snapshot_timer = 10 - def compute_jam_score(self, car_ratio, detections): - # TODO: Write Jam_Score logic - - if self.max_cars == 0: - jam_score = 0 - else: - scaler = 0.85 - exponent = detections / self.max_cars - jam_score = min(1.0, (np.exp(exponent*scaler)-1)) - #jam_score = math.exp(exponent)-1 + def clear_scores(self): + self.score_list = [] + def write_log(self, detections, car_ratio, jam_score): # Pfad zur Log-Datei log_path = "jam_log.csv" @@ -33,8 +36,28 @@ class Jam_Detection: # Log-Daten in Datei schreiben with open(log_path, "a") as f: if file_empty: - f.write("car_ratio,jam_score,number_of_detections\n") - f.write(f"{car_ratio},{jam_score},{detections}\n") + f.write("camera, video, frame, timestamp, car_ratio,jam_score,number_of_detections\n") + f.write(f"{self.camera}, {os.path.basename(self.video)}, {self.frame} {self.timestamp}, {detections}, {car_ratio}, {jam_score}\n") + + print(f"Saved log for Frame {self.frame}") + + + def compute_frame_slot(self): + self.timestamp += timedelta(seconds=self.snapshot_timer) + columns = list(zip(*self.score_list)) + averages = [sum(col) / len(col) for col in columns] + self.write_log(averages[0], averages[1], averages[2]) + self.clear_scores() + + + def compute_jam_score(self, detections): + if self.max_cars == 0: + jam_score = 0 + else: + scaler = 0.85 + exponent = detections / self.max_cars + jam_score = min(1.0, (np.exp(exponent*scaler)-1)) + #jam_score = math.exp(exponent)-1 return jam_score @@ -71,8 +94,14 @@ class Jam_Detection: car_count = len(detections) # Berechne den Stau-Score nur anhand von Autos - jam_score = self.compute_jam_score(car_ratio, car_count) + jam_score = self.compute_jam_score(car_count) + self.frame = self.frame + 1 + + self.score_list.append([len(detections), car_ratio, jam_score]) + + if len(self.score_list) % (self.fps * self.snapshot_timer) == 0: + self.compute_frame_slot() # Visualisierung self.visualize_overlay(frame, np.zeros_like(car_mask), car_ratio, car_count, jam_score, detections=detections) @@ -132,3 +161,39 @@ class Jam_Detection: def setMask(self, mask): self.road_mask = mask print(f"mask set: {mask.shape}") + + def setCameraVideo(self, camera, video): + print(f"camera set: {camera}") + print(f"video set: {video}") + self.camera = camera + self.video = video + self.frame = 0 + self.fps = self.getFramerate() + self.timestamp = self.getVideoStartTime(video) + + + def getVideoStartTime(self, video): + video = os.path.basename(video) + date = datetime( + int(video[0:4]), # Jahr + int(video[4:6]), # Monat + int(video[6:8]), # Tag + int(video[8:10]), # Stunde + int(video[10:12]), # Minute + int(video[12:14]) # Sekunde + ) + return date + + + def getFramerate(self): + cap = cv2.VideoCapture(self.video) + + if not cap.isOpened(): + print("Video not opened") + cap.release() + + else: + fps = cap.get(cv2.CAP_PROP_FPS) + print(f"Video fps: {fps}") + cap.release() + return fps From 7153cc6884caa9666c03cd885e0f9ca1dfc64a1f Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Thu, 7 Aug 2025 17:14:47 +0200 Subject: [PATCH 3/5] Bugfix: camera log name --- calibration.py | 2 +- jam_detection.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/calibration.py b/calibration.py index 6e87e2e..19de2a3 100644 --- a/calibration.py +++ b/calibration.py @@ -74,7 +74,7 @@ class Calibration: with tqdm(total=len(calibration_videos), desc=desc, position=0, ncols=self.progress_bar_cols) as outer_bar: for video in calibration_videos: - self.jamDetection.setCameraVideo(desc, video) + self.jamDetection.setCameraVideo(desc.split(": ")[1], video) self.calibrate_video(video, track) outer_bar.update(1) diff --git a/jam_detection.py b/jam_detection.py index a912240..f5b0ed2 100644 --- a/jam_detection.py +++ b/jam_detection.py @@ -20,14 +20,16 @@ class Jam_Detection: self.frame = 0 self.fps = 0 self.timestamp = None - self.snapshot_timer = 10 + self.snapshot_timer = 5 def clear_scores(self): self.score_list = [] def write_log(self, detections, car_ratio, jam_score): # Pfad zur Log-Datei - log_path = "jam_log.csv" + print(self.camera) + log_path = f"jam_log_{self.camera}.csv" + #log_path = "jam_log_.csv" # Prüfen, ob Datei existiert und leer ist file_exists = os.path.exists(log_path) From 019c2b095ba62163ef9bdce2e6d24f4cd902e100 Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Thu, 7 Aug 2025 17:17:54 +0200 Subject: [PATCH 4/5] Bugfix: log creation --- jam_detection.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jam_detection.py b/jam_detection.py index f5b0ed2..1fc9218 100644 --- a/jam_detection.py +++ b/jam_detection.py @@ -39,7 +39,7 @@ class Jam_Detection: with open(log_path, "a") as f: if file_empty: f.write("camera, video, frame, timestamp, car_ratio,jam_score,number_of_detections\n") - f.write(f"{self.camera}, {os.path.basename(self.video)}, {self.frame} {self.timestamp}, {detections}, {car_ratio}, {jam_score}\n") + f.write(f"{self.camera}, {os.path.basename(self.video)}, {self.frame}, {self.timestamp}, {detections}, {car_ratio}, {jam_score}\n") print(f"Saved log for Frame {self.frame}") From b61b4a693c204c1f3b6ce83f339f3aecb87dc27e Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Thu, 7 Aug 2025 17:34:11 +0200 Subject: [PATCH 5/5] Bugfix: log --- jam_detection.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jam_detection.py b/jam_detection.py index 1fc9218..cb1a850 100644 --- a/jam_detection.py +++ b/jam_detection.py @@ -38,8 +38,8 @@ class Jam_Detection: # Log-Daten in Datei schreiben with open(log_path, "a") as f: if file_empty: - f.write("camera, video, frame, timestamp, car_ratio,jam_score,number_of_detections\n") - f.write(f"{self.camera}, {os.path.basename(self.video)}, {self.frame}, {self.timestamp}, {detections}, {car_ratio}, {jam_score}\n") + f.write("camera, video, frame, timestamp, number_of_detections, car_ratio, jam_score, max_cars\n") + f.write(f"{self.camera}, {os.path.basename(self.video)}, {self.frame}, {self.timestamp}, {detections}, {car_ratio}, {jam_score}, {self.max_cars}\n") print(f"Saved log for Frame {self.frame}")