201 lines
7.2 KiB
Python
201 lines
7.2 KiB
Python
import cv2
|
||
import os
|
||
import time
|
||
import requests
|
||
from line_profiler import profile
|
||
|
||
class BaseDetector:
|
||
# интервал между заменой кадров при определении движения
|
||
FRAME_PERSIST = 3
|
||
# пороговое значение размера контура движущегося объекта
|
||
CONTOUR_TRESHOLD = 10000
|
||
# сохраненный кадр для сравнения
|
||
frame_check = None
|
||
check_num = 0
|
||
# вывод дополнительной информации
|
||
calibration = 0
|
||
|
||
@profile
|
||
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
|
||
|
||
@profile
|
||
def contour_treshold(self, contours):
|
||
for contour in contours:
|
||
contourArea = cv2.contourArea(contour)
|
||
if contourArea < self.CONTOUR_TRESHOLD:
|
||
return True, None
|
||
return False, None
|
||
|
||
@profile
|
||
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)),
|
||
'contour': contours,
|
||
'max_contour_array': max_contour_array,
|
||
'contours_tr': contours_tr}
|
||
return (max_contour > self.CONTOUR_TRESHOLD), info
|
||
|
||
@profile
|
||
def find_moving_object(self, img):
|
||
"""
|
||
Сравнивает новый кадр с кадром сохраненным ранее
|
||
возвращает координаты прямоугольных контуров движущихся объектов
|
||
"""
|
||
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||
if self.check_num == 0 or self.frame_check.shape!=img.shape: # обновление сохраненного кадра
|
||
self.frame_check = img
|
||
self.check_num = self.FRAME_PERSIST
|
||
|
||
self.check_num -= 1
|
||
diff = cv2.absdiff(self.frame_check, img)
|
||
contours = self.find_contours(diff)
|
||
return (self.contour_treshold_info(contours) if self.calibration
|
||
else self.contour_treshold(contours))
|
||
|
||
|
||
class MainDetector(BaseDetector, YoloDetector):
|
||
def __init__(self, rtsp, url_post=None):
|
||
self.yolo_init()
|
||
self.url_post = url_post
|
||
self.rtsp = rtsp
|
||
|
||
self.status_human = False
|
||
self.status = False
|
||
self.time_frame = 0
|
||
self.read_time = 0
|
||
|
||
self.human_contours = []
|
||
self.moving_detected = None
|
||
self.frame_human = None
|
||
self.frame = None
|
||
self.top = 40
|
||
self.bottom = 0
|
||
self.left = 50
|
||
self.right = 20
|
||
self.frame_time_between = 0.3
|
||
self.FRAME_PERSIST = 3
|
||
self.CONTOUR_TRESHOLD = 300
|
||
self.calibration = 1
|
||
|
||
super().__init__()
|
||
self.cam_connect()
|
||
|
||
@profile
|
||
def cam_connect(self, retry=3):
|
||
if retry<0:
|
||
print('Error connecting to rtsp: ',self.rtsp)
|
||
quit()
|
||
self.cam = cv2.VideoCapture(self.rtsp)
|
||
if not self.cam.isOpened():
|
||
return self.cam_connect(retry=retry-1)
|
||
self.cam.set(3, 640)
|
||
self.cam.set(4, 640)
|
||
return True
|
||
|
||
@profile
|
||
def frame_read(self, retry=3):
|
||
if retry<0 and self.cam_connect():
|
||
return self.frame_read()
|
||
|
||
frame_exists, self.frame = self.cam.read()
|
||
if self.frame is None:
|
||
return self.frame_read(retry=retry-1)
|
||
self.read_time = time.time()
|
||
return True
|
||
|
||
@profile
|
||
def find_moving_in_sub_stream(self):
|
||
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)
|
||
|
||
@profile
|
||
def find_human_in_main_stream(self):
|
||
status_human, self.human_contours = self.find_human(self.frame)
|
||
self.status_human = bool(status_human)
|
||
|
||
@profile
|
||
def send_info(self):
|
||
if self.status==self.status_human:
|
||
return
|
||
self.status = self.status_human
|
||
data = {"status": self.status, 'cam': '22'}
|
||
print(data)
|
||
if self.url_post is not None:
|
||
requests.put(url_post, json.dumps(data))
|
||
|
||
@profile
|
||
def frame_draw(self):
|
||
self.frame = cv2.putText(self.frame, f'status: {self.status_human}', (50, 50), cv2.FONT_HERSHEY_SIMPLEX,
|
||
1, (0, 0, 0), 2, cv2.LINE_AA)
|
||
for contour in self.human_contours:
|
||
contour_int = list(map(int, contour))
|
||
self.frame = cv2.rectangle(self.frame,
|
||
contour_int[:2], contour_int[2:],
|
||
(0, 0, 255), 3)
|
||
@profile
|
||
def frame_show(self):
|
||
if self.frame is not None:
|
||
# self.frame_main = cv2.resize(self.frame_main, (320, 320))
|
||
cv2.imshow('main', self.frame)
|
||
# if self.frame_sub is not None:
|
||
# cv2.imshow('sub', self.frame_sub)
|
||
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||
quit()
|
||
|
||
@profile
|
||
def detector_step(self):
|
||
self.find_moving_in_sub_stream()
|
||
if self.moving_detected != self.status_human:
|
||
self.find_human_in_main_stream()
|
||
if self.moving_detected == self.status_human:
|
||
self.send_info()
|
||
|
||
@profile
|
||
def run(self, count=0):
|
||
step = int(count > 0)
|
||
while count >= 0:
|
||
self.frame_read()
|
||
if time.time()-self.time_frame<self.frame_time_between:
|
||
continue
|
||
self.time_frame = time.time()
|
||
self.detector_step()
|
||
if self.calibration:
|
||
self.frame_draw()
|
||
self.frame_show()
|
||
count -= step
|
||
|
||
|
||
if __name__ == '__main__':
|
||
login = os.environ.get('CAM_LOGIN')
|
||
password = os.environ.get('CAM_PASSWORD')
|
||
host = os.environ.get('CAM_HOST')
|
||
port = os.environ.get('CAM_PORT')
|
||
|
||
rtsp = f"rtsp://{login}:{password}@{host}:{port}/view/sub"
|
||
# /api/v2/service/put_camera_event/
|
||
url_post = os.environ.get('URL_POST', None)
|
||
|
||
detector1 = MainDetector(rtsp, url_post)
|
||
detector1.run() |