DEV Community

El Bruno for Microsoft Azure

Posted on β€’ Originally published at elbruno.com on

7 1

#OpenCV – Detect and blur faces 😁 using DNN in Python 🐍

Hi !

Quick post today: detect a face using a pretrained DNN model and blur the face area. Easy to implement, and also easy to read:

demo of face blur

Code below

# Copyright (c) 2022
# Author : Bruno Capuano
# Create Time : 2022 Feb
# Change Log :
# - Open a camera feed from a local webcam and analyze each frame to detect faces using DNN
# - When a face is detected, the app will blur the face zone
# - Download model and prototxt from https://github.com/spmallick/learnopencv/tree/master/FaceDetectionComparison/models
# - Press [D] to start/stop face detection
# - Press [Q] to quit the app
#
# The MIT License (MIT)
#
# 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.
import cv2
import time
video_capture = cv2.VideoCapture(0)
time.sleep(2)
# -----------------------------------------------
# Face Detection using DNN Net
# -----------------------------------------------
# detect faces using a DNN model
# download model and prototxt from https://github.com/spmallick/learnopencv/tree/master/FaceDetectionComparison/models
def detectFaceOpenCVDnn(net, frame, conf_threshold=0.7):
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), [104, 117, 123], False, False,)
net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > conf_threshold:
x1 = int(detections[0, 0, i, 3] * frameWidth)
y1 = int(detections[0, 0, i, 4] * frameHeight)
x2 = int(detections[0, 0, i, 5] * frameWidth)
y2 = int(detections[0, 0, i, 6] * frameHeight)
bboxes.append([x1, y1, x2, y2])
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), int(round(frameHeight / 150)), 8,)
top=x1
right=y1
bottom=x2-x1
left=y2-y1
# blurry rectangle to the detected face
face = frame[right:right+left, top:top+bottom]
face = cv2.GaussianBlur(face,(23, 23), 30)
frame[right:right+face.shape[0], top:top+face.shape[1]] = face
return frame, bboxes
# load face detection model
modelFile = "models/res10_300x300_ssd_iter_140000_fp16.caffemodel"
configFile = "models/deploy.prototxt"
net = cv2.dnn.readNetFromCaffe(configFile, modelFile)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
detectionEnabled = False
while True:
try:
_, frameOrig = video_capture.read()
frame = cv2.resize(frameOrig, (640, 480))
if(detectionEnabled == True):
outOpencvDnn, bboxes = detectFaceOpenCVDnn(net, frame)
cv2.imshow('@ElBruno - Face Blur usuing DNN', frame)
except Exception as e:
print(f'exc: {e}')
pass
# key controller
key = cv2.waitKey(1) & 0xFF
if key == ord("d"):
detectionEnabled = not detectionEnabled
if key == ord("q"):
break
video_capture.release()
cv2.destroyAllWindows()

That’s it, sample using DNN. Next challenge will be to do this in F#.

Face Recognition and Face Detection series in Python

  1. Detecting Faces with 20 lines in Python
  2. Face Recognition with 20 lines in Python
  3. Detecting Facial Features with 20 lines in Python
  4. Facial Features and Face Recognition with 20 lines in Python
  5. Performance improvements with code
  6. Resize the camera input with OpenCV
  7. Working with Haar Cascades and OpenCV
  8. Detect and blur faces 😁 using haar cascades
  9. Detect and blur faces 😁 using DNN

Original Post

Happy coding!

Greetings

El Bruno


Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs