|
#!/usr/bin/python2 |
|
|
|
import cv2 |
|
import numpy as np |
|
|
|
|
|
import PIL |
|
from PIL import Image |
|
|
|
face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml') |
|
eye_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_eye.xml') |
|
imgname = 'hunter2.png' |
|
frame = cv2.imread(imgname) |
|
boggle = cv2.imread("boggle.png", -1) |
|
|
|
boggleGray = cv2.cvtColor(boggle, cv2.COLOR_BGR2GRAY) |
|
ret, orig_mask = cv2.threshold(boggleGray, 10, 255, cv2.THRESH_BINARY) |
|
orig_mask_inv = cv2.bitwise_not(orig_mask) |
|
|
|
boggle = boggle[:,:,0:3] |
|
origBoggleHeight, origBoggleWidth = boggle.shape[:2] |
|
|
|
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
|
faces = face_cascade.detectMultiScale(gray, 1.12, 3) |
|
print(faces) |
|
for (x,y,w,h) in faces: |
|
# cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) |
|
roi_gray = gray[y:y+h, x:x+w] |
|
roi_color = frame[y:y+h, x:x+w] |
|
eyes = eye_cascade.detectMultiScale(roi_gray, 1.12, 3) |
|
# for (ex,ey,ew,eh) in eyes: |
|
# cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) |
|
c = 0 |
|
for (ex, ey, ew, eh) in eyes: |
|
c += 1 |
|
if not (c == 4 or c == 2): |
|
continue |
|
glassesWidth = ew |
|
glassesHeight = eh |
|
scale = 4 |
|
|
|
# Center the glasses on the bottom of the nose |
|
x1 = ex - (ew/scale) |
|
x2 = ex + (ew/scale) + ew |
|
y1 = ey - (eh/scale) |
|
y2 = ey + (eh/scale) + eh |
|
|
|
# Check for clipping |
|
if x1 < 0: |
|
x1 = 0 |
|
if y1 < 0: |
|
y1 = 0 |
|
if x2 > w: |
|
x2 = w |
|
if y2 > h: |
|
y2 = h |
|
|
|
# Re-calculate the width and height of the glasses image |
|
glassesWidth = x2 - x1 |
|
glassesHeight = y2 - y1 |
|
|
|
# Re-size the original image and the masks to the glasses sizes |
|
# calcualted above |
|
glasses = cv2.resize(boggle, (glassesWidth,glassesHeight), interpolation = cv2.INTER_AREA) |
|
mask = cv2.resize(orig_mask, (glassesWidth,glassesHeight), interpolation = cv2.INTER_AREA) |
|
mask_inv = cv2.resize(orig_mask_inv, (glassesWidth,glassesHeight), interpolation = cv2.INTER_AREA) |
|
|
|
# take ROI for glasses from background equal to size of glasses image |
|
roi = roi_color[y1:y2, x1:x2] |
|
|
|
# roi_bg contains the original image only where the glasses is not |
|
# in the region that is the size of the glasses. |
|
roi_bg = cv2.bitwise_and(roi,roi,mask = mask_inv) |
|
|
|
# roi_fg contains the image of the glasses only where the glasses is |
|
roi_fg = cv2.bitwise_and(glasses,glasses,mask = mask) |
|
|
|
# join the roi_bg and roi_fg |
|
dst = cv2.add(roi_bg,roi_fg) |
|
|
|
# place the joined image, saved to dst back over the original image |
|
roi_color[y1:y2, x1:x2] = dst |
|
|
|
# cv2.imshow('frame',frame) |
|
# cv2.waitKey(0) |
|
# cv2.destroyAllWindows() |
|
cv2.imwrite('boggle' + imgname, frame) |