autojs-ocr-paddle

使用情景

安卓手机, 不联网, 使用百度的paddle飞浆ocr, 识别文字

效果展示

在这里插入图片描述
在这里插入图片描述

原理

  1. paddle安卓版添加一个服务与autojs通信
  2. autojs调用服务识别图片上的文字

代码讲解

  1. 创建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("识别错误");
            }
          }
        },
      })
    );
  },
});

  1. 绑定服务
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);
});
  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);
}
  1. 启动通信函数
setTimeout(function () {
    
    
  ocr(imgPath);
}, 1000);
  1. 收到数据后, 使用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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/snailuncle2/article/details/113942732
OCR
今日推荐