发布于2020-02-10 15:12 阅读(473) 评论(0) 点赞(25) 收藏(5)
随着圣诞的到来,想给给自己的头像加上一顶圣诞帽。如果不是头像,就加一个圣诞老人陪伴。
用Python给头像加上圣诞帽,看了下大概也都是来自2017年大神的文章: https://zhuanlan.zhihu.com/p/32283641
主要流程
素材准备
人脸检测与人脸关键点检测
调整大小,添加帽子
用dlib的正脸检测器进行人脸检测,用dlib提供的模型提取人脸的五个关键点
# dlib人脸关键点检测器
predictor\_path = "shape\_predictor\_5\_face\_landmarks.dat"
predictor = dlib.shape\_predictor(predictor\_path)
# dlib正脸检测器
detector = dlib.get\_frontal\_face\_detector()
# 正脸检测
dets = detector(img, 1)
# 如果检测到人脸
if len(dets)>0:
for d in dets:
x,y,w,h \= d.left(),d.top(), d.right()-d.left(), d.bottom()-d.top()
# x,y,w,h = faceRect
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2,8,0)
# 关键点检测,5个关键点
shape = predictor(img, d)
for point in shape.parts():
cv2.circle(img,(point.x,point.y),3,color=(0,255,0))
cv2.imshow("image",img)
cv2.waitKey()
选取两个眼角的点,求中心作为放置帽子的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()
# 根据人脸大小调整帽子大小
factor = 1.5
resized\_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))
if resized\_hat\_h > y:
resized\_hat\_h = y\-1
# 根据人脸大小调整帽子大小
resized\_hat = cv2.resize(rgb\_hat,(resized\_hat\_w,resized\_hat\_h))
当然有些同学的头像不是人物或不能准确的识别无关,所有添加了标识。(即在右下添加小图标)。
小图标避免单调,是从图标中随机选择一个:
图标位置也可以根据爱好调整大小和位置
代码如下:
# 水印图片
num = random.randint(1, 5)
logo = Image.open("img\_icon/santa\_" + str(num) + ".png")
img = Image.open(imgPath)
print(img.size, logo.size)
# 图层
layer = Image.new("RGBA", img.size, (255, 255, 255, 0))
layer.paste(logo, (img.size\[0\] - logo.size\[0\], img.size\[1\]-logo.size\[1\]))
# 覆盖
img\_after = Image.composite(layer, img, layer)
# img\_after.show()
img\_after.save(outImgePath)
结果如下
作者:小兔子乖乖
链接:https://www.pythonheidong.com/blog/article/230589/2424ffb15be4e800f8f5/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!