uni |
您所在的位置:网站首页 › 华为手机智能识别文字怎么用 › uni |
本文将会介绍如何使用百度AI开放平台中的文字识别服务来识别图片中的文字。百度AI开放平台的访问网址为:百度AI开放平台,为了能够使用该平台提供的AI服务,你需要事先注册一个百度账号。 首先先注册一个百度账号,申请 通用文字识别API,前面这些基础的东西我就不讲了,不懂的可以参考文章 创建百度AI文字识别应用在百度AI开放平台中,登录自己的百度账号,点击 “文字识别” 服务中的 “通用场景文字识别” ,选择 “创建应用”,填好应用名称,选择应用类型,填好应用描述,这样就创建好了 “通用场景文字识别” 服务,如下图: 在应用列表中,能够看到自己刚刚创建好的文字识别服务了,记住,这个应用中的 AppID, API Key, Secret Key 很重要,是你这个应用的唯一识别。 接口描述点击下面链接进行了解 通用文字识别接口描述 格式如下: uni.request({ url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=【你的access_token值】', data:{ image:【图片的base64编码】, language_type:'ENG', //识别语言类型,默认中英文结合 detect_direction:true ,//检测图像朝向 }, method:'POST', header: { 'Content-Type': 'application/x-www-form-urlencoded' }, success :(res)=> { console.log(res.data) } }) } });其中你的access_token值需要用你的 API Key 和 Secret Key来获取,获取方法点击链接 access_token获取方法 但是看了API的调用方法中写了必须要base64编码,详情见图这个方法很好,代码页式最易懂的 首先选取本地图片的临时路径: x.chooseImage({ success:res=>{ this.urlTobase64(res.tempFilePaths[0]) } })接下来,把临时路径作为一个请求的url,把数据返回格式设置成arraybuffer,上代码。 urlTobase64(url){ wx.request({ url:url, // 必须是https链接 responseType: 'arraybuffer', //最关键的参数,设置返回的数据格式为arraybuffer success:res=>{ //把arraybuffer转成base64 let base64 = wx.arrayBufferToBase64(res.data); //不加上这串字符,在页面无法显示的哦 base64 = 'data:image/jpeg;base64,' + base64 //打印出base64字符串,可复制到网页校验一下是否是你选择的原图片呢 console.log(base64) } }) }这种方法看起来天衣无缝,其实测试一下你就知道,在微信开发平台上可以使用,但是在手机端就数据就失效了! 这是因为微信小程序开发工具要求 request 必须是 https 链接。在电脑端选取的图片满足要求,但是手机端上传的图片临时地址却不满足要求,所以就转码失败导致识别错误。 第二种方法 (成功版)以前微信开发者工具没有选取文件的函数,更新过后增加了 etFileSystemManager() 的 readFile 函数,可以通过对文件的编码操作进行本地转码。 x.chooseImage({ success: res => { wx.getFileSystemManager().readFile({ filePath: res.tempFilePaths[0], //选择图片返回的相对路径 encoding: 'base64', //编码格式 success: res => { //成功的回调 console.log(res.data) } }) } })注意: 前面不需要加 ’ data:image/jpeg;base64 ’ res.data 就是转码成功的base64编码 . . . 下面贴一个完整的 uni-app 代码 :只需要修改 百度 API 的 access_token 即可 选取图片识别 {{item.words}} export default { data(){ return{ src:'', content:[] } }, methods:{ uploadImage(){ // 选取照片,进行OCR识别 uni.chooseImage({ count:1,//默认9 sizeType:['original', 'compressed'],//可以指定是原图还是压缩图,默认二者都有 success: (res)=> { uni.showLoading({ title: '正在识别中...' }); this.src = res.tempFilePaths[0]; //后面还能用到 src 暂且留着 // 下面进行转码 wx.getFileSystemManager().readFile({ filePath:res.tempFilePaths[0], //选择图片返回的相对路径 encoding:'base64',//编码格式 success:(res)=>{ //成功回调页面 uni.request({ url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=【你的access_token】', data:{ image:res.data, language_type:'ENG', //识别语言类型,默认中英文结合 detect_direction:true ,//检测图像朝向 }, method:'POST', header: { 'Content-Type': 'application/x-www-form-urlencoded' }, success :(res)=> { this.content = res.data.words_result uni.hideLoading(); //把正在加载中隐藏 console.log(res.data) } }) } }); } }) } } } .vvv{ width: 99%; border: 2px dashed #eeeeee; height: 700upx; margin: 30upx 0 0 0; } 效果图如下: |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |