243 lines
10 KiB
Python
243 lines
10 KiB
Python
import datetime
|
|
import os
|
|
from linecache import cache
|
|
|
|
import cv2
|
|
import munch
|
|
import numpy as np
|
|
from tqdm import tqdm
|
|
from vidgear.gears.stabilizer import Stabilizer
|
|
from norfair import Detection, Tracker
|
|
|
|
from detection import CombinedDetector, YoloDetector
|
|
from jam_detection import Jam_Detection
|
|
import diskcache # For camera mask
|
|
|
|
|
|
class Calibration:
|
|
def __init__(self):
|
|
self.init = False
|
|
self.frame_count = 0
|
|
self.confidence = None
|
|
self.mask = None
|
|
self.stable_mask = None
|
|
self.debug_mode = True
|
|
self.stabilize_video = False
|
|
self.scale = 0.5
|
|
self.progress_bar_cols = 150
|
|
self.road_mask = None
|
|
self.speed_mask = None
|
|
self.fps = 1
|
|
self.detector = YoloDetector()
|
|
self.tracker = Tracker(distance_function="euclidean", distance_threshold=100)
|
|
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):
|
|
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.")
|
|
print(f"mask set: {self.mask.shape}")
|
|
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
|
|
self.detect_traffic_jam(camera)
|
|
self.calibrate(speed_calibration_videos, f"Calibrating speed in camera: {camera}", self.track_cars)
|
|
return self.get_speed_mask()
|
|
|
|
def calibrate(self, calibration_videos, desc, track):
|
|
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)
|
|
|
|
def calibrate_video(self, video, track):
|
|
name = os.path.basename(video)
|
|
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(video)
|
|
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
self.fps = int(cap.get(cv2.CAP_PROP_FPS))
|
|
|
|
stabilizer = Stabilizer() if self.stabilize_video else munch.Munch(stabilize=lambda f: f)
|
|
|
|
if not cap.isOpened():
|
|
raise RuntimeError("Error opening video stream or file")
|
|
limit = min(2500, length)
|
|
pbar = tqdm(total=limit, desc=f"Processing video recorded on {date}", position=1,
|
|
leave=False, ncols=self.progress_bar_cols)
|
|
while cap.isOpened() and pbar.n < limit:
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
break
|
|
stab_frame = stabilizer.stabilize(frame)
|
|
self.show_debug_info(frame if stab_frame is None else stab_frame)
|
|
self.analyze_frame(stab_frame, track)
|
|
if self.stop():
|
|
break
|
|
pbar.update(1)
|
|
cap.release()
|
|
pbar.close()
|
|
|
|
def stop(self):
|
|
if self.debug_mode:
|
|
key = cv2.waitKey(1) & 0xFF
|
|
if key == ord('q'):
|
|
return True
|
|
if key == 27:
|
|
raise KeyboardInterrupt()
|
|
return False
|
|
|
|
def show_debug_info(self, frame):
|
|
if self.debug_mode:
|
|
cv2.imshow('Frame', frame)
|
|
|
|
def analyze_frame(self, frame, track):
|
|
if frame is None:
|
|
return
|
|
frame = cv2.resize(frame, (0, 0), fx=self.scale, fy=self.scale)
|
|
if not self.init:
|
|
self.init = True
|
|
if self.confidence is None:
|
|
self.confidence = np.zeros_like(frame, dtype=np.float32, shape=(frame.shape[0], frame.shape[1], 1))
|
|
if self.mask is None:
|
|
self.mask = np.zeros_like(frame, dtype=np.float32, shape=(frame.shape[0], frame.shape[1], 1))
|
|
if self.speed_mask is None:
|
|
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):
|
|
cars = np.zeros_like(frame, np.uint8, shape=(frame.shape[0], frame.shape[1], 1))
|
|
for car in cars_list:
|
|
cv2.rectangle(cars, (car[0], car[1]), (car[2], car[3]), (255, 255, 255), cv2.FILLED)
|
|
ones = np.zeros_like(frame, dtype=np.uint8, shape=(frame.shape[0], frame.shape[1], 1))
|
|
ones[cars == 255] = 1
|
|
self.confidence += (ones - self.confidence) / self.frame_count
|
|
max_val = np.max(self.confidence)
|
|
if max_val < 0.001:
|
|
return
|
|
self.mask = self.confidence.copy()
|
|
self.mask /= np.max(self.mask)
|
|
self.mask = np.clip(self.mask, 0, 1)
|
|
if self.debug_mode:
|
|
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("Cars", cars)
|
|
|
|
def track_cars(self, cars, frame):
|
|
roads = self.get_roads()
|
|
if roads.size != frame.size:
|
|
roads = cv2.resize(roads, (frame.shape[1], frame.shape[0]))
|
|
centers = [(int(car[0]+((car[2]-car[0])/2)), int(car[1]+((car[3]-car[1])/2))) for car in cars]
|
|
on_road = [roads[center[1],center[0]]>128 for center in centers]
|
|
centers = [center for center, on_road in zip(centers, on_road) if on_road]
|
|
norfair_detections = [Detection(np.array(center)) for center in centers]
|
|
tracked_objects = self.tracker.update(detections=norfair_detections)
|
|
tracked_objects = [t for t in tracked_objects if t.live_points]
|
|
centers = [o.estimate for o in tracked_objects]
|
|
centers = [(int(c[0,0]), int(c[0,1])) for c in centers]
|
|
speed = [o.estimate_velocity for o in tracked_objects]
|
|
speed = [(float(s[0,0]), float(s[0,1])) for s in speed]
|
|
speed = [np.sqrt(s[0]*s[0]+s[1]*s[1]) for s in speed]
|
|
speed = [round(s * self.fps, 3) for s in speed]
|
|
ids = [o.id for o in tracked_objects]
|
|
|
|
for c, s in zip(centers, speed):
|
|
radius = 5
|
|
x_indices = np.arange(max(c[0] - radius, 0), min(c[0] + radius + 1, frame.shape[0]))
|
|
y_indices = np.arange(max(c[1] - radius, 0), min(c[1] + radius + 1, frame.shape[1]))
|
|
xx, yy = np.meshgrid(x_indices, y_indices, indexing='ij')
|
|
distances = np.sqrt((xx - c[0]) ** 2 + (yy - c[1]) ** 2)
|
|
mask = distances <= radius
|
|
# print(self.speed_mask)
|
|
# print(self.speed_mask.shape)
|
|
# avg_speed, max_speed, measurements = self.speed_mask[xx[mask], yy[mask]]
|
|
points = self.speed_mask[xx[mask], yy[mask]]
|
|
for i in range(points.shape[0]):
|
|
avg_speed, max_speed, measurements = points[i, 0], points[i, 1], points[i, 2]
|
|
avg_speed = ((avg_speed * measurements) + s) / (measurements + 1)
|
|
max_speed = max(max_speed, s)
|
|
measurements += 1
|
|
points[i, 0], points[i, 1], points[i, 2] = avg_speed, max_speed, measurements
|
|
avg_speeds = self.speed_mask[:, :, 0].copy()
|
|
if np.max(avg_speeds) > 0:
|
|
avg_speeds /= np.max(avg_speeds)
|
|
avg_speeds *= 255
|
|
avg_speeds = avg_speeds.astype(np.uint8)
|
|
cv2.imshow("Detected Speed", avg_speeds)
|
|
|
|
debug_image = frame.copy()
|
|
for car_center, car_speed, car_id in zip(centers, speed, ids):
|
|
cv2.circle(debug_image, car_center, 2, (0, 0, 255), cv2.FILLED)
|
|
cv2.putText(debug_image, str(car_id) + " " + str(car_speed), car_center, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))
|
|
# TODO: overlay speed map
|
|
|
|
self.jamDetection.detect_frame(frame)
|
|
cv2.imshow('Detection', debug_image)
|
|
|
|
|
|
def get_roads(self):
|
|
if self.road_mask is not None:
|
|
return self.road_mask
|
|
if self.mask is None:
|
|
return None
|
|
_, mask = cv2.threshold(self.mask, 0.1, 1, cv2.THRESH_TOZERO)
|
|
mask = (mask * 255).astype(np.uint8)
|
|
mask = cv2.resize(mask, (0, 0), fx=1/self.scale, fy=1/self.scale)
|
|
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) if len(a) > 0 else 0
|
|
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)
|
|
contour_image = cv2.morphologyEx(contour_image, cv2.MORPH_OPEN, np.ones((11, 11), np.uint8))
|
|
contour_image = cv2.dilate(contour_image, np.ones((7, 7), np.uint8), iterations=1)
|
|
self.road_mask = contour_image
|
|
return contour_image
|
|
|
|
def set_roads(self, roads):
|
|
self.road_mask = roads
|
|
|
|
def get_speed_mask(self):
|
|
pass
|