Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- face_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_alt.xml')
- face_mask = cv2.imread('images/p2.png')
- h_mask, w_mask = face_mask.shape[:2]
- if face_cascade.empty():
- raise IOError('Unable to load the face cascade classifier xml file')
- cap = cv2.VideoCapture(0)
- scaling_factor = 0.5
- while True:
- ret, frame = cap.read()
- frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
- gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
- face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)
- for (x,y,w,h) in face_rects:
- if h > 0 and w > 0:
- h, w = int(2.0*h), int(1.7*w)
- y -= int(0.3*h)
- x -= int(0.2*w)
- face_mask_small = cv2.resize(face_mask, (w,h), interpolation=cv2.INTER_AREA)
- # Trimming the face mask when it goes beyond frame boundaries
- frame_height, frame_width = frame.shape[:2]
- trim_top, trim_bottom = 0, 0
- if (y + h > frame_height):
- trim_bottom = (y + h) - frame_height
- if (y < 0):
- trim_top = -y
- trim_left, trim_right = 0, 0
- if (x + w > frame_width):
- trim_right = (x + w) - frame_width
- if (x < 0):
- trim_left = -x
- face_mask_small = face_mask_small[trim_top:(h - trim_bottom),trim_left:(w - trim_right)]
- frame_roi = frame[(y+trim_top):(y+h-trim_bottom), (x+trim_left):(x+w-trim_right)]
- gray_mask = cv2.cvtColor(face_mask_small, cv2.COLOR_BGR2GRAY)
- ret, mask = cv2.threshold(gray_mask, 220, 255, cv2.THRESH_BINARY_INV)
- mask_inv = cv2.bitwise_not(mask)
- print("mask_small",face_mask_small.shape)
- print("mask_roi",frame_roi.shape)
- masked_frame = cv2.bitwise_and(frame_roi, frame_roi, mask=mask_inv)
- masked_face = cv2.bitwise_and(face_mask_small, face_mask_small, mask=mask)
- frame_roi[:,:] = cv2.add(masked_face, masked_frame)
- #cv2.namedWindow("window", cv2.WND_PROP_FULLSCREEN)
- #cv2.setWindowProperty("window",cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN)
- cv2.imshow('Face Detector', frame)
- c = cv2.waitKey(1)
- if c == 27:
- break
- cap.release()
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement