利用Python程序实现图片颜值打分

 

百度AI开放平台

调用主要有三步:

  • 获取access_token
  • 将图片处理成base64编码格式
  • post请求访问接口得到结果

1.获取access_token

官方给的python示例代码,不过这个是python2的代码,python3里已经没有了urllib2,而且很繁琐

给出博主自己编写的py3利用requests的demo: 

# -*- coding: utf-8 -*-

__author__ = 'fff_zrx'

import requests

#获取access_token

#client_id 为官网获取的AK, client_secret 为官网获取的SK

host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=your ak&client_secret=your sk'

header={'Content-Type': 'application/json; charset=UTF-8'}

response1=requests.post(url=host,headers=header)#<class 'requests.models.Response'>

json1 = response1.json()#<class 'dict'>

access_token=json1['access_token']

2.将图片处理成base64编码格式

流程大致是将图片读取为二进制格式,再利用二进制到base64格式的函数转换

参考博客

                                                                                        图片来自here

转换代码:

import base64

filepath='zrx.jpg'

f = open(r'%s' % filepath, 'rb')

pic = base64.b64encode(f.read())

f.close()

base64=str(pic,'utf-8')

print(base64)

 3.post请求访问接口得到结果

request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"

params = {"image":base64,"image_type":"BASE64","face_field":"faceshape,facetype,beauty,"}

header={'Content-Type': 'application/json'}

request_url = request_url + "?access_token=" + access_token

response1=requests.post(url=request_url,data=params,headers=header)#<class 'requests.models.Response'>

json1 = response1.json()#<class 'dict'>

print(json1)

print("颜值评分为")

print (json1["result"]["face_list"][0]['beauty'],'分/100分')

 完整代码: 

# -*- coding: utf-8 -*-

__author__ = 'fff_zrx'

import requests

import base64

#获取access_token

#client_id 为官网获取的AK, client_secret 为官网获取的SK

host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=your ak&client_secret=your sk'

header={'Content-Type': 'application/json; charset=UTF-8'}

response1=requests.post(url=host,headers=header)#<class 'requests.models.Response'>

json1 = response1.json()#<class 'dict'>

access_token=json1['access_token']

#转换图片格式

filepath='zrx.jpg'

f = open(r'%s' % filepath, 'rb')

pic = base64.b64encode(f.read())

f.close()

base64=str(pic,'utf-8')

print(base64)

#访问人脸检测api

request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"

params = {"image":base64,"image_type":"BASE64","face_field":"faceshape,facetype,beauty,"}

header={'Content-Type': 'application/json'}

request_url = request_url + "?access_token=" + access_token

response1=requests.post(url=request_url,data=params,headers=header)#<class 'requests.models.Response'>

json1 = response1.json()#<class 'dict'>

print(json1)

print("颜值评分为")

print (json1["result"]["face_list"][0]['beauty'],'分/100分')

 实例图


另外本人还开设了个人公众号:JiandaoStudio ,会在公众号内定期发布行业信息,以及各类免费代码、书籍、大师课程资源。

                                            

扫码关注本人微信公众号,有惊喜奥!公众号每天定时发送精致文章!回复关键词可获得海量各类编程开发学习资料!

例如:想获得Python入门至精通学习资料,请回复关键词Python即可。

猜你喜欢

转载自blog.csdn.net/weixin_41213648/article/details/92427306