zircon/detector/detector.py
2025-04-04 03:35:58 +07:00

118 lines
4.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import cv2
class BaseDetector:
# интервал между заменой кадров при определении движения
FRAME_PERSIST = 3
STATUS_PERSIST = 6
# пороговое значение размера контура движущегося объекта
CONTOUR_TRESHOLD = 10
# сохраненный кадр для сравнения
frame_check = []
status_list = []
# вывод дополнительной информации
calibration = 1
def __init__(self, path, top, bottom, left, right):
self.path = path
self.top = top
self.bottom = bottom
self.left = left
self.right = right
def find_contours(self, img):
blur = cv2.GaussianBlur(img, (5, 5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
return contours
def contour_treshold(self, contours):
for contour in contours:
contourArea = cv2.contourArea(contour)
if contourArea < self.CONTOUR_TRESHOLD:
return True, None
return False, None
def contour_treshold_info(self, contours) -> tuple([bool, dict]):
max_contour, min_contour = 0, 10**5
sum_contour = 0
max_contour_array = []
contours_tr = []
for contour in contours:
contourArea = cv2.contourArea(contour)
sum_contour += contourArea
if contourArea > max_contour:
max_contour = contourArea
max_contour_array = contour
if contourArea < min_contour:
min_contour = contourArea
if contourArea > self.CONTOUR_TRESHOLD:
contours_tr.append(contour)
info = {'max_contour': max_contour,
'min_contour': min_contour,
'average': sum_contour / max(1, len(contours))}
return (max_contour > self.CONTOUR_TRESHOLD), info
def find_moving_object(self, img):
"""
Сравнивает новый кадр с кадром сохраненным ранее
возвращает координаты прямоугольных контуров движущихся объектов
"""
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
self.frame_check.append(img)
if len(self.frame_check)>self.FRAME_PERSIST:
self.frame_check.pop(0)
diff = cv2.absdiff(self.frame_check[0], img)
contours = self.find_contours(diff)
return (self.contour_treshold_info(contours) if self.calibration
else self.contour_treshold(contours))
def draw(self):
self.frame = cv2.rectangle(self.frame, (self.left, self.top), (self.frame.shape[1] - self.right, self.frame.shape[0] - self.bottom),
(255,0,0), 3)
color = (0, 255, 0) if self.status else (0, 0, 255)
self.frame = cv2.rectangle(self.frame, (self.left, self.top), (self.frame.shape[1] - self.right, self.frame.shape[0] - self.bottom),
color, 3)
def show(self):
cv2.imshow('test', self.frame)
cv2.waitKey(1)
def run(self):
self.cam = cv2.VideoCapture(self.path)
frame_width = int(self.cam.get(3))
frame_height = int(self.cam.get(4))
size = (frame_width, frame_height)
while True:
frame_exists, self.frame = self.cam.read()
if not frame_exists:
break
self.frame_margins = self.frame[self.top: self.frame.shape[0] - self.bottom,
self.left: self.frame.shape[1] - self.right]
self.moving_detected, self.info_moving = self.find_moving_object(self.frame_margins)
self.status_list.append(self.moving_detected)
if len(self.status_list)>self.STATUS_PERSIST:
self.status_list.pop(0)
self.status = (sum(self.status_list)/len(self.status_list))>0.5
print(self.status, self.info_moving)
result.write(self.frame)
result.release()
if __name__ == '__main__':
path = ""
#0 top=150, bottom=300, left=900, right=150
#1 top=450, bottom=100, left=50, right=800
#2 top=150, bottom=200, left=520, right=0
#3 top=100, bottom=100, left=20, right=20
#4 top=0, bottom=250, left=950, right=0
detector1 = BaseDetector(path, top=150, bottom=200, left=520, right=0)
detector1.run()