Skip to content

Instantly share code, notes, and snippets.

@Thimira
Created May 8, 2020 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thimira/070635d5e711840a9816207c050b4ac0 to your computer and use it in GitHub Desktop.
Save Thimira/070635d5e711840a9816207c050b4ac0 to your computer and use it in GitHub Desktop.
# Using a circular mask as the blur area to automatically blur the face in a video, giving it a more cleaner look.
# We're using OpenCV, and Dlib with Python.
# See tutorial here: https://youtu.be/1p1lUyLGB2E
import numpy as np
import cv2
import dlib
video_capture = cv2.VideoCapture(1)
detector = dlib.get_frontal_face_detector()
blurred = False
framed = False
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
# create a temp image and a mask to work on
temp_img = frame.copy()
mask_shape = (frame.shape[0], frame.shape[1], 1)
mask = np.full(mask_shape, 0, dtype=np.uint8)
if (ret):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
for rect in rects:
x = rect.left()
y = rect.top()
x1 = rect.right()
y1 = rect.bottom()
h = rect.height()
w = rect.width()
if blurred:
temp_img[y:y1, x:x1] = cv2.blur(temp_img[y:y1, x:x1], (25, 25))
# create the circle in the mask and in the temp_img, notice the one in the mask is full
cv2.circle(mask, (int((x + x + w)/2), int((y + y + h)/2)), int(h / 2), (255), -1)
if framed:
cv2.circle(temp_img, ( int((x + x + w )/2), int((y + y + h)/2 )), int (h / 2), (0, 255, 0), 5)
# apply the mask and combine
mask_inv = cv2.bitwise_not(mask)
img_bg = cv2.bitwise_and(frame, frame, mask=mask_inv)
img_fg = cv2.bitwise_and(temp_img, temp_img, mask=mask)
combined = cv2.add(img_bg, img_fg)
# Display the resulting frame
cv2.imshow('Video Feed', combined)
ch = 0xFF & cv2.waitKey(1)
# press "b" to toggle blurring.
if ch == ord("b"):
blurred = not blurred
# press "f" to toggle the frame.
if ch == ord("f"):
framed = not framed
# press "q" to quit the program.
if ch == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment