zircon/service/detector.py
za_litvu 5b536d76ad добавлен проект джанго, настроены модели базы данных
добавлен инструмент для разметки изображений (labelme)
интегрирован и видоизменен код использованый в прототипе
2025-02-26 13:44:23 +07:00

91 lines
3.6 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
from line_profiler import profile
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 run(self):
while True:
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
if __name__ == '__main__':
path = "video/ScreenRecorderProject5.mkv"
detector1 = BaseDetector(path, top=150, bottom=200, left=520, right=0)
detector1.run()