搜尋
首頁微信小程式小程式開發小程式呼叫百度雲端介面實現人臉辨識

小程式呼叫百度雲端介面實現人臉辨識

Dec 14, 2020 pm 05:32 PM
人臉辨識小程式

小程式開發教學欄位介紹不一樣的實作人臉辨識方法

小程式呼叫百度雲端介面實現人臉辨識

相關免費學習推薦:小程式開發教學

一  準備好百度雲端的開發者帳號

  1. 登入
  2. 進入主機
  3. 人工智慧------圖像辨識
  4. 建立應用程式      

           

取得介面所需的參數

查看官網API文件

二頁佈局

檔ai.wxml:

<view>
    <view>
       
    </view>
    <button>选择图片</button>

    <view>
      <image></image>
   
       <text>颜值:{{face.beauty}}</text>
       <text>年龄:{{face.age}}</text>
       <text>性别:{{face.gender.type}}</text>
       <text>情绪:{{face.emotion.type}}</text>
    </view>
</view>

寫樣式檔ai.wxss

.c1{
  padding: 50rpx;

}
.c1-1{
  height: 800rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: center;
  font-size: 30rpx;
  box-shadow: 0px 0px 10px gray;
}
.c1-2{

}

頁面佈局如下: 

js

//获取app.js对象
var app = getApp();

Page({
  data: {
	face: {},//检测结果
	img: '',  //选择的图片
	showResult: false //检测是由有结果
  },
  onLoad: function (options) {
	//console.log('获取全局变量数据:' + app.globalData.access_token);
  },
  //选择图片事件
  chooseImage(){
	  var that = this;
	  wx.chooseImage({
	    count: 1,
	    sizeType: ['original', 'compressed'],
	    sourceType: ['album', 'camera'],
	    success (res) {
	      const tempPath = res.tempFilePaths[0];//获取选择的图片的地址
		  //准备好了access_token和图片后,就可以开始请求百度的人脸检测接口了https://aip.baidubce.com/rest/2.0/face/v3/detect
		  //该接口需要的参数是access_token,图片的base64值
		  //图片的base64值的处理
		  var base64 = wx.getFileSystemManager().readFileSync(tempPath,'base64');
		  //提示
		  wx.showLoading({
			  title: '人脸检测中...',
			  mask: true
		  });
		  //开始请求百度的人脸检测接口
		  wx.request({
		    url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token='+app.globalData.access_token,
      
		    data: {
		    image: base64,
			  image_type: 'BASE64',
			 face_field: 'age,beauty,expression,face_shape,gender,glasses,race,emotion'
		    face_field: 'name, kind'
        },
			method: 'POST',
		    header: {'content-type': 'application/json'},
		    //header: {'content-type': 'application/x-www-form-urlencoded'},
        success (res) {
				console.log(res);
				if(res.statusCode == 200 && res.data.error_code == 0){ //检测结果正确
					//将选择的图片回显到页面
					//that.setData({img: tempPath});
          that.setData();
          //植物识别要传入键值对
					//取出检测的结果进行页面显示
					var face = res.data.result.face_list[0];
          console.log(face);
					that.setData({face: face,showResult: true});
					//隐藏加载窗口
					wx.hideLoading();
				}else{
					wx.showToast({
						title: '检测失败'+res.data.error_msg,
						duration: 5000
					});
				}
		    }
		  })
	    }
	  })
  },
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

app.js

//app.js
App({
  onLaunch: function () {
    var access_token = wx.getStorageSync('access_token');
    var expire_in = wx.getStorageSync('expire_in');
   // var access_token = parse;
    var access_token_date = parseInt(wx.getStorageSync('access_token_date'));
    var now = new Date().getTime();
    if(!access_token){
      this.requestToken();

    } else if(now > access_token_date + expire_in){
      this.requestToken();
    }else{

    }
  

    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
    
  },
  globalData: {
    userInfo: null
  },

  requestToken() {
    var that = this;
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token',
      data: {
        grant_type: 'client_credentials',
        // aaa那里填写自己的百度key值
        client_id: 'aaa',
        client_secret: 'aaa'

      },
      //header: {'content-type': 'application/json'},
      header: {'content-type': 'application/x-www-form-urlencoded'},
      success (res) {
        if(res.statusCode == 200){
          wx.setStorageSync("access_token", res.data.access_token);
          wx.setStorageSync("expires_in", res.data.expires_in);
          //wx.setStorageSync("access_token_date", res.data.access_token_date);
          wx.setStorageSync("access_token_date", new Date().getTime());
          that.globalData.access_token = res.data.access_token;
        }
      }
    })
  }
})

識別結果如下:

以上是小程式呼叫百度雲端介面實現人臉辨識的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:CSDN。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器