imradv3 / src /WeChatOcrCpp /Wchtcr.cpp
fasdfsa's picture
返回结果加端口号, 批量运行 exe 脚本
a1d4680
#include "Wchtcr.h"
#include "ImageOcr.h"
#include <fstream>
#include <chrono>
#include <thread>
#include <iostream>
#include <filesystem>
#include <regex>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
Wchtcr::Wchtcr()
{
}
//std::future<std::string> Wchtcr::rec_async(const std::string& pth_img)
//{
// // 创建新的Promise
// _promise = std::promise<std::string>();
// std::future<std::string> future = _promise.get_future();
//
// // 在新线程中执行OCR
// std::thread([this, pth_img, &future]() {
// try
// {
// // 创建OCR实例并执行识别
// ImageOcr ocr;
// ocr.Run(pth_img, [this](const std::string& path, std::string& result) {
// _promise.set_value(result);
// });
//
// // 等待一小时超时
// auto status = future.wait_for(std::chrono::hours(1));
// if (status == std::future_status::timeout)
// {
// _promise.set_value("");
// }
// }
// catch (const std::exception& ex)
// {
// std::cerr << "Error: " << ex.what() << std::endl;
// _promise.set_value("");
// }
// }).detach();
//
// return future;
//}
std::string Wchtcr::rec(const std::string& pth_img)
{
// 检查文件是否存在
if (!std::filesystem::exists(pth_img))
{
return "文件不存在: " + pth_img;
}
try
{
std::string result;
// 创建一个原子变量来标记任务是否完成
std::atomic<bool> taskCompleted(false);
// 创建 ImageOcr 实例
//ImageOcr ocr;
// 设置回调函数并执行OCR
this->ocr.Run(pth_img, [&taskCompleted, &result](const std::string& imagePath, std::string& jsonstr) {
result = jsonstr;
// 标记任务完成
taskCompleted = true;
});
std::cout << "OCR任务已提交,等待结果..." << std::endl;
// 等待任务完成或超时
int timeoutSeconds = 600;
for (int i = 0; i < timeoutSeconds * 10 && !taskCompleted; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (taskCompleted) {
std::cout << "OCR任务已完成!" << std::endl;
}
else {
std::cout << "OCR任务超时!" << std::endl;
}
return result;
}
catch (const std::exception& ex)
{
return "错误: " + std::string(ex.what());
}
}