diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..654b903 --- /dev/null +++ b/.gitignore @@ -0,0 +1,162 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so +myenv/ +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + diff --git a/README.md b/README.md index 66b898a..e69de29 100644 --- a/README.md +++ b/README.md @@ -1,2 +0,0 @@ -# zircon - diff --git a/detector.py b/detector.py new file mode 100644 index 0000000..7f7ab55 --- /dev/null +++ b/detector.py @@ -0,0 +1,126 @@ +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 + + + @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))} + return (max_contour > self.CONTOUR_TRESHOLD), info + + @profile + 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) + result = cv2.VideoWriter('filename.mp4', + cv2.VideoWriter_fourcc(*'MP4V'), + 30, size) + 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) + self.draw() + self.show() + result.write(self.frame) + result.release() + + + +if __name__ == '__main__': + path = "video/ScreenRecorderProject5.mkv" + #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() \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e69de29 diff --git a/main.py b/main.py new file mode 100644 index 0000000..43d3112 --- /dev/null +++ b/main.py @@ -0,0 +1,36 @@ +import cv2 +from line_profiler import profile +import time + +class VideoReader: + path = 0 + top = 0 + bottom = 0 + left = 0 + right = 0 + read_time = None + + def __init__(self, path) -> None: + self.path + + def cam_connect(self, retry=3): + if retry<0: + print('Error connecting',self.path) + quit() + self.cam = cv2.VideoCapture(self.path) + if not self.cam.isOpened(): + return self.cam_connect(retry=retry-1) + return True + + 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 + + def frmae_split(self, n): + \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..792e2a1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,12 @@ +numpy==1.26.4 +Django==4.2 +psycopg2-binary==2.9.9 +python-dotenv==1.0.1 +requests +gunicorn==22.0.0 +pydantic==2.10.5 +django-cors-headers +ultralytics==8.2.70 +numpy==1.26.4 +opencv-python-headless==4.10.0.84 +redis