nodejs实现名片识别

一、说明:

百度云提供了名片识别的api,每天可以免费调用500次:https://cloud.baidu.com/product/ocr/cards
因此,需要先上百度云注册一个开发者应用

二、名片识别代码

baiduocr.js

const request = require('request-promise');
// 上百度云注册开发者应用
const BDOCRCONF = {
  grant_type: 'xxxxxxxxxxx',
  client_id: 'xxxxxxxxxxx',
  client_secret: 'xxxxxxxxxxx',
}

/**
 * 从百度提供的api获取access_token
 */
async function getBdOCRToken() {
  let client_id = BDOCRCONF.client_id;
  let client_secret = BDOCRCONF.client_secret;
  let url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=${BDOCRCONF.grant_type}&client_id=${client_id}&client_secret=${client_secret}`;
  var options = {
    method: 'get',
    url: url
  };
  let result = await request(options);
  return JSON.parse(result)['access_token'];
}
/**
 * 名片识别
 */
async function scanCard(imgData, access_token) {
  let url = `https://aip.baidubce.com/rest/2.0/ocr/v1/business_card?access_token=${access_token}`;
  var options = {
    method: 'POST',
    uri: url,
    headers: {
      'content-type': 'application/x-www-form-urlencoded;',
    },
    form: {
      image: imgData
    }
  };
  let resultStr = await request(options);
  return resultStr;
}

exports.getBdOCRToken = getBdOCRToken;
exports.scanCard = scanCard;

三、使用方法

const baiduocr = require('./baiduocr');
const fs = require('fs');

async function getImgData() {
  const imgContent = fs.readFileSync('./1.jpg');
  const imgContentBase64 = Buffer.from(imgContent, 'binary').toString('base64');
  const imgData = encodeURI(imgContentBase64);
  return imgData;
}

async function startScanCard() {
  const imgData = await getImgData();
  const baiduocr_access_token = await baiduocr.getBdOCRToken();
  const resultStr = await baiduocr.scanCard(imgData, baiduocr_access_token);
  console.log(resultStr);
}

startScanCard();

你可能感兴趣的:(nodejs实现名片识别)