combined yolo and optical flow for car detection

This commit is contained in:
2025-07-03 15:41:54 +02:00
parent 01846a85aa
commit 4ecf90c27a
4 changed files with 132 additions and 53 deletions
+1
View File
@@ -7,3 +7,4 @@ cache/
gui-cache/
recordings*/
*.prof
*.pt
+16 -52
View File
@@ -7,25 +7,23 @@ import numpy as np
from tqdm import tqdm
from vidgear.gears.stabilizer import Stabilizer
from detection import CombinedDetector
class Calibration:
def __init__(self):
self.bg_subtractor = cv2.createBackgroundSubtractorMOG2()
self.gray = None
self.mask = None
self.init = False
self.frame_count = 0
self.confidence = None
self.mask = None
self.stable_mask = None
self.gray_prev = None
self.init = False
self.debug_mode = True
self.stabilize_video = True
self.motion_accumulator = None
self.optical_flow_scale = 1
self.stabilize_video = False
self.scale = 0.5
self.progress_bar_cols = 150
self.road_mask = None
self.speed_mask = None
self.detector = CombinedDetector()
def calibrate_roads(self, camera, road_calibration_videos):
if self.road_mask is not None:
@@ -56,7 +54,7 @@ class Calibration:
# fps = int(cap.get(cv2.CAP_PROP_FPS))
stabilizer = Stabilizer() if self.stabilize_video else munch.Munch(stabilize=lambda f: f)
self.reset_roads()
if not cap.isOpened():
raise RuntimeError("Error opening video stream or file")
limit = length# min(1000, length)
@@ -84,10 +82,6 @@ class Calibration:
raise KeyboardInterrupt()
return False
def reset_roads(self):
self.bg_subtractor = cv2.createBackgroundSubtractorMOG2()
self.init = False
def show_debug_info(self, frame):
if self.debug_mode:
cv2.imshow('Frame', frame)
@@ -98,21 +92,19 @@ class Calibration:
frame = cv2.resize(frame, (0, 0), fx=self.scale, fy=self.scale)
if not self.init:
self.init = True
self.gray_prev = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
self.gray = np.zeros_like(self.gray_prev, dtype=np.uint8)
self.motion_accumulator = np.zeros_like(self.gray_prev, dtype=np.uint16)
if self.confidence is None:
self.confidence = np.zeros_like(self.gray_prev, dtype=np.float32)
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(self.gray_prev, dtype=np.float32)
self.mask = np.zeros_like(frame, dtype=np.float32, shape=(frame.shape[0], frame.shape[1], 1))
self.frame_count += 1
cars = self.find_cars(frame)
cars = self.detector.detect(frame)
track(cars, frame)
def track_roads(self, cars, frame):
ones = np.zeros_like(cars, dtype=np.uint8)
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)
@@ -134,34 +126,6 @@ class Calibration:
roads = self.get_roads()
pass
def find_cars(self, frame):
fg_mask = self.bg_subtractor.apply(frame)
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY, self.gray)
small_gray = cv2.resize(self.gray, (0, 0), fx=self.optical_flow_scale, fy=self.optical_flow_scale)
small_gray_prev = cv2.resize(self.gray_prev, (0, 0), fx=self.optical_flow_scale, fy=self.optical_flow_scale)
small_flow = cv2.calcOpticalFlowFarneback(
small_gray_prev, small_gray, None,
pyr_scale=0.5, levels=2, winsize=9,
iterations=2, poly_n=5, poly_sigma=1.1, flags=0
)
flow = cv2.resize(small_flow, (self.gray.shape[1], self.gray.shape[0]))
flow *= 1 / self.optical_flow_scale
self.gray_prev, self.gray = self.gray, self.gray_prev
magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
motion_mask = (magnitude > 1.0).astype(np.uint8) * 255
combined_mask = cv2.bitwise_and(fg_mask, motion_mask)
self.motion_accumulator = cv2.add(self.motion_accumulator, combined_mask.astype(np.uint16))
self.motion_accumulator = cv2.subtract(self.motion_accumulator, 50)
self.motion_accumulator = np.clip(self.motion_accumulator, 0, 255)
final_mask = (self.motion_accumulator > 20).astype(np.uint8) * 255
final_mask = cv2.morphologyEx(final_mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8))
return final_mask
def get_road_confidence_map(self):
mask = cv2.resize(self.mask, (0, 0), fx=1/self.scale, fy=1/self.scale)
return mask
def get_roads(self):
if self.road_mask is not None:
return self.road_mask
@@ -173,7 +137,7 @@ class Calibration:
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)
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)
+113
View File
@@ -0,0 +1,113 @@
import abc
import cv2
import numpy as np
from ultralytics import YOLO
def contains(box, b):
xa1, ya1, xa2, ya2 = box
xb1, yb1, xb2, yb2 = b
xi1, yi1, xi2, yi2 = max(xa1, xb1), max(ya1, yb1), min(xa2, xb2), min(ya2, yb2)
if xi1 >= xi2 or yi1 >= yi2:
return False
return ((xi2 - xi1) * (yi2 - yi1)) / ((xb2 - xb1) * (yb2 - yb1)) > 0.25
def filter_boxes(boxes):
if len(boxes) == 0:
return []
boxes = sorted(boxes, key=lambda b: b[2] * b[3], reverse=True)
boxes = [(x, y, x + w, y + h) for x, y, w, h, in boxes]
filtered = []
while len(boxes) > 0:
box = boxes.pop(0)
filtered.append(box)
boxes = [b for b in boxes if not contains(box, b)]
average_area = sum([(x2 - x1) * (y2 - y1) for x1, y1, x2, y2 in filtered]) / len(filtered)
return [b for b in filtered if (b[2] - b[0]) * (b[3] - b[1]) > (average_area / 4)]
class Detector(abc.ABC):
def __init__(self):
pass
@abc.abstractmethod
def detect(self, image) -> list[tuple[int, int, int, int]]:
pass
class CombinedDetector(Detector):
def __init__(self):
super().__init__()
self.yolo = YoloDetector()
self.flow = OpticalFlowDetector()
def detect(self, image) -> list[tuple[int, int, int, int]]:
# if self.debug_mode:
# img = frame.copy()
# for car in cars_yolo:
# cv2.rectangle(img, (car[0], car[1]), (car[2], car[3]), (255, 0, 0), 2)
# for car in cars_optical_flow:
# cv2.rectangle(img, (car[0], car[1]), (car[2], car[3]), (0, 0, 255), 2)
# cv2.imshow('Cars', img)
yolo_cars = self.yolo.detect(image)
flow_cars = self.flow.detect(image)
cars = yolo_cars + flow_cars
cars = [(x1, y1, x2-x1, y2-y1) for x1, y1, x2, y2 in cars]
return filter_boxes(cars)
class YoloDetector(Detector):
def __init__(self):
super().__init__()
self.model = YOLO("yolo11n.pt")
def detect(self, image) -> list[tuple[int, int, int, int]]:
return [(int(box[0]), int(box[1]), int(box[2]), int(box[3]))
for result in self.model.predict(image, verbose=False)
for box, cls in zip(result.boxes.xyxy, result.boxes.cls)
if int(cls) in (2, 3, 5, 7)]
class OpticalFlowDetector(Detector):
def __init__(self):
super().__init__()
self.bg_subtractor = None
self.init = False
self.gray_prev = None
self.gray = None
self.motion_accumulator = None
self.optical_flow_scale = 1
def detect(self, image):
if not self.init:
self.bg_subtractor = cv2.createBackgroundSubtractorMOG2()
self.gray_prev = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
self.gray = np.zeros_like(self.gray_prev, dtype=np.uint8)
self.motion_accumulator = np.zeros_like(self.gray_prev, dtype=np.uint16)
self.init = True
fg_mask = self.bg_subtractor.apply(image)
cv2.cvtColor(image, cv2.COLOR_BGR2GRAY, self.gray)
small_gray = cv2.resize(self.gray, (0, 0), fx=self.optical_flow_scale, fy=self.optical_flow_scale)
small_gray_prev = cv2.resize(self.gray_prev, (0, 0), fx=self.optical_flow_scale, fy=self.optical_flow_scale)
small_flow = cv2.calcOpticalFlowFarneback(
small_gray_prev, small_gray, None,
pyr_scale=0.5, levels=2, winsize=9,
iterations=2, poly_n=5, poly_sigma=1.1, flags=0
)
flow = cv2.resize(small_flow, (self.gray.shape[1], self.gray.shape[0]))
flow *= 1 / self.optical_flow_scale
self.gray_prev, self.gray = self.gray, self.gray_prev
magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
motion_mask = (magnitude > 1.0).astype(np.uint8) * 255
combined_mask = cv2.bitwise_and(fg_mask, motion_mask)
self.motion_accumulator = cv2.add(self.motion_accumulator, combined_mask.astype(np.uint16))
self.motion_accumulator = cv2.subtract(self.motion_accumulator, 50)
self.motion_accumulator = np.clip(self.motion_accumulator, 0, 255)
final_mask = (self.motion_accumulator > 20).astype(np.uint8) * 255
final_mask = cv2.morphologyEx(final_mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8))
if not cv2.hasNonZero(final_mask):
return []
contours, _ = cv2.findContours(final_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
boxes = [cv2.boundingRect(c) for c in contours]
return filter_boxes(boxes)
+2 -1
View File
@@ -36,7 +36,7 @@ class Main:
def calibrate_camera(self):
self.select_camera()
self.find_roads()
self.estimate_speed()
# self.estimate_speed()
def find_roads(self):
all_roads = self.cache.get("roads", dict())
@@ -61,6 +61,7 @@ class Main:
pass
def main(self):
self.cache.clear()
self.calibrate_camera()