Skip to content

Instantly share code, notes, and snippets.

@ecodrive-18
Created December 4, 2020 23:59
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 ecodrive-18/f62cfe853747f8196d7fe8ecd16ace1e to your computer and use it in GitHub Desktop.
Save ecodrive-18/f62cfe853747f8196d7fe8ecd16ace1e to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
import datetime
import time
cap = cv2.VideoCapture(2)
cascade_path = "path/to/haarcascade_frontalface_alt.xml"
cascade = cv2.CascadeClassifier(cascade_path)
index = 0
img_list = []
img_size = 700
image_number = 45
## microseconds
interval = 70000
## seconds
actual_interval = 0
# Load image
for i in range(0,image_number):
src = "src/laugh" + str(i).zfill(2) + ".png"
img = cv2.imread(src,-1)
rate = img.shape[0] / img.shape[1]
img = cv2.resize(img,(img_size,int(img_size*rate)))
img_list.append(img)
while(True):
start = datetime.datetime.now()
# Capture frame-by-frame
ret, frame = cap.read()
# Detect face
facerect = cascade.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=2, minSize=(250,250))
# Prepare image
img = img_list[index]
width, height = img.shape[0:2]
# Extract α channel
mask = img[:,:,3]
mask = cv2.cvtColor(mask,cv2.COLOR_GRAY2BGR)
img = img[:,:,:3]
# Image composition
if len(facerect) > 0:
for rect in facerect:
x = int((rect[1] + rect[3] / 2) - (width / 2))
y = int((rect[0] + rect[2] / 2) - (height / 2))
try:
frame[x:x+width,y:y+height] = np.uint8(frame[x:x+width,y:y+height] * (1 - mask / 255.0))
frame[x:x+width,y:y+height] = frame[x:x+width,y:y+height] + np.uint8(img * (mask / 255.0))
except:
pass
# Display the result frame
cv2.imshow('laugh',frame)
# Increment index
index = (index + 1) % image_number
# Quit when 'q' key pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Adjust fps
spend_time = datetime.datetime.now() - start
actual_interval = (interval - spend_time.microseconds) / 1000000
if actual_interval > 0 :
time.sleep(actual_interval)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment