通知:今年的圣诞节推迟到2021年1月8日,因为圣诞老人到了之后还要被隔离14天。


马上就要圣诞节了,大家想好送什么礼物给自己对象了吗?
因为疫情原因,圣诞老人不能来中国给我们送礼物了,所以今年由我来给大家圣诞礼物——用python给你的头像戴圣诞帽!
我知道网上已经有很多关于这个的代码了,他们一般都是调用cv或者dlib的人脸识别库来实现,但今天我想通过调用百度AI的人脸识别接口来实现。

实现步骤

首先我们需要申请百度AI的密钥,之后就可以通过开发文档来进行人脸识别了。(我之前的一篇文章已经讲的十分清楚了python颜值分析,这里就不再描述。)
其次我们需要一个背景透明的圣诞帽。可以通过ps等软件把圣诞帽抠出来,也可以通过python代码。

python使图片白色背景变透明代码:

这是一个单独的python file,你可以命名为transparent.py

from PIL import Image
def transparent():img = Image.open('hat.jpg')# 图片转换为四通道。第四个通道就是我们要修改的透明度。#RGBA是代表Red(红色)Green(绿色)Blue(蓝色)和Alpha的色彩空间。#如果一个像素的alpha通道数值为0%,那它就是完全透明的(也就是看不见的),而数值为100%则意味着一个完全不透明的像素(传统的数字图像)。img = img.convert('RGBA')# 获取图片像素尺寸width, height = img.sizepix = img.load()#方法load()返回一个用于读取和修改像素的像素访问对象#print(pixel_data[0,0])for i in range(height):for j in range(width):pixel = pix[j, i]r = pixel[0]g = pixel[1]b = pixel[2]a = pixel[3]# 四通道色彩值大于250(白色且不透明),则将像素点变为透明块if r > 245 and g > 245 and b > 245 and a > 250:pix[j, i] = (255, 255, 255, 0)img.save('newhat.png')  # 保存新图片
transparent()

原图:

透明化后:

然后我们需要通过百度AI人脸识别接口得到人脸位置、大小等信息。

获取人脸信息核心代码:

    def face_identification(self):# 人脸检测与属性分析img = self.img_to_base64(self.img_src)request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"post_data = {"image": img,"image_type": "BASE64","max_face_num":10,"face_field": "face_num,face_list",#包括age,beauty,expression,face_shape,gender,glasses,landmark,emotion,face_type,mask,spoofing信息"face_type": "LIVE"#人脸的类型。LIVE表示生活照,IDCARD表示身份证芯片照,WATERMARK表示带水印证件照,CERT表示证件照片,默认LIVE。}access_token = self.get_AccessToken()request_url = request_url + "?access_token=" + access_tokenresponse = requests.post(url=request_url, data=post_data, headers=self.headers)json_result = json.loads(response.text)print(json_result)if json_result['error_code'] == 0:a = 1print('检测到的图片中的人脸数量:',json_result['result']['face_num'])for i in json_result['result']['face_list']:face_info = []print('第{}张人脸信息:'.format(a))a=a+1left=i['location']['left']face_info.append(left)top=i['location']['top']face_info.append(top)width=i['location']['width']face_info.append(width)height=i['location']['height']face_info.append(height)print('人脸区域离左边界的距离:',left)print('人脸区域离上边界的距离:', top)print("人脸区域的宽度:",width )print("人物区域的高度:", height)faces.append(face_info)#print("人物特征点位置:", json_result['result']['face_list'][0]['landmark72'])else:print(json_result['error_code'])print(json_result['error_msg'])

最后我们需要根据人脸信息确定圣诞帽的位置。

确定圣诞帽位置代码:

def addhat(faces,face_image,hat_image):for face in faces:hat = cv2.imread(hat_image, -1)  # 读入完整图片,包括alpha通道。scale = face[3] / hat.shape[0] * 1.4hat = cv2.resize(hat, (0, 0), fx=scale, fy=scale)  # 改变帽子大小x_offset = int(face[0] -10+face[2] / 2 - hat.shape[1] / 2)y_offset = int(face[1] - hat.shape[0]/1)  # 根据人脸坐标调整帽子位置x1, x2 = max(x_offset, 0), min(x_offset + hat.shape[1], face_image.shape[1])y1, y2 = max(y_offset, 0), min(y_offset + hat.shape[0], face_image.shape[0])hat_x1 = max(0, -x_offset)hat_x2 = hat_x1 + x2 - x1hat_y1 = max(0, -y_offset)hat_y2 = hat_y1 + y2 - y1  # 计算贴图位置alpha_h = hat[hat_y1:hat_y2, hat_x1:hat_x2, 3] / 255  # 透明部分的处理alpha = 1 - alpha_hfor c in range(0, 3):face_image[y1:y2, x1:x2, c] = (alpha_h * hat[hat_y1:hat_y2, hat_x1:hat_x2, c] + alpha * face_image[y1:y2, x1:x2,c])  # 按3个通道合并图片return face_image

上面代码参考于网上。

给头像添加圣诞帽完整代码:

这是另一个独立的python file,你可以命名为add_hat.py

# encoding:utf-8
import base64
import json
import requests
import cv2class BaiduAI:def __init__(self, img):self.AK = ""#你的应用API Keyself.SK = ""#你的应用Secret Keyself.img_src = imgself.headers = {"Content-Type": "application/json; charset=UTF-8"}def get_AccessToken(self):#获取Access Tokenhost = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + self.AK + '&client_secret=' + self.SKresponse = requests.get(host, headers=self.headers)json_result = json.loads(response.text)if response:return json_result['access_token']else:print(json_result)return 0def img_to_base64(slef, path):#图片转化为base64with open(path, 'rb') as f:image = f.read()image_base64 = str(base64.b64encode(image), encoding='utf-8')return image_base64def face_identification(self):# 人脸检测与属性分析img = self.img_to_base64(self.img_src)request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"post_data = {"image": img,"image_type": "BASE64","max_face_num":10,"face_field": "face_num,face_list",#包括age,beauty,expression,face_shape,gender,glasses,landmark,emotion,face_type,mask,spoofing信息"face_type": "LIVE"#人脸的类型。LIVE表示生活照,IDCARD表示身份证芯片照,WATERMARK表示带水印证件照,CERT表示证件照片,默认LIVE。}access_token = self.get_AccessToken()request_url = request_url + "?access_token=" + access_tokenresponse = requests.post(url=request_url, data=post_data, headers=self.headers)json_result = json.loads(response.text)print(json_result)if json_result['error_code'] == 0:a = 1print('检测到的图片中的人脸数量:',json_result['result']['face_num'])for i in json_result['result']['face_list']:face_info = []print('第{}张人脸信息:'.format(a))a=a+1left=i['location']['left']face_info.append(left)top=i['location']['top']face_info.append(top)width=i['location']['width']face_info.append(width)height=i['location']['height']face_info.append(height)print('人脸区域离左边界的距离:',left)print('人脸区域离上边界的距离:', top)print("人脸区域的宽度:",width )print("人物区域的高度:", height)faces.append(face_info)#print("人物特征点位置:", json_result['result']['face_list'][0]['landmark72'])else:print(json_result['error_code'])print(json_result['error_msg'])
def addhat(faces,face_image,hat_image):for face in faces:hat = cv2.imread(hat_image, -1)  # 读入完整图片,包括alpha通道。scale = face[3] / hat.shape[0] * 1.5hat = cv2.resize(hat, (0, 0), fx=scale, fy=scale)  # 改变帽子大小x_offset = int(face[0] +face[2] / 2 - hat.shape[1] / 2)y_offset = int(face[1] - hat.shape[0]/1.2)  # 根据人脸坐标调整帽子位置x1, x2 = max(x_offset, 0), min(x_offset + hat.shape[1], face_image.shape[1])y1, y2 = max(y_offset, 0), min(y_offset + hat.shape[0], face_image.shape[0])hat_x1 = max(0, -x_offset)hat_x2 = hat_x1 + x2 - x1hat_y1 = max(0, -y_offset)hat_y2 = hat_y1 + y2 - y1  # 计算贴图位置alpha_h = hat[hat_y1:hat_y2, hat_x1:hat_x2, 3] / 255  # 透明部分的处理alpha = 1 - alpha_hfor c in range(0, 3):face_image[y1:y2, x1:x2, c] = (alpha_h * hat[hat_y1:hat_y2, hat_x1:hat_x2, c] + alpha * face_image[y1:y2, x1:x2,c])  # 按3个通道合并图片return face_image
if __name__ == '__main__':img_file = ''hat_file=''faces=[]demo = BaiduAI(img_file)if(demo.get_AccessToken()):demo.face_identification()print(faces)face_image = cv2.imread(img_file)face_image=addhat(faces,face_image,hat_file)cv2.imwrite('addhat_' + img_file, face_image)

说明:self.AK用你的应用API Key,self.SK用你的应用Secret Key。img_file用你的照片路径,hat_file用你的圣诞帽图片路径。

最终效果

原图:

戴上圣诞帽:

原图:

戴上圣诞帽:

这次的分享到此结束。
圣诞节要到了,送大家三千万。千万要开心,千万要快乐,千万要幸福!!!

python自动给头像添加圣诞帽相关推荐

  1. 圣诞节,教你用Python给微信头像添加一个圣诞帽!

    作者:刘早起 来源:早起Python 圣诞节快到了,每年一到圣诞节就会有很多人的头像上多了一顶小红帽 那么你有想过如何用Python去实现吗? 如果你尝试去搜索,会发现网上教程一大堆,但是由于大多数人 ...

  2. 使用paddlehub给头像添加圣诞帽(GUI版)

    我的前一篇博客:使用PaddleHub给头像添加圣诞帽已经详细介绍了如何使用paddlehub给头像添加一个圣诞帽,但之前的版本由于时间仓促还存在一些问题: 圣诞帽超出头像边界程序会报错 无法识别出人 ...

  3. 微信官方都辟谣,可真有技术人用 AI、大数据实现头像添加圣诞帽了!

    点击上方"CSDN",选择"置顶公众号" 关键时刻,第一时间送达! 从昨天到现在,朋友圈里便持续性地见到了许多"请给我一顶圣诞帽@微信官方" ...

  4. 教你用OpenCV人脸检测自动给头像戴圣诞帽(附代码)

    来源:老王和他的IT界朋友们 作者:流川疯 本文长度为3400字,建议阅读7分钟 跟着代码走,教你自动给头像带上圣诞帽. 原图: 效果: 原理其实很简单: 采用一张圣诞帽的png图像作为素材 利用pn ...

  5. 在线工具给头像添加圣诞帽html源码

    最近马上圣诞节也要来临,跟一波风,弄了一个关于在线制作圣诞帽的小程序,感兴趣的朋友可以去尝试一下哦~ <!DOCTYPE html> <html> <head>&l ...

  6. python自动抠头像图_Python实现AI自动抠图实例解析

    一.简介 抠图是用PS? 用魔棒和快速选择工具? 遇到复杂背景怎么办? 最近发现一个神奇的工具--Remove Image Background 它是基于Python.Ruby和深度学习技术开发,通过 ...

  7. 不用P图!用Python给头像加圣诞帽并制作成可执行软件!

    文 | 闲欢 来源:Python 技术「ID: pythonall」 随着圣诞节的到来,节日气氛也越来越浓厚.大街上随处可见挂满饰品的圣诞树,好多小伙伴的头上也多了一顶红色牛角的圣诞帽. 往年在这个时 ...

  8. python画圣诞帽_用Python给头像加上圣诞帽

    原标题:用Python给头像加上圣诞帽 随着圣诞的到来,大家纷纷@官微给自己的头像加上一顶圣诞帽.我们有必要写一个程序来做这件事情. 用到的工具 OpenCV dlib 流程 一.素材准备 首先我们需 ...

  9. 用Python给头像加上圣诞帽或圣诞老人小徽章

    随着圣诞的到来,想给给自己的头像加上一顶圣诞帽.如果不是头像,就加一个圣诞老人陪伴. 用Python给头像加上圣诞帽,看了下大概也都是来自2017年大神的文章: https://zhuanlan.zh ...

最新文章

  1. 产品需求管理经验分享
  2. 多巴胺如何驱使我们克服复杂情况、逆境、情绪, 让我们掌控周遭的环境的
  3. 知乎高赞:字节总监的开发手记!
  4. python数据库操作之pymysql模块和sqlalchemy模块(项目必备)
  5. WinXP登录时不用输入用户名和密码,自动登录系统
  6. java 省市区三级联动_AJAX省市区三级联动下拉菜单(java版)
  7. [css] style标签写在body前和body后的区别是什么?
  8. 简单的循环以及从接口获取数组对象的一个字段集合
  9. MySQL笔记(六)视图 view
  10. 外贸网站香港服务器,香港云服务器更适合小型外贸网站使用
  11. String.fromCharCode()函数
  12. ArcGIS10.2的详细安装过程和下载方法
  13. 超赞!设计师完全自学指南
  14. CSPS2019Day1T1(格雷码)题解
  15. 数据分析模型篇—麦肯锡矩阵(GE矩阵)
  16. Cesium for UE4 与 3DTiles
  17. 学习笔记(4):【数据分析实战训练营】 数据分析基础及方法论-row-column-len-lenb函数...
  18. 小满网络模型http1-http2 浏览器缓存
  19. XShell6(配置XFTP 文件传输) 安装+简单使用教程
  20. C#网络爬虫抓取小说

热门文章

  1. Java面试之Synchronized无法禁止指令重排却能保证有序性
  2. Java容器-面试题
  3. 002 ceph的deploy部署
  4. informix长事务的处理方式
  5. Oracle Golden Gate 系列十六 -- 配置 GG 安全 说明 与 示例
  6. Java基础面试题,java初级面试笔试题
  7. CentOS7安装Java,java高级面试笔试题
  8. 程序人生:初学者最常问的几个问题
  9. (转)淘淘商城系列——zookeeper单机版安装
  10. TML 打印预览问题,怎么设置有些内容不出现在打印预览页面上。怎么控制,有下代码 看得不是很懂 求解释...