圣诞节来了,想给头像添加圣诞帽。如果它不是头像,请添加一个圣诞老人来陪伴它。使用Python为头像添加圣诞帽。看完大概是大神2017年的一篇文章:https://zhuanlan.zhihu.com/p/32283641人脸检测的主要流程素材准备和人脸关键点检测调整大小,加个帽子使用dlib的frontalfacedetector检测人脸,使用dlib提供的模型提取人脸的五个关键点#dlibfacekeypointdetectorpredictor\_path="shape\_predictor\_5\_face\_landmarks.dat"predictor=dlib.shape\_predictor(predictor\_path)#dlib正面人脸检测器detector=dlib.get\_frontal\_face\_detector()#正面人脸检测dets=detector(img,1)#如果检测到Tofaceiflen(dets)>0:forddets:x,y,w,h\=d.left(),d.top(),d.right()-d.left(),d.bottom()-d.top()#x,y,w,h=faceRectcv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2,8,0)#关键点检测,5关键点shape=predictor(img,d)forpointinshape.parts():cv2.circle(img,(point.x,point.y),3,color=(0,255,0))cv2.imshow("image",img)cv2.waitKey()调整s帽子的尺寸,在戴帽子的眼角处取两个点,找中心作为放置帽子的x方向的参考坐标,y方向的坐标用y坐标表示脸部框架上的线条。然后我们根据人脸检测检测到的人脸大小来调整帽子的大小,让帽子的大小合适。#选择左右眼角的点point1=shape.part(0)point2=shape.part(2)#求两点的中心eyes\_center=((point1.x+point2.x)//2,(point1.y+point2.y)//2)#cv2.circle(img,eyes\_center,3,color=(0,255,0))#cv2.imshow("image",img)#cv2.waitKey()#根据人脸大小调整hatsizefactor=1.5resized\_hat\_h=int(round(rgb\_hat.shape\[0\]\*w/rgb\_hat.shape\[1\]\*factor))resized\_hat\_w=int(round(rgb\_hat.shape\[1\]\*w/rgb\_hat.shape\[1\]\*factor))ifresized\_hat\_h>y:resized\_hat\_h=y\-1#根据脸的大小调整帽子的大小不能准确识别不相关的,都加了logo。(即在右下角添加小图标)。为避免单调,图标中随机选取小图标:图标位置也可以根据代码的大小和位置调整如下:#watermarkimagenum=random.randint(1,5)logo=Image.open("img\_icon/santa\_"+str(num)+".png")img=Image.open(imgPath)print(img.size,logo.size)#layerlayer=Image.new("RGBA",img.size,(255,255,255,0))layer.paste(logo,(img.size\[0\]-logo.size\[0\],img.size\[1\]-logo.size\[1\]))#Overrideimg\_after=Image.composite(layer,img,layer)#img\_after.show()img\_after.save(outImgePath)结果通过以下代码得到:关注公众号,回复:20191224或圣诞节
