美文网首页
图像识别功能在小程序中的使用

图像识别功能在小程序中的使用

作者: yunshengz | 来源:发表于2019-10-14 15:35 被阅读0次

    需求简介:

    在小程序中通过拍照或者选取手机图库中的图片来识别图片中的物体,并给出图片的识别相似度百分比

    使用技术介绍

    首先小程序用的并不是原生的,而是uni-app,对于实现这个功能没什么影响;图片识别的api用的是百度api;根据需求用的是其中的通用物体和场景识别高级版这个api;其实一开始考虑的是同腾讯的相关api,但是经过测试发现腾讯的api会报参数错误,有时候会报超时,反正是没有一次成功的,最后选择了百度ai的相关api;

    实现步骤

    1.注册网站相关账号,拿到API_KeySecret_Key

    2.获取token
    想授权地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐post),并在url中带上相关参数;
    -grant_type: 必须参数,固定为client_credentials;
    -client_id: 必须参数,应用的API_Key;
    _client_secret: 必须参数,应用的Secret_Key;

    const url = 'https://aip.baidubce.com/oauth/2.0/token'+
              '?grant_type=client_credentials'+
             '&client_id=你的apikey&client_secret=你的secret_key';
    uni.request({
        url,
        method: 'POST',
        success: res => {
            const {access_token, expires_in} = res.data;  
                /*
                access_token: 要获取的Access Token;
                expires_in: Access Token的有效期(秒为单位,一般为1个月);
                */
            },
            fail: () => {}
    });
    

    3.token的保存
    在获取的token之后我们可以用uni.setStorage方法(原生的方法不太一样,不过原来都是一样的)把获取到的token和有效时间加上当前时间的值存储到本地,这样不用每次进入小程序就不用反复的请求token;
    具体怎么做:

             onReady() {
                const that = this;
                // 获取相关storage
                uni.getStorage({
                    key: 'endTime',
                    success(res) {
                        // 获取成功,证明本地已存有相关token
                        const newT = new Date().getTime();
                        // 用当前时间和存储的时间判断,token是否已过期
                        if (newT > parseInt(res.data)) {
                            // token过期,重新获取token
                            that.getToken();
                        } else {
                            // 获取本地缓存的token
                            that.getBdToken();
                        }
                    },
                    fail() {
                        // 获取失败,开始获取token
                        that.getToken();
                    }
                });
            }
    

    4.设置图片来源选择
    用uni.showActionSheet()来配置图片来源的选择

                  uni.showActionSheet({
                        itemList: [
                            '拍照',
                            '从手机相册选择'
                        ],
                        itemColor: '#262626',
                        success(res) {
                            
                            const type = res.tapIndex === 0 ? ['camera'] : ['album']; 
                            uni.chooseImage({
                                count: 1,
                                sourceType: type,
                                success(res) {
                                    
                                    const path = res.tempFilePaths[0];
                                    that.imgPath = path; //本地图片文件路径
                                    /*
                                    other code
                                    */
                                    
                                },
                                fail(res) {
                                    console.log(res);
                                }
                            });
                            
                        },
                        fail(res) {
                            console.log(res.errMsg);
                        }
                    });
    

    5.根据图片识别接口需要,图片转base64

                    //读取图片的base64文件内容
                    const that = this;
                    wx.getFileSystemManager().readFile({
                        filePath: that.imgPath, //选择图片返回的相对路径
                        encoding: 'base64', //编码格式
                        success(res) {
                            //图片需要base64编码、去掉编码头后再进行urlencode
                            that.encodeImg = encodeURI(`${res.data}`);
                            
                        }  
                    })
    

    6.请求图像识别api
    注意:token要放到URL中,请求方式为post;header中Content-Type设置为application/x-www-form-urlencoded

    getImgInfo() {
                    const that = this;
                    uni.request({
                        url: `https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=${that.token}`,
                        method: 'POST',
                        data: {
                            'image': that.encodeImg
                        },
                        header: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            
                        },
                        success: res => {
                            console.log('res', res);
                            
                            if ('result' in res.data) {
                                // result为标签结果数组
                                const {result} = res.data;
                                
                                that.list = result;
                                
                                uni.hideLoading();
                            } else {
                                const {error_msg} = res.data;
                                uni.hideLoading();
                                
                                that.list = [];
                                uni.showToast({
                                    title: error_msg,
                                    icon: 'none',
                                    duration: 2400
                                });
                            }
                        },
                        fail: () => {
                            uni.hideLoading();
                            uni.showToast({
                                title: '搜索识别失败,请重试!',
                                icon: 'none'
                            });
                        }
                    });
                }
    
    以上就是图片识别的基本过程,从上面的过程可以看出功能并不复杂;下面贴一下实际的效果
    image.png

    相关文章

      网友评论

          本文标题:图像识别功能在小程序中的使用

          本文链接:https://www.haomeiwen.com/subject/karrmctx.html