小程序调用百度云接口实现人脸识别

落日映苍穹つ 2023-02-11 10:22 101阅读 0赞

一 准备好百度云的开发者账号

  1. 登录
  2. 进入控制台
  3. 人工智能———图像识别
  4. 创建应用
  1. ![20200523095231984.png][]

获取接口需要的参数

20200523095311945.png

查看官网API文档

20200523095344489.png

二 页面布局

2020052309541118.png

20200530225839664.png

文件ai.wxml:

  1. <view class="c1">
  2. <view class="c1-1">
  3. </view>
  4. <button type="primary" size="mini" bindtap="chooseImage">选择图片</button>
  5. <view class="c1-2">
  6. <image src="{
  7. {img}}" mode="widthFix"></image>
  8. <text>颜值:{
  9. {face.beauty}}</text>
  10. <text>年龄:{
  11. {face.age}}</text>
  12. <text>性别:{
  13. {face.gender.type}}</text>
  14. <text>情绪:{
  15. {face.emotion.type}}</text>
  16. </view>
  17. </view>

编写样式文件ai.wxss

  1. .c1{
  2. padding: 50rpx;
  3. }
  4. .c1-1{
  5. height: 800rpx;
  6. margin-bottom: 20rpx;
  7. display: flex;
  8. justify-content: center;
  9. font-size: 30rpx;
  10. box-shadow: 0px 0px 10px gray;
  11. }
  12. .c1-2{
  13. }

页面布局如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2dpdGh1Yl8zOTUzMzQxNA_size_16_color_FFFFFF_t_70

ai.js

  1. //获取app.js对象
  2. var app = getApp();
  3. Page({
  4. data: {
  5. face: {},//检测结果
  6. img: '', //选择的图片
  7. showResult: false //检测是由有结果
  8. },
  9. onLoad: function (options) {
  10. //console.log('获取全局变量数据:' + app.globalData.access_token);
  11. },
  12. //选择图片事件
  13. chooseImage(){
  14. var that = this;
  15. wx.chooseImage({
  16. count: 1,
  17. sizeType: ['original', 'compressed'],
  18. sourceType: ['album', 'camera'],
  19. success (res) {
  20. const tempPath = res.tempFilePaths[0];//获取选择的图片的地址
  21. //准备好了access_token和图片后,就可以开始请求百度的人脸检测接口了https://aip.baidubce.com/rest/2.0/face/v3/detect
  22. //该接口需要的参数是access_token,图片的base64值
  23. //图片的base64值的处理
  24. var base64 = wx.getFileSystemManager().readFileSync(tempPath,'base64');
  25. //提示
  26. wx.showLoading({
  27. title: '人脸检测中...',
  28. mask: true
  29. });
  30. //开始请求百度的人脸检测接口
  31. wx.request({
  32. url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token='+app.globalData.access_token,
  33. data: {
  34. image: base64,
  35. image_type: 'BASE64',
  36. face_field: 'age,beauty,expression,face_shape,gender,glasses,race,emotion'
  37. face_field: 'name, kind'
  38. },
  39. method: 'POST',
  40. header: {'content-type': 'application/json'},
  41. //header: {'content-type': 'application/x-www-form-urlencoded'},
  42. success (res) {
  43. console.log(res);
  44. if(res.statusCode == 200 && res.data.error_code == 0){ //检测结果正确
  45. //将选择的图片回显到页面
  46. //that.setData({img: tempPath});
  47. that.setData();
  48. //植物识别要传入键值对
  49. //取出检测的结果进行页面显示
  50. var face = res.data.result.face_list[0];
  51. console.log(face);
  52. that.setData({face: face,showResult: true});
  53. //隐藏加载窗口
  54. wx.hideLoading();
  55. }else{
  56. wx.showToast({
  57. title: '检测失败'+res.data.error_msg,
  58. duration: 5000
  59. });
  60. }
  61. }
  62. })
  63. }
  64. })
  65. },
  66. /**
  67. * 用户点击右上角分享
  68. */
  69. onShareAppMessage: function () {
  70. }
  71. })

app.js

  1. //app.js
  2. App({
  3. onLaunch: function () {
  4. var access_token = wx.getStorageSync('access_token');
  5. var expire_in = wx.getStorageSync('expire_in');
  6. // var access_token = parse;
  7. var access_token_date = parseInt(wx.getStorageSync('access_token_date'));
  8. var now = new Date().getTime();
  9. if(!access_token){
  10. this.requestToken();
  11. } else if(now > access_token_date + expire_in){
  12. this.requestToken();
  13. }else{
  14. }
  15. // 展示本地存储能力
  16. var logs = wx.getStorageSync('logs') || []
  17. logs.unshift(Date.now())
  18. wx.setStorageSync('logs', logs)
  19. // 登录
  20. wx.login({
  21. success: res => {
  22. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  23. }
  24. })
  25. // 获取用户信息
  26. wx.getSetting({
  27. success: res => {
  28. if (res.authSetting['scope.userInfo']) {
  29. // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
  30. wx.getUserInfo({
  31. success: res => {
  32. // 可以将 res 发送给后台解码出 unionId
  33. this.globalData.userInfo = res.userInfo
  34. // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
  35. // 所以此处加入 callback 以防止这种情况
  36. if (this.userInfoReadyCallback) {
  37. this.userInfoReadyCallback(res)
  38. }
  39. }
  40. })
  41. }
  42. }
  43. })
  44. },
  45. globalData: {
  46. userInfo: null
  47. },
  48. requestToken() {
  49. var that = this;
  50. wx.request({
  51. url: 'https://aip.baidubce.com/oauth/2.0/token',
  52. data: {
  53. grant_type: 'client_credentials',
  54. // aaa那里填写自己的百度key值
  55. client_id: 'aaa',
  56. client_secret: 'aaa'
  57. },
  58. //header: {'content-type': 'application/json'},
  59. header: {'content-type': 'application/x-www-form-urlencoded'},
  60. success (res) {
  61. if(res.statusCode == 200){
  62. wx.setStorageSync("access_token", res.data.access_token);
  63. wx.setStorageSync("expires_in", res.data.expires_in);
  64. //wx.setStorageSync("access_token_date", res.data.access_token_date);
  65. wx.setStorageSync("access_token_date", new Date().getTime());
  66. that.globalData.access_token = res.data.access_token;
  67. }
  68. }
  69. })
  70. }
  71. })

识别结果如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2dpdGh1Yl8zOTUzMzQxNA_size_16_color_FFFFFF_t_70 1

发表评论

表情:
评论列表 (有 0 条评论,101人围观)

还没有评论,来说两句吧...

相关阅读