雜七雜八(2):簡單的加聖誕帽的程式,python3+opencv3.4
阿新 • • 發佈:2018-11-22
簡單的加聖誕帽的程式,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格式的帽子圖片。以下是隨手測試的幾張人臉效果
如有侵權請留言,我會刪除。