前端百度OCR文字识别

1,652 阅读1分钟

项目中需要用到百度文字识别,下面记录一下详细的使用步骤及方法。

1、获取API Key和Secret Key,以及通过这两个参数获取access_token

创建应用的方法参考:ai.baidu.com/ai-doc/REFE…

创建完应用后,就可以拿到API Key和Secret Key

微信截图_20220226164804.png 根据这两个参数我们可以通过调用获取token的接口拿到access_token

const getAccessToken = async () => { //获取access_token
    const params = new FormData()
    params.append('grant_type', 'client_credentials')
    params.append('client_id', '这里填你的API Key')
    params.append('client_secret', '这里填你的Secret Key')
    const res = await service({
        url: '/baiduApi/oauth/2.0/token',
        method: 'POST',
        data: params,
        headers: {
            'content-type': 'application/x-www-form-urlencoded'
        }
    })
    console.log('getAccessToken-res: ', res);
    return res.access_token
}

这里的service是封装好的request.js里的方法

2、通过access_token去来调用文字识别的接口(我这里识别的是增值税发票)

const ocrIndentify = async (ocrImg: string) => { //百度ocr识别
    const token = await getAccessToken()
    const params = new FormData()
    params.append('image', ocrImg)
    params.append('access_token', token)
    const res = await service({
        url: '/baiduApi/rest/2.0/ocr/v1/vat_invoice?access_token',
        method: 'POST',
        data: params,
        headers: {
            'content-type': 'application/x-www-form-urlencoded'
        }
    })
    console.log('ocrIndentify-res: ', res);
    if (res.error_code) {
        ElMessage({
            type: 'error',
            message: '不能识别该图片'
        })
        return null
    } else {
        return res
    }
}

这就完成了图片文字的识别

要注意的是,识别前要将图片转为base64格式,也是就是说ocrIndentify这个函数的参数要是base64格式的图片

本文为随笔,并非高深技术理论,如有不足之处还望大家多多指教!