一、需求
百度AI OCR:https://cloud.baidu.com/doc/OCR/s/2kibizy58
1.在官方网站下载C++ SDK压缩包。
2.将下载的aip-cpp-sdk-version.zip
解压, 其中文件为包含实现代码的头文件。
3.安装依赖库libcurl(需要支持https,) openssl, jsoncpp(>1.6.2版本,0.x版本将不被支持)。
二、案例
openssl编译很麻烦的,可以直接在网上找编译好的。下面提供我编译好的案例。
c++调用百度AI OCR案例:
https://download.youkuaiyun.com/download/greless/16635738
注意:秘钥自己改成你自己的秘钥
// 设置APPID/AK/SK
std::string app_id = "你的 App ID";
std::string api_key = "你的 Api key";
std::string secret_key = "你的 Secret Key";
// BaiduAI_OCR.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
using namespace std;
#include "ocr.h"
#pragma comment(lib,"jsoncpp.lib")
#pragma comment(lib,"libcurl.lib")
#pragma comment(lib,"libeay32.lib")
wchar_t *utf_8ToUnicode(const char *u8s)
{
int wcsLen = MultiByteToWideChar(CP_UTF8, NULL, u8s, strlen(u8s), NULL, NULL);
wchar_t *wcString = new wchar_t[wcsLen + 1];
MultiByteToWideChar(CP_UTF8, NULL, u8s, strlen(u8s), wcString, wcsLen);
wcString[wcsLen] = '\0';
return wcString;
}
char *unicodeToAnsi(wchar_t *wcString)
{
int len = WideCharToMultiByte(CP_ACP, NULL, wcString, -1, NULL, NULL, NULL, NULL);
char *str = new char[len];
WideCharToMultiByte(CP_ACP, NULL, wcString, -1, str, len, NULL, NULL);
return str;
}
int main()
{
// 设置APPID/AK/SK
std::string app_id = "你的 App ID";
std::string api_key = "你的 Api key";
std::string secret_key = "你的 Secret Key";
aip::Ocr client(app_id, api_key, secret_key);
Json::Value result;
std::string image;
aip::get_file_content("ocr.jpg", &image);
// 调用通用文字识别, 图片参数为本地图片
result = client.general_basic(image, aip::null);
std::cout << result << std::endl;
Json::Value res = result["words_result"];
std::string str;
for (int i = 0; i < res.size(); i++)
str.append(res[i]["words"].asString());
//返回文字
std::cout << "返回识别文字:"<<unicodeToAnsi(utf_8ToUnicode(str.c_str())) << std::endl;
getchar();
}