杂七杂八(2):简单的加圣诞帽的程序,python3+opencv3.4

简单的加圣诞帽的程序,python3+opencv3.4


最最最最简单的加圣诞帽的程序,python3+opencv3.4

# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 15:22:14 2017

@author: Elam
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 09:36:07 2017

@author: Elam
"""

import cv2
import numpy as np
face_patterns = cv2.CascadeClassifier('D:\\opencv3.0\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml')
sample_image = cv2.imread('C:\\Users\\Elam\\Desktop\\llll.jpg')
hat=cv2.imread('C:\\Users\\Elam\\Desktop\\lvse.png',cv2.IMREAD_UNCHANGED)
a,b,c,d=cv2.split(hat)
rgb_hat=cv2.merge((a,b,c))
sample_wh=sample_image.shape
temp=float(sample_wh[1]/sample_wh[0])
temp_h=int(1024*temp)
sample_image_res=cv2.resize(sample_image,(temp_h,1024),interpolation=cv2.INTER_CUBIC)
faces = face_patterns.detectMultiScale(sample_image_res,scaleFactor=1.1,minNeighbors=5,minSize=(60, 60))
k_w=faces[0][2]
k_h=faces[0][3]

#####hat
hat_wh=rgb_hat.shape
temp_hat=float(hat_wh[1]/hat_wh[0])
#####改变帽子大小######
temp_hat_h=int((k_w)*4/5*temp_hat)
temp_hat_w=int(k_w*3/5)
###################



res=cv2.resize(rgb_hat,(temp_hat_h,temp_hat_w),interpolation=cv2.INTER_CUBIC)
res_d=cv2.resize(d,(temp_hat_h,temp_hat_w),interpolation=cv2.INTER_CUBIC)
#hsv=cv2.cvtColor(res,cv2.COLOR_BGR2HSV)
#lower_blue=np.array([0,0,0])
#upper_blue=np.array([255,255,253])
#mask = cv2.inRange(hsv, lower_blue, upper_blue)
#erode=cv2.erode(mask,None,iterations=2)
#dilate=cv2.dilate(erode,None,iterations=2)


####改变帽子位置#####
x_new=faces[0][0]+int(k_w/6)
y_new=faces[0][1]-int(k_h*0.65)
center=[y_new,x_new]#在新背景图片中的位置
for i in range(temp_hat_w):
    for j in range(temp_hat_h):
        if res_d[i,j]!=0:#0代表黑色的点
            sample_image_res[center[0]+i,center[1]+j]=res[i,j]#此处替换颜色,为BGR通道
######################

#cv2.imshow('Mask', mask)
#res=cv2.resize(hat,(182,220),interpolation=cv2.INTER_CUBIC)
#WH=res.shape
#mask=cv2.imread('C:\\Users\\Elam\\Desktop\\hat.jpg',0)

#imgROI=sample_image[10:192,10:230]
#sample_image[0:220,0:182]=res
for (x, y, w, h) in faces:
    cv2.rectangle(sample_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imwrite('C:\\Users\\Elam\\Desktop\\test333333.png', sample_image_res)
#cv2.imwrite('C:\\Users\\Elam\\Desktop\\hattttttt.png', hat)

写完才感觉真的很蠢,直接使用了opencv自带的人脸检测库,起初是利用人脸的黄金分割比例企图对帽子进行定位,后来发现他的人脸检测的框有时候会只检测到眉毛并不会框到额头。另外添加了帽子的自适应大小,帽子会根据所检测到的人脸的区域的大小自行拉伸到合适大小,同时还对图片进行了规范化。现在只能说对大部分比较标准的人脸可以做到帽子位置添加正确。想尝试的童鞋可以试试。实际上还试过有背景的帽子图片,做了很多掩膜提取的工作,但是效果都不是很好,最后还是去找了png格式的帽子图片。以下是随手测试的几张人脸效果
如有侵权请留言,我会删除。
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_16019107/article/details/78894369
今日推荐