前言:百度API可以在微信小程序中进行数字识别,而微信小程序通用印刷体识别需要请求后台,在后台调用微信接口获取要识别的结果。

一、基于百度AI接口的数字识别

开发前的准备:需要在百度AI开放平台创建相关应用实例,在开发中会用到里面的相关数据,具体创建流程可以参考官方文档的QuickStart

代码如下:

wxml

<camera
                 class="camera"
                 device-position="back"
                 flash="off"
                 binderror="error"></camera>
             <view class="button" catchtap="numberRecognition">识别</view>

js

数据模型

data: {
        src: "",
        token: "",
        base64: "",
        isShow: false,
        numberList: [],
    },

方法:

numberRecognition(){
        wx.showLoading({
          title: '识别中...',
        })
        this.takePhoto();
        this.uploadAndRecognition();
      },
      //拍照
      takePhoto() {
        var that = this;
        //创建拍照上下文对象
        const ctx = wx.createCameraContext()
        ctx.takePhoto({
          quality: 'high',
          //拍照成功
          success: (res) => {
            //console.log(res)
            wx.getFileSystemManager().readFile({
              filePath: res.tempImagePath,
              encoding: 'base64',
              success: res => {
                //console.log(res)
                this.setData({
                  base64: res.data
                })
              },
              //拍照失败
              fail: err => {
                console.log(err)
                this.showToast();
              }
            })
          },
          fail: err => {
            this.showToast();
          }
        })
      },
    
      //上传识别
      uploadAndRecognition() {
        //调用接口,获取token
        wx.request({
          url: 'https://aip.baidubce.com/oauth/2.0/token', //百度智能云相关的接口地址
          data: {
            grant_type: 'client_credentials',
            client_id: 'hsfGF3F....Q1OtR4nLccBC0',//用你创建的应用的API Key
            client_secret: '2tyN2QygjKwQ.....qt6afV9bXjqfvT5'//用你创建的应用的Secret Key
          },
          header: {
            'Content-Type': 'application/json' // 默认值
          },
          //获取成功之后
          success: res => {
            console.log(res)
            wx.request({
              url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/numbers?access_token=' + res.data.access_token,
              method: 'POST',
              data: {
                //所有图片均需要base64编码、去掉编码头后再进行urlencode
                image: decodeURI(this.data.base64),
              },
              header: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              success: res => {
                console.log(res.data)
                let length = res.data.words_result_num;
                console.log(length)
                if (length > 0){
                  for (let i = 0; i < length;i++){
                    let tempDataList = {
                      title:""+i+"个:",
                      number: res.data.words_result[i].words
                    } 
                    console.log(tempDataList)
                    let temp = "numberList["+ i +"]";
                    console.log(temp)
                    this.setData({
                      [temp]:tempDataList
                    })
                  }
                  this.showCover();
                  console.log(this.data.numberList)
                }else{
                  wx.showModal({
                    content: '未识别到数字',
                  })
                }
              },
              fail: err => {
                console.log(err)
                this.showToast();
              }
            })
          },
          fail:err=>{
            console.log(err)
            this.showToast();
          },
          complete:()=>{
            wx.hideLoading();
          }
        })
      },
      //隐藏遮罩
      hideCover() {
        this.setData({
          isShow: false
        })
      },
      //显示遮罩
      showCover() {
        this.setData({
          isShow: true
        })
      },
      //封装的wx.showToast
      showToast() {
        wx.showToast({
          title: "服务异常,请稍后重试",
          icon: 'none',
          duration: 3000
        })
      },

结果如下:

二、基于微信小程序接口的数字识别

1、获取access_token

public class demo4 {
    public static void main(String[] args) {
        //获取access_token填写client_credential
        String grant_type = "client_credential";
        //    第三方用户唯一凭证
        String appid = "wx13f1....30a8e192";
        //第三方用户唯一凭证密钥,即appsecret
        String secret = "3f3718064f.....a9887.....ddd4fdd";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret;
        HttpClient httpClient = new HttpClient();
        JSONObject json = httpClient.getJSON(url);
        System.out.println(json);
    }
}

使用postman请求

2、通用印刷体识别接口调用

public class demo5 {
    public static void main(String[] args) {
        String access_token = "72_OLBiphYTBNEmzEgBkDVyLmTXbf7Oab620_eaTgZbVK9rxIfTxeluRefGVYAsyEQgnwANF4_ExI2WwEHypqSkBaJWfhv5l6P7ZcoHLJWCGOBlQ1sO0Blj7AkljtMCKOeAIANVZ";
        String url = "https://api.weixin.qq.com/cv/ocr/comm?access_token="+access_token;
        String filePath = "D:\\project\\工程文档\\......追溯系统\\二维码和验证码图片\\内码\\ocr.png";
        RestTemplate rest = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();

        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        //MultipartFile的名称
        param.add("img", resource);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, httpHeaders);
        ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
        String result = responseEntity.getBody();
        System.out.println(result);

    }
}

postman请求:access_token在Params中输入,img在请求体的form-data中输入。

 

posted on 2023-11-01 09:16  周文豪  阅读(272)  评论(1编辑  收藏  举报