OpenCV-Python系列·第二十三集:戴眼镜

Tip:1、先检测面部;2、在检测眼镜,并确定眼镜的坐标;3、制作掩膜。

注:掩膜的size一定要跟src的一致。

# -*- coding: utf-8 -*-
"""
Created on Thu Sep 13 16:50:40 2018

@author: Administrator
"""

import cv2
import numpy as np

#加载面部配置文件
face_cascade = cv2.CascadeClassifier("./data/haarcascades/haarcascade_frontalface_alt.xml")
eye_cascade = cv2.CascadeClassifier("./data/haarcascades/haarcascade_eye.xml")
if face_cascade.empty():
    raise IOError("Cannot load the face's xml file.")
if face_cascade.empty():
    raise IOError("Cannot load the eye's xml file.")

##加载眼镜
sunglasses_img = cv2.imread("mask.jpg")
cv2.imshow('Glasses',sunglasses_img)

#加载面部图像
img = cv2.imread("james.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('James',img)
print(img.shape)
cv2.imshow('gray',gray)
print(gray.shape)

#保存中心位置
centers = []
faces = face_cascade.detectMultiScale(gray)

##获取目标位置
for (x,y,w,h) in faces:
    roi_gray = gray[y:h+y,x:w+x]
    roi_color = gray[y:y+h,x:x+w]
    cv2.imshow('roi_color',roi_color)
    #检测眼睛位置
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (eye_x,eye_y,eye_w,eye_h) in eyes:
#        eye = roi_gray[eye_y:eye_y+int(eye_y+0.5*eye_h),
#                       eye_x:eye_x+int(eye_x+0.5*eye_w)]
#        cv2.imshow('eye',eye)
        centers.append((x+int(eye_x+0.5*eye_w),
                        y+int(eye_y+0.5*eye_h)))

#判断是否得到了眼睛的中心位置
if len(centers) > 0:
    sunglasses_width = 2.12*abs(centers[1][0]-centers[0][0])
    overlay_img = np.ones(img.shape,np.uint8)*255
    
    cv2.imshow('overlay',overlay_img)
    
    h,w = sunglasses_img.shape[:2]
    scaling_factor = sunglasses_width/w
    overlay_sunglasses = cv2.resize(sunglasses_img,None,
                                    fx = scaling_factor,
                                    fy = scaling_factor,
                                    interpolation = cv2.INTER_AREA)
    cv2.imshow('overlay_glasses',overlay_sunglasses)
    
    
    x = centers[0][0] if centers[1][0]

 

你可能感兴趣的:(OpenCV-Python)