开发环境
- 微信小程序开发者工具 v1.02.1809260
- 调试基础库 2.0.4
实现功能
- 上传一张图片检测图片中的人脸展示人脸属性信息,如年龄、性别、表情、美丑打分等。
接口
- 接口用到的百度AI开放平台的人脸检测与属性分析
接口文档
实现步骤
- 本地选取一张图片
- 获取图片base64编码
- 获取百度开发api请求token
- 请求人脸检测接口
效果图
python实现
先用python把接口调试一下,测试调通
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import base64 import json import urllib import urllib.request from urllib import request
def get_token(host): header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko', "Content-Type": "application/json"} req = request.Request(url=host, headers=header_dict) res = request.urlopen(req) res = res.read() res_json = json.loads(res.decode('utf-8')) print(res_json) return res_json["access_token"]
''' 进行post请求 url:请求地址 values:请求体 ''' def get_info_post_json_data(url, value): header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko', "Content-Type": "application/json"} req = request.Request(url=url, data=value, headers=header_dict) res = request.urlopen(req) res = res.read() return (res.decode('utf-8')) ''' 调用百度API,进行人脸探测 imgPath: 图片地址 access_token: 开发者token ''' def getBaiduFaceTech(imgPath, access_token): request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect" f = open(imgPath, 'rb') img = base64.b64encode(f.read()) params = {"image": img, "image_type": "BASE64", "face_field": "age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,face_type"} params = urllib.parse.urlencode(params).encode(encoding='utf-8') request_url = request_url + "?access_token=" + access_token face_info = get_info_post_json_data(request_url, params) face_json = json.loads(face_info) if face_json["error_code"] != 0: elif face_json["result"]['face_num'] != 0: result = face_json['result']['face_list'][0] print("分值:" + str(result['beauty'])) print("年龄:" + str(result['age'])) print("性别:" + result['gender']['type'] + "\n可能性:" + str(result['gender']['probability'])) gender = result['gender']['type'] age = str(result['age']) beauty = str(result['beauty']) probability = str(result['gender']['probability']) face_dict = {"gender": gender, "age": age, "probability": probability, "beauty": beauty} return face_dict '''
if __name__ == '__main__': # client_id 为官网获取的AK, client_secret 为官网获取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】' token = get_token(host) # 调用百度人脸识别API face_dict = getBaiduFaceTech("face.jpg", token)
|
步骤1:本地选取一张图片
直接调用小程序wx.chooseImage(Object object)从本地相册选择图片或使用相机拍照
https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
1 2 3 4 5 6 7 8 9 10 11
| wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album', 'camera'], success: function(res) { var tempFilePaths = res.tempFilePaths; _this.setData({ img: tempFilePaths[0], }); })
|
步骤2:
早期在微信小程序中将图片base64化需要借助微信原生的 wx.canvasGetImageData 得到图片的像素信息,再通过开源库UPNG将像素信息编码,最后通过wx.arrayBufferToBase64转化为base64数据,看起来就挺麻烦的,我使用的调试基础库2.0.4,小程序有新接口获取图片base64编码,wx.getFileSystemManager() 注意版本库要在1.9.9以后的版本才支持
https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.getFileSystemManager.html
1 2 3 4 5 6 7 8 9 10
| wx.getFileSystemManager().readFile({ filePath: _this.data.img, encoding: 'base64', success: res => { _this.setData({ base64: res.data, })
|
步骤3:
百度的api要求向API服务地址使用POST发送请求,必须在URL中带上参数access_token,没得办法要用人家的服务就得按规矩来,直接使用wx.request()发起一个网络请求
https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
1 2 3 4 5 6 7 8 9 10 11 12
| wx.request({ url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】', header: { 'content-type': 'application/json' }, method: "POST", success(res) { _this.setData({ access_token: res.data.access_token, }) } })
|
步骤4:
带上access_token和图片base64编码请求人脸检测接口,还是一个wx.request()发起一个网络请求
https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| wx.request({ url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect' + '?access_token=' + _this.data.access_token, data: { image: _this.data.base64, image_type: 'BASE64', face_field: 'age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,face_type', }, header: { 'content-type': 'application/json' }, method: "POST", success(res) { wx.hideLoading(); var data = res.data; } })
|
完整参考代码 weixinxiaochengxu
参考链接
[微信小程序图片压缩及base64化上传]https://zhuanlan.zhihu.com/p/37440710
[小程序选择相册后转为base64编码的方法]https://www.jianshu.com/p/5d99db6b6901
[小程序图片转Base64,方法总结]https://blog.csdn.net/qq_36875339/article/details/81086205