使用C++调用百度OCR的示例源码

#include
#include
#include
#include
#include"ocr\ocr.h"
//OCR
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")

using std::string;
using std::vector;
using std::cout;

//百度OCR SDK
std::string app_id = "18726420";
std::string api_key = "Euq0KhNuyBPLiQG9XLrOYdp8";
std::string secret_key = "aMxYYpKlmyv6P3ZWOReHdpLPN94Rlryh";
aip::Ocr client(app_id, api_key, secret_key);

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;
}

string baiDuOcr(const string &imagePath)
{
	Json::Value result;
	std::string image;
	aip::get_file_content(imagePath.c_str(), &image);
	// 调用通用文字识别(高精度版本accurate_basic), 图片参数为本地图片
	result = client.accurate_basic(image, aip::null);
	Json::Value res = result["words_result"];
	string str;
	for (int i = 0; i < res.size(); i++)
		str.append(res[i]["words"].asString());
	//返回第一行文字
	return unicodeToAnsi(utf_8ToUnicode(str.c_str()));
}

void getFiles(string path, vector<string> &files, string format)
{
	intptr_t hFile;
	__finddata64_t fileInfo;

	path.append("\\*" + format);

	if ((hFile = _findfirst64(path.c_str(), &fileInfo)) != -1)
	{
		do
		{
			files.push_back(fileInfo.name);
		} while (_findnext64(hFile, &fileInfo) == 0);
		cout << "存在" << files.size() << "个指定类型文件!\n\n";
	}
	else
		cout << "文件查找失败!\n\n";
	_findclose(hFile);
}

int main()
{
	vector<string> v_files;
	string directory = "1";
	getFiles(directory, v_files, ".jpg");

	for (vector<string>::iterator it = v_files.begin(); it != v_files.end(); it++)
	{
		string str = directory + "\\" + *it;
		cout << baiDuOcr(str) << "\n\n";
		str.clear();
		Sleep(1000);//这里需要暂停一会,不然百度的数据还没传完过来而main程序已经结束
	}
	return 0;
}

注意:使用C++调用百度OCR,是需要libcurl、jsoncpp、openssl这三个库,同时也要百度提供的SDK。

你可能感兴趣的:(百度OCR的调用)