auto.js調用百度ocr實現圖片上的文字識別

auto.waitFor(); //console.show();
var height = device.height; var width = device.width; var curr_time = new Date(); var now_D = curr_time.getDay(); log("\n設備寬:" + width + "\n" + "設備高:" + height + "\n" + "手機型號:" + device.model + "\n安卓版本:" + device.release); //設置腳本座標點擊所適合的屏幕寬高。
setScreenMetrics(width, height); //請求截圖權限
if (!requestScreenCapture()) { toast("請求截圖失敗"); exit(); } var imgScreen = captureScreen();//請求截取當前屏幕
var logOcr= Baidu_ocr(imgScreen); log(logOcr); var wordResult=logOcr.words_result; var count=0; wordResult.forEach(element => { count++; log(count+":"+element.words); }); //調用百度文字識別ocr獲得當前手機截屏文字
function Baidu_ocr(imgFile){ log("調用百度ocr開始識圖"); //var imag64 = images.toBase64(imgFile);//轉換截屏圖片
    var imag64 = images.toBase64(imgFile, "png", 100);//轉換截屏圖片
    //log(imag64.string());
    //該APIKey和Secret爲"這是誰的爽歪歪"全部
    var API_Key="xXLSyVarLbQZarIgPZLyAgMa"; var Secret_Key="bw1KWXr8TVuLmfwg4qsBhzkrqAnkffXQ"; //access_token獲取地址。
    var getTokenUrl="https://aip.baidubce.com/oauth/2.0/token"; var token_Res = http.post(getTokenUrl, { grant_type: "client_credentials", client_id: API_Key, client_secret: Secret_Key, }); var access_token=token_Res.body.json().access_token; //通用文字識別,50000次/天免費
    var ocrUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"; var ocr_Res = http.post(ocrUrl, { headers: { "Content - Type": "application/x-www-form-urlencoded" }, access_token: access_token, image: imag64, language_type:"CHN_ENG" }); var json = ocr_Res.body.json(); //log(json);
    return json; }

用百度智能雲提供的文字識別返回json格式內容,很是好用。json

還有另一種寫法,由飛雲腳本圈整理提供(www.feiyunjs.com)app

function Baidu_OCR(imgFile) { access_token = http.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=YIKKfQbdpYRRYtqqTPnZ5bCE&client_secret=hBxFiPhOCn6G9GH0sHoL0kTwfrCtndDj").body.json().access_token; url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic" + "?access_token=" + access_token; imag64 = images.toBase64(images.read(imgFile)); res = http.post(url, {headers: {'Content-Type': 'application/x-www-form-urlencoded'},image: imag64,image_type: "BASE64",language_type:"JAP"}); str = JSON.parse(res.body.string()).words_result.map(val => val.words).join('\n'); return str; } imgFile = "/storage/emulated/0/tencent/Tim_Images/-2c197ea407301935.jpg"; log(Baidu_OCR(imgFile));

這個代碼看起來很是簡潔,可是有些不容易看懂,仍是推薦我寫的第一種post

相關文章
相關標籤/搜索