Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
markusschmitz53 committed Aug 27, 2023
0 parents commit 49b3ee6
Show file tree
Hide file tree
Showing 8 changed files with 410 additions and 0 deletions.
163 changes: 163 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
*.iml
.idea
*.mp4

# C extensions
*.so

# 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/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Markus Schmitz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# demo-face-blur
Video anonymization software in Python that blurs people's faces using OpenCV, YuNet.

## Requirements
- Python 3.9
- OpenCV 4.7.0

OpenCV is not part of requirements.txt as I am using a custom build with CUDA support.
You should be able to `pip install opencv-python==4.7.0`

## Usage
1. add model files to `models` folder. Download:
[face_detection_yunet_2022mar.onnx](https://github.com/opencv/opencv_zoo/blob/7e062e54cf5410c09b795ff71b4a255e58498c79/models/face_detection_yunet/face_detection_yunet_2022mar.onnx).
2. `pip install -r requirements.txt`
3. install OpenCV (see Requirements)
4. run `python main.py input.mp4`

## Credits
Multi-threading video display code Copyright (c) 2018 Najam Syed (MIT License)
https://nrsyed.com/2018/07/05/multithreading-with-opencv-python-to-improve-video-processing-performance/
https://github.com/nrsyed/computer-vision/tree/master/multithread
34 changes: 34 additions & 0 deletions VideoShow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
Copyright (c) 2018 Najam Syed
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@see https://github.com/nrsyed/computer-vision
"""

from threading import Thread
import cv2


class VideoShow:
"""
Class that continuously shows a frame using a dedicated thread.
"""

def __init__(self, frame=None):
self.frame = frame
self.stopped = False

def start(self):
Thread(target=self.show, args=()).start()
return self

def show(self):
while not self.stopped:
cv2.imshow("demo-face-blur", self.frame)
if cv2.waitKey(1) == ord("q"):
self.stopped = True

def stop(self):
self.stopped = True
140 changes: 140 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""
Copyright (c) 2023, Markus Schmitz
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import os
import cv2
import time
import logging
import argparse
import numpy as np
from pathlib import Path
from imutils.video import FileVideoStream, FPS
from VideoShow import VideoShow
from util import log_timing_info, anonymize_roi
from alive_progress import alive_bar

show_video = True
default_frame_width = 1280
fvs_queue_size = 64
kernel_size = (20, 20)
device = 'cuda:0'
use_yolo = False
resize_video = False
parser = argparse.ArgumentParser()
parser.add_argument("path", nargs="?", type=Path)
args = parser.parse_args()

logging.basicConfig(
format='%(asctime)s %(message)s',
datefmt='%d.%m.%y %H:%M',
stream=os.sys.stdout,
)
logging.getLogger().setLevel(logging.INFO)


def process_file(input_video):
datetime = time.strftime("%Y-%m-%d_%H%M")
input_video_path = str(input_video.resolve())

logging.info(f'Processing {input_video} start time {datetime}')

fvs = FileVideoStream(input_video_path, None, fvs_queue_size).start()

while not fvs.more():
time.sleep(0.1)

fps = FPS().start()
frame = fvs.read()

assert len(frame.shape) == 3, logging.critical('Frame has invalid shape')
frame_height, frame_width, _ = frame.shape
assert frame_height > 0, logging.critical('Frame height too low')
assert frame_width > 0, logging.critical('Frame width too low')
aspect_ratio = frame_width / frame_height
frame_count = int(fvs.stream.get(cv2.CAP_PROP_FRAME_COUNT))

if show_video:
video_shower = VideoShow(frame).start()

target_frame_width = frame_width
target_frame_height = frame_height

if resize_video:
target_frame_width = default_frame_width
target_frame_height = int(target_frame_width / aspect_ratio)

logging.info('Original video dimensions %dx%d' % (frame_width,
frame_height))

if resize_video:
logging.info('Applying video dimensions %dx%d' % (target_frame_width,
target_frame_height))

yunet_model = cv2.FaceDetectorYN_create(
model='models/face_detection_yunet_2022mar.onnx',
config='',
input_size=[target_frame_width, target_frame_height],
score_threshold=0.7,
nms_threshold=0.8,
top_k=40)

frames_processed = 0
try:
with alive_bar(frame_count) as bar:
while fvs.running():
frame = fvs.read()
if frame is None:
fps.update()
bar()
continue

_, faces = yunet_model.detect(frame)
faces = faces if faces is not None else []
faces = np.asarray(faces, dtype=np.int16)

for face in faces:
x1, y1, w, h = face[:4]
x2 = x1 + w
y2 = y1 + h

frame = anonymize_roi(frame, x1, y1, x2, y2)

# write frame to output video file here

if show_video:
video_shower.frame = frame

fps.update()
frames_processed += 1
bar()
return True
except KeyboardInterrupt:
return False
finally:
fps.stop()
fvs.stop()
if show_video:
video_shower.stop()
if frames_processed > 0:
log_timing_info(fps, frames_processed)


def main():
if args.path is None:
logging.critical("Missing input video path")
raise SystemExit(1)
else:
input_video = Path(args.path)
if not input_video.exists():
logging.critical("Input file doesn't exist")
raise SystemExit(1)
process_file(input_video)

cv2.destroyAllWindows()


if __name__ == '__main__':
main()
Empty file added models/.gitkeep
Empty file.
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
alive_progress==3.1.2
imutils==0.5.4
numpy==1.24.2
Loading

0 comments on commit 49b3ee6

Please sign in to comment.