Merge branch 'lukasTest' of https://project.nes.uni-due.de/gitea/roch/TrafficAnalyzer into lukasTest
This commit is contained in:
+27
-5
@@ -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
|
||||
@@ -59,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.split(": ")[1], video)
|
||||
self.calibrate_video(video, track)
|
||||
outer_bar.update(1)
|
||||
|
||||
@@ -117,6 +133,12 @@ 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)
|
||||
|
||||
# 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}")
|
||||
|
||||
track(cars, frame)
|
||||
|
||||
def track_roads(self, cars_list, frame):
|
||||
|
||||
+128
-55
@@ -1,78 +1,115 @@
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
from fontTools.pens.basePen import NullPen
|
||||
|
||||
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
|
||||
self.score_list = []
|
||||
self.camera = None
|
||||
self.video = None
|
||||
self.frame = 0
|
||||
self.fps = 0
|
||||
self.timestamp = None
|
||||
self.snapshot_timer = 5
|
||||
|
||||
def compute_jam_score(self, flow_ratio, car_ratio, only_flow = True):
|
||||
def clear_scores(self):
|
||||
self.score_list = []
|
||||
|
||||
if only_flow:
|
||||
jam_score = flow_ratio
|
||||
def write_log(self, detections, car_ratio, jam_score):
|
||||
# Pfad zur Log-Datei
|
||||
print(self.camera)
|
||||
log_path = f"jam_log_{self.camera}.csv"
|
||||
#log_path = "jam_log_.csv"
|
||||
|
||||
else:
|
||||
# TODO: Change jam_score calculation
|
||||
jam_score = flow_ratio * car_ratio
|
||||
# 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("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}")
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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_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
|
||||
self.frame = self.frame + 1
|
||||
|
||||
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
|
||||
self.score_list.append([len(detections), car_ratio, jam_score])
|
||||
|
||||
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)
|
||||
if len(self.score_list) % (self.fps * self.snapshot_timer) == 0:
|
||||
self.compute_frame_slot()
|
||||
|
||||
def visualize_overlay(self, frame, final_mask, coverage_ratio, car_ratio, jam_score, yolo_used=False, detections=None):
|
||||
# Visualisierung
|
||||
self.visualize_overlay(frame, np.zeros_like(car_mask), car_ratio, car_count, jam_score, detections=detections)
|
||||
|
||||
|
||||
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 +126,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:
|
||||
@@ -126,3 +163,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
|
||||
|
||||
+50
@@ -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()
|
||||
Reference in New Issue
Block a user