118 lines
4.5 KiB
Python
118 lines
4.5 KiB
Python
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]]:
|
|
yolo_cars = self.yolo.detect(image)
|
|
flow_cars = self.flow.detect(image)
|
|
img = image.copy()
|
|
for car in yolo_cars:
|
|
cv2.rectangle(img, (car[0], car[1]), (car[2], car[3]), (255, 0, 0), 2)
|
|
for car in flow_cars:
|
|
cv2.rectangle(img, (car[0], car[1]), (car[2], car[3]), (0, 0, 255), 2)
|
|
cv2.imshow('Cars', img)
|
|
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, learningRate=0.001)
|
|
|
|
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 > 0.8).astype(np.uint8) * 255
|
|
|
|
#TODO: maybe change mask
|
|
combined_mask = cv2.bitwise_and(fg_mask, motion_mask)
|
|
#combined_mask = motion_mask
|
|
|
|
self.motion_accumulator = cv2.add(self.motion_accumulator, combined_mask.astype(np.uint16))
|
|
self.motion_accumulator = cv2.subtract(self.motion_accumulator, 70)
|
|
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)
|