1.準(zhǔn)備工作
(1).登陸 百度智能云-管理中心 創(chuàng)建 “文字識(shí)別”應(yīng)用,獲取 “API Key ”和 “Secret Key”:
通用參考 - 鑒權(quán)認(rèn)證機(jī)制 | 百度AI開放平臺(tái) (baidu.com)
(2).根據(jù) API Key 和 Secret Key 獲取 AccessToken
2.掃描圖片上傳
// 掃描
setScan() {
uni.chooseImage({
count: 1, //默認(rèn)9
sizeType: ['original', 'compressed'], //可以指定是原圖還是壓縮圖,默認(rèn)二者都有
sourceType: ['camera', 'album'], //前者喚起相機(jī),后者從相冊(cè)選擇
success: res => {
console.log('img', res);
this.uploadImg(res.tempFilePaths); //上傳圖片
}
});
},
// 圖片上傳
uploadImg(tempFilePaths) {
let that = this;
uni.showLoading({
title: '識(shí)別中'
});
//調(diào)用后端圖片上傳接口
uni.uploadFile({
url: that.api.baseUrl + '/file/upload',
// header:{},
filePath: tempFilePaths[0], // 要上傳文件資源的路徑
name: 'file', // 文件對(duì)應(yīng)的 key , 開發(fā)者在服務(wù)器端通過(guò)這個(gè) key 可以獲取到文件二進(jìn)制內(nèi)容
formData: {
user: 'test'
},
success(res) {
let data = JSON.parse(res.data);
console.log(data);
that.tui.toast('上傳成功');
//調(diào)用ocr識(shí)別行駛證方法
that.iOCR(data.data.url);
},
fail() {
uni.hideLoading();
that.tui.toast('上傳失敗,請(qǐng)重試');
},
complete() {
uni.hideLoading();
console.log('結(jié)束');
}
});
},
3.OCR識(shí)別
iOCR(url) {
// 生成assets token
uni.request({
//client_id:第一步獲取到的API Key;client_secret:第一步獲取的Secret Key
url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxx&client_secret=xxx`,
method: 'POST',
success: res => {
console.log('assets_token', res.data.access_token);
// 獲取到access_token之后,調(diào)用ocr接口
uni.request({
url: `https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=${res.data.access_token}`,
method: 'POST',
header: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
url: url //上傳之后的行駛證url
},
success: res => {
console.log(res);
if (res.data.words_result) {
//識(shí)別出的數(shù)據(jù)
} else {
this.tui.toast('未識(shí)別出有效數(shù)據(jù),請(qǐng)重新操作');
}
},
fail: res => {
this.tui.toast('網(wǎng)絡(luò)錯(cuò)誤,請(qǐng)重試');
}
});
}
});
},