Saving max-cars per camera in Cache. Jam-Score Prototype.

This commit is contained in:
2025-08-06 20:12:46 +02:00
parent 27269c34af
commit 3f13b09813
3 changed files with 136 additions and 60 deletions
+25 -5
View File
@@ -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):
+61 -55
View File
@@ -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:
+50
View File
@@ -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()