Files
TrafficAnalyzer/analyzer.py
T
2025-05-22 16:47:31 +02:00

101 lines
4.3 KiB
Python

import cv2
import numpy as np
class Analyzer:
def __init__(self):
self.motion_accumulator = None
self.gray_prev = None
self.bgsub = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=50, detectShadows=False)
self.feature_params = dict(maxCorners=100, qualityLevel=0.3, minDistance=7, blockSize=7)
self.lk_params = dict(winSize=(15, 15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
self.color = np.random.randint(0, 255, (100, 3))
self.old_gray = None
self.p0 = None
self.mask = None
self.lines = []
self.history_length = 5
self.mask_history = []
def analyze_frame(self, frame):
if self.old_gray is None:
self.gray_prev = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
self.motion_accumulator = np.zeros_like(self.gray_prev, dtype=np.uint16)
fg_mask = self.bgsub.apply(frame)
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
# --- Optical flow computation ---
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(
self.gray_prev, gray, None,
pyr_scale=0.5, levels=3, winsize=15,
iterations=3, poly_n=5, poly_sigma=1.2, flags=0
)
gray_prev = gray.copy()
magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
motion_mask = (magnitude > 1.0).astype(np.uint8) * 255
# --- Combine background and optical flow masks ---
combined_mask = cv2.bitwise_and(fg_mask, motion_mask)
# --- Update motion accumulator (temporal smoothing) ---
self.motion_accumulator = cv2.add(self.motion_accumulator, combined_mask.astype(np.uint16))
self.motion_accumulator = cv2.subtract(self.motion_accumulator, 1) # decay by 1
self.motion_accumulator = np.clip(self.motion_accumulator, 0, 255)
motion_stable = (self.motion_accumulator > 20).astype(np.uint8) * 255
contours, _ = cv2.findContours(motion_stable, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
final_mask = np.zeros_like(motion_stable)
for cnt in contours:
area = cv2.contourArea(cnt)
if 500 < area < 50000:
cv2.drawContours(final_mask, [cnt], -1, 255, -1)
output = frame.copy()
output[final_mask == 255] = [0, 255, 0] # highlight moving areas in green
cv2.imshow("Detected Motion", output)
cv2.imshow("Final Mask", final_mask)
def analyze_frame_old(self, frame):
if self.old_gray is None:
self.old_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
self.p0 = cv2.goodFeaturesToTrack(self.old_gray, mask=None, **self.feature_params)
self.mask = np.zeros_like(frame)
fgmask = self.bgsub.apply(frame)
background = self.bgsub.getBackgroundImage()
self.mask_history.append(fgmask)
if len(self.mask_history) > self.history_length:
self.mask_history.pop(0)
persistent_mask = np.sum(self.mask_history, axis=0)
threshold = int(self.history_length * 0.6)
persistent_mask = (persistent_mask >= threshold * 255).astype(np.uint8) * 255
fg = cv2.bitwise_and(frame, frame, mask=persistent_mask)
cv2.imshow("Foreground", fg)
cv2.imshow('Background', background)
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
p1, st, err = cv2.calcOpticalFlowPyrLK(self.old_gray, frame_gray,
self.p0, None, **self.lk_params)
good_new = None
good_old = None
if p1 is not None:
good_new = p1[st==1]
good_old = self.p0[st==1]
lines = []
for i, (new, old) in enumerate(zip(good_new, good_old)):
a, b = new.ravel()
c, d = old.ravel()
self.mask = cv2.line(self.mask, (int(a), int(b)), (int(c), int(d)), self.color[i].tolist(), 2)
lines.append(((int(a), int(b)), (int(c), int(d))))
new_lines = [t for t in lines if t[0] != t[1]]
# print(analyze_frame.flow_params["lines"])
img = cv2.add(frame, self.mask)
cv2.imshow('Optical Flow', img)
self.old_gray = frame_gray.copy()
self.p0 = good_new.reshape(-1, 1, 2)