使用情景
安卓手机, 不联网, 使用百度的paddle飞浆ocr, 识别文字
效果展示
原理
- paddle安卓版添加一个服务与autojs通信
- autojs调用服务识别图片上的文字
代码讲解
- 创建adapter
_connection = new JavaAdapter(ServiceConnection, {
onServiceConnected: function (name, service) {
_service = new Messenger(service);
_messenger = new Messenger(
new JavaAdapter(Handler, {
handleMessage: function (msg) {
if (msg.what == MSG_RESULT) {
let result = msg.getData().getString("result");
let jsonObj = JSON.parse(result);
if (jsonObj && jsonObj.length > 0 && jsonObj[0].Text) {
showData(jsonObj, imgPath, ocrType);
events.broadcast.emit("识别完成", imgPath);
} else {
throw new Error("识别错误");
}
}
},
})
);
},
});
- 绑定服务
let thread = threads.start(function () {
let intent = new Intent();
intent.setComponent(new ComponentName("com.paddle.ocr", "com.paddle.ocr.MsgService"));
context.bindService(intent, _connection, 1);
});
- 定义与服务通信的函数
function ocr(imgPath) {
if (_service == null || _messenger == null) {
throw new Error("未绑定服务或绑定失败, 需要安装paddleocr server并开启自启动权限!");
}
console.log("本次识别 imgPath = " + imgPath);
let src = images.read(imgPath);
let img = src.getBitmap();
recycleObjList.push(src, img);
if (img == null) {
alert("读取img失败!");
return;
}
let message = Message.obtain(null, MSG_OCR);
let bundle = new Bundle();
bundle.putParcelable("img", img);
message.setData(bundle);
message.replyTo = _messenger;
_service.send(message);
}
- 启动通信函数
setTimeout(function () {
ocr(imgPath);
}, 1000);
- 收到数据后, 使用showData函数, 用canvas在图片上画出识别结果, 然后保存到手机
canvas.drawRect(rect[0], rect[1], rect[2], rect[3], rectanglePaint);
canvas.drawText(
data.Text,
rect[0] + parseInt((rect[2] - rect[0]) / 2),
rect[3] + Math.abs(fontMetrics.top),
textPaint
);
images.save(image, newFilepath);
代码仓库:
https://gitee.com/yashujs/autojs-ocr-paddle
代码运行必要的插件下载
公众号回复 [ paddle ]
微信公众号 AutoJsPro教程
QQ群
747748653