Commit 2475c919 authored by liucong's avatar liucong
Browse files

重新Cpp代码格式化

parent 466992ff
This diff is collapsed.
...@@ -20,20 +20,20 @@ typedef struct _DBParameter ...@@ -20,20 +20,20 @@ typedef struct _DBParameter
int LimitSideLen; int LimitSideLen;
std::string ScoreMode; std::string ScoreMode;
}DBParameter; } DBParameter;
class DB class DB
{ {
public: public:
DB(); DB();
~DB(); ~DB();
ErrorCode Initialize(InitializationParameterOfDB InitializationParameterOfDB); ErrorCode Initialize(InitializationParameterOfDB InitializationParameterOfDB);
ErrorCode Infer(const cv::Mat &img, std::vector<cv::Mat> &imgList); ErrorCode Infer(const cv::Mat& img, std::vector<cv::Mat>& imgList);
private: private:
cv::FileStorage configurationFile; cv::FileStorage configurationFile;
migraphx::program net; migraphx::program net;
...@@ -41,38 +41,39 @@ private: ...@@ -41,38 +41,39 @@ private:
std::string inputName; std::string inputName;
migraphx::shape inputShape; migraphx::shape inputShape;
DBParameter dbParameter; DBParameter dbParameter;
}; };
class DBPostProcessor { class DBPostProcessor
public: {
void GetContourArea(const std::vector<std::vector<float>> &box, public:
float unclip_ratio, float &distance); void
GetContourArea(const std::vector<std::vector<float>>& box, float unclip_ratio, float& distance);
cv::RotatedRect UnClip(std::vector<std::vector<float>> box, cv::RotatedRect UnClip(std::vector<std::vector<float>> box, const float& unclip_ratio);
const float &unclip_ratio);
float **Mat2Vec(cv::Mat mat); float** Mat2Vec(cv::Mat mat);
std::vector<std::vector<int>> std::vector<std::vector<int>> OrderPointsClockwise(std::vector<std::vector<int>> pts);
OrderPointsClockwise(std::vector<std::vector<int>> pts);
std::vector<std::vector<float>> GetMiniBoxes(cv::RotatedRect box, std::vector<std::vector<float>> GetMiniBoxes(cv::RotatedRect box, float& ssid);
float &ssid);
float BoxScoreFast(std::vector<std::vector<float>> box_array, cv::Mat pred); float BoxScoreFast(std::vector<std::vector<float>> box_array, cv::Mat pred);
float PolygonScoreAcc(std::vector<cv::Point> contour, cv::Mat pred); float PolygonScoreAcc(std::vector<cv::Point> contour, cv::Mat pred);
std::vector<std::vector<std::vector<int>>> std::vector<std::vector<std::vector<int>>>
BoxesFromBitmap(const cv::Mat pred, const cv::Mat bitmap, BoxesFromBitmap(const cv::Mat pred,
const float &box_thresh, const float &det_db_unclip_ratio, const cv::Mat bitmap,
const std::string &det_db_score_mode); const float& box_thresh,
const float& det_db_unclip_ratio,
const std::string& det_db_score_mode);
std::vector<std::vector<std::vector<int>>> std::vector<std::vector<std::vector<int>>>
FilterTagDetRes(std::vector<std::vector<std::vector<int>>> boxes, FilterTagDetRes(std::vector<std::vector<std::vector<int>>> boxes,
float ratio_h, float ratio_w, cv::Mat srcimg); float ratio_h,
float ratio_w,
cv::Mat srcimg);
private: private:
static bool XsortInt(std::vector<int> a, std::vector<int> b); static bool XsortInt(std::vector<int> a, std::vector<int> b);
static bool XsortFp32(std::vector<float> a, std::vector<float> b); static bool XsortFp32(std::vector<float> a, std::vector<float> b);
...@@ -83,23 +84,26 @@ private: ...@@ -83,23 +84,26 @@ private:
inline int _min(int a, int b) { return a >= b ? b : a; } inline int _min(int a, int b) { return a >= b ? b : a; }
template <class T> inline T clamp(T x, T min, T max) { template <class T>
if (x > max) inline T clamp(T x, T min, T max)
{
if(x > max)
return max; return max;
if (x < min) if(x < min)
return min; return min;
return x; return x;
} }
inline float clampf(float x, float min, float max) { inline float clampf(float x, float min, float max)
if (x > max) {
if(x > max)
return max; return max;
if (x < min) if(x < min)
return min; return min;
return x; return x;
} }
}; };
} } // namespace migraphxSamples
#endif #endif
\ No newline at end of file
...@@ -6,20 +6,14 @@ ...@@ -6,20 +6,14 @@
namespace migraphxSamples namespace migraphxSamples
{ {
SVTR::SVTR() SVTR::SVTR() {}
{
}
SVTR::~SVTR() SVTR::~SVTR() { configurationFile.release(); }
{
configurationFile.release();
}
ErrorCode SVTR::Initialize(InitializationParameterOfSVTR InitializationParameterOfSVTR) ErrorCode SVTR::Initialize(InitializationParameterOfSVTR InitializationParameterOfSVTR)
{ {
// 读取配置文件 // 读取配置文件
std::string configFilePath=InitializationParameterOfSVTR.configFilePath; std::string configFilePath = InitializationParameterOfSVTR.configFilePath;
if(!Exists(configFilePath)) if(!Exists(configFilePath))
{ {
LOG_ERROR(stdout, "no configuration file!\n"); LOG_ERROR(stdout, "no configuration file!\n");
...@@ -40,45 +34,45 @@ ErrorCode SVTR::Initialize(InitializationParameterOfSVTR InitializationParameter ...@@ -40,45 +34,45 @@ ErrorCode SVTR::Initialize(InitializationParameterOfSVTR InitializationParameter
// 加载模型 // 加载模型
if(!Exists(modelPath)) if(!Exists(modelPath))
{ {
LOG_ERROR(stdout,"%s not exist!\n",modelPath.c_str()); LOG_ERROR(stdout, "%s not exist!\n", modelPath.c_str());
return MODEL_NOT_EXIST; return MODEL_NOT_EXIST;
} }
migraphx::onnx_options onnx_options; migraphx::onnx_options onnx_options;
onnx_options.map_input_dims["x"]={1,3,48,320}; // 设置最大shape onnx_options.map_input_dims["x"] = {1, 3, 48, 320}; // 设置最大shape
net = migraphx::parse_onnx(modelPath, onnx_options); net = migraphx::parse_onnx(modelPath, onnx_options);
LOG_INFO(stdout,"succeed to load model: %s\n",GetFileName(modelPath).c_str()); LOG_INFO(stdout, "succeed to load model: %s\n", GetFileName(modelPath).c_str());
// 获取模型输入/输出节点信息 // 获取模型输入/输出节点信息
std::unordered_map<std::string, migraphx::shape> inputs=net.get_inputs(); std::unordered_map<std::string, migraphx::shape> inputs = net.get_inputs();
std::unordered_map<std::string, migraphx::shape> outputs=net.get_outputs(); std::unordered_map<std::string, migraphx::shape> outputs = net.get_outputs();
inputName=inputs.begin()->first; inputName = inputs.begin()->first;
inputShape=inputs.begin()->second; inputShape = inputs.begin()->second;
int N=inputShape.lens()[0]; int N = inputShape.lens()[0];
int C=inputShape.lens()[1]; int C = inputShape.lens()[1];
int H=inputShape.lens()[2]; int H = inputShape.lens()[2];
int W=inputShape.lens()[3]; int W = inputShape.lens()[3];
inputSize=cv::Size(W,H); inputSize = cv::Size(W, H);
// 设置模型为GPU模式 // 设置模型为GPU模式
migraphx::target gpuTarget = migraphx::gpu::target{}; migraphx::target gpuTarget = migraphx::gpu::target{};
// 编译模型 // 编译模型
migraphx::compile_options options; migraphx::compile_options options;
options.device_id=0; // 设置GPU设备,默认为0号设备 options.device_id = 0; // 设置GPU设备,默认为0号设备
options.offload_copy=true; options.offload_copy = true;
net.compile(gpuTarget,options); net.compile(gpuTarget, options);
LOG_INFO(stdout,"succeed to compile model: %s\n",GetFileName(modelPath).c_str()); LOG_INFO(stdout, "succeed to compile model: %s\n", GetFileName(modelPath).c_str());
// warm up // warm up
std::unordered_map<std::string, migraphx::argument> inputData; std::unordered_map<std::string, migraphx::argument> inputData;
inputData[inputName]=migraphx::argument{inputShape}; inputData[inputName] = migraphx::argument{inputShape};
net.eval(inputData); net.eval(inputData);
std::ifstream in(dictPath); std::ifstream in(dictPath);
std::string line; std::string line;
if (in) if(in)
{ {
while (getline(in, line)) while(getline(in, line))
{ {
charactorDict.push_back(line); charactorDict.push_back(line);
} }
...@@ -92,15 +86,16 @@ ErrorCode SVTR::Initialize(InitializationParameterOfSVTR InitializationParameter ...@@ -92,15 +86,16 @@ ErrorCode SVTR::Initialize(InitializationParameterOfSVTR InitializationParameter
} }
// log // log
LOG_INFO(stdout,"InputMaxSize:%dx%d\n",inputSize.width,inputSize.height); LOG_INFO(stdout, "InputMaxSize:%dx%d\n", inputSize.width, inputSize.height);
LOG_INFO(stdout,"InputName:%s\n",inputName.c_str()); LOG_INFO(stdout, "InputName:%s\n", inputName.c_str());
return SUCCESS; return SUCCESS;
} }
ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdScore, float &maxWHRatio) ErrorCode
SVTR::Infer(cv::Mat& img, std::string& resultsChar, float& resultsdScore, float& maxWHRatio)
{ {
if(img.empty()||img.type()!=CV_8UC3) if(img.empty() || img.type() != CV_8UC3)
{ {
LOG_ERROR(stdout, "image error!\n"); LOG_ERROR(stdout, "image error!\n");
return IMAGE_ERROR; return IMAGE_ERROR;
...@@ -115,7 +110,7 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco ...@@ -115,7 +110,7 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco
int resizeW; int resizeW;
int imgW = int((48 * maxWHRatio)); int imgW = int((48 * maxWHRatio));
ratio = float(srcImage.cols) / float(srcImage.rows); ratio = float(srcImage.cols) / float(srcImage.rows);
if (ceil(imgH * ratio) > imgW) if(ceil(imgH * ratio) > imgW)
{ {
resizeW = imgW; resizeW = imgW;
} }
...@@ -124,27 +119,33 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco ...@@ -124,27 +119,33 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco
resizeW = int(ceil(imgH * ratio)); resizeW = int(ceil(imgH * ratio));
} }
cv::resize(srcImage, resizeImg, cv::Size(resizeW, imgH)); cv::resize(srcImage, resizeImg, cv::Size(resizeW, imgH));
cv::copyMakeBorder(resizeImg, resizeImg, 0, 0, 0, cv::copyMakeBorder(resizeImg,
int(imgW - resizeImg.cols), cv::BORDER_CONSTANT, resizeImg,
0,
0,
0,
int(imgW - resizeImg.cols),
cv::BORDER_CONSTANT,
{127, 127, 127}); {127, 127, 127});
resizeImg.convertTo(resizeImg, CV_32FC3, 1.0/255.0); resizeImg.convertTo(resizeImg, CV_32FC3, 1.0 / 255.0);
std::vector<cv::Mat> bgrChannels(3); std::vector<cv::Mat> bgrChannels(3);
cv::split(resizeImg, bgrChannels); cv::split(resizeImg, bgrChannels);
std::vector<float> mean = {0.485f, 0.456f, 0.406f}; std::vector<float> mean = {0.485f, 0.456f, 0.406f};
std::vector<float> scale = {1 / 0.229f, 1 / 0.224f, 1 / 0.225f}; std::vector<float> scale = {1 / 0.229f, 1 / 0.224f, 1 / 0.225f};
for (auto i = 0; i < bgrChannels.size(); i++) for(auto i = 0; i < bgrChannels.size(); i++)
{ {
bgrChannels[i].convertTo(bgrChannels[i], CV_32FC1, 1.0 * scale[i], bgrChannels[i].convertTo(
(0.0 - mean[i]) * scale[i]); bgrChannels[i], CV_32FC1, 1.0 * scale[i], (0.0 - mean[i]) * scale[i]);
} }
cv::merge(bgrChannels, resizeImg); cv::merge(bgrChannels, resizeImg);
cv::Mat inputBlob = cv::dnn::blobFromImage(resizeImg); cv::Mat inputBlob = cv::dnn::blobFromImage(resizeImg);
std::vector<std::size_t> inputShapeOfInfer={1,3,48,resizeW}; std::vector<std::size_t> inputShapeOfInfer = {1, 3, 48, resizeW};
// 创建输入数据 // 创建输入数据
std::unordered_map<std::string, migraphx::argument> inputData; std::unordered_map<std::string, migraphx::argument> inputData;
inputData[inputName]= migraphx::argument{migraphx::shape(inputShape.type(),inputShapeOfInfer), (float*)inputBlob.data}; inputData[inputName] = migraphx::argument{migraphx::shape(inputShape.type(), inputShapeOfInfer),
(float*)inputBlob.data};
// 推理 // 推理
std::vector<migraphx::argument> inferenceResults = net.eval(inputData); std::vector<migraphx::argument> inferenceResults = net.eval(inputData);
...@@ -156,7 +157,7 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco ...@@ -156,7 +157,7 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco
int n3 = outputShape.lens()[2]; int n3 = outputShape.lens()[2];
int n = n2 * n3; int n = n2 * n3;
std::vector<float> out(n); std::vector<float> out(n);
memcpy(out.data(),result.data(),sizeof(float)*outputShape.elements()); memcpy(out.data(), result.data(), sizeof(float) * outputShape.elements());
out.resize(n); out.resize(n);
int argmaxIdx; int argmaxIdx;
...@@ -164,14 +165,13 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco ...@@ -164,14 +165,13 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco
float score = 0.f; float score = 0.f;
int count = 0; int count = 0;
float maxValue = 0.0f; float maxValue = 0.0f;
for (int j = 0; j < n2; j++) for(int j = 0; j < n2; j++)
{ {
argmaxIdx = int(std::distance(&out[(j) * n3], argmaxIdx =
std::max_element(&out[(j) * n3], &out[(j + 1) * n3]))); int(std::distance(&out[(j)*n3], std::max_element(&out[(j)*n3], &out[(j + 1) * n3])));
maxValue = float(*std::max_element(&out[(j) * n3], maxValue = float(*std::max_element(&out[(j)*n3], &out[(j + 1) * n3]));
&out[(j + 1) * n3]));
if (argmaxIdx > 0 && (!(n > 0 && argmaxIdx == lastIndex))) if(argmaxIdx > 0 && (!(n > 0 && argmaxIdx == lastIndex)))
{ {
score += maxValue; score += maxValue;
count += 1; count += 1;
...@@ -184,4 +184,4 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco ...@@ -184,4 +184,4 @@ ErrorCode SVTR::Infer(cv::Mat &img, std::string &resultsChar, float &resultsdSco
return SUCCESS; return SUCCESS;
} }
} } // namespace migraphxSamples
...@@ -11,16 +11,17 @@ namespace migraphxSamples ...@@ -11,16 +11,17 @@ namespace migraphxSamples
class SVTR class SVTR
{ {
public: public:
SVTR(); SVTR();
~SVTR(); ~SVTR();
ErrorCode Initialize(InitializationParameterOfSVTR InitializationParameterOfSVTR); ErrorCode Initialize(InitializationParameterOfSVTR InitializationParameterOfSVTR);
ErrorCode Infer(cv::Mat &img, std::string &resultsChar, float &resultsdScore, float &maxWHRatio); ErrorCode
Infer(cv::Mat& img, std::string& resultsChar, float& resultsdScore, float& maxWHRatio);
private: private:
cv::FileStorage configurationFile; cv::FileStorage configurationFile;
migraphx::program net; migraphx::program net;
...@@ -29,8 +30,7 @@ private: ...@@ -29,8 +30,7 @@ private:
migraphx::shape inputShape; migraphx::shape inputShape;
std::string dictPath; std::string dictPath;
std::vector<std::string> charactorDict; std::vector<std::string> charactorDict;
}; };
} } // namespace migraphxSamples
#endif #endif
\ No newline at end of file
...@@ -3,22 +3,17 @@ ...@@ -3,22 +3,17 @@
namespace migraphxSamples namespace migraphxSamples
{ {
VLPR::VLPR() VLPR::VLPR() {}
{
} VLPR::~VLPR() { configurationFile.release(); }
VLPR::~VLPR() ErrorCode VLPR::Initialize(InitializationParameterOfDB initParamOfDB,
{ InitializationParameterOfSVTR initParamOfSVTR)
configurationFile.release();
}
ErrorCode VLPR::Initialize(InitializationParameterOfDB initParamOfDB, InitializationParameterOfSVTR initParamOfSVTR)
{ {
// 初始化DB // 初始化DB
initParamOfDB.configFilePath = CONFIG_FILE; initParamOfDB.configFilePath = CONFIG_FILE;
ErrorCode errorCode=db.Initialize(initParamOfDB); ErrorCode errorCode = db.Initialize(initParamOfDB);
if(errorCode!=SUCCESS) if(errorCode != SUCCESS)
{ {
LOG_ERROR(stdout, "fail to initialize db!\n"); LOG_ERROR(stdout, "fail to initialize db!\n");
exit(-1); exit(-1);
...@@ -27,8 +22,8 @@ ErrorCode VLPR::Initialize(InitializationParameterOfDB initParamOfDB, Initializa ...@@ -27,8 +22,8 @@ ErrorCode VLPR::Initialize(InitializationParameterOfDB initParamOfDB, Initializa
// 初始化SVTR // 初始化SVTR
initParamOfSVTR.configFilePath = CONFIG_FILE; initParamOfSVTR.configFilePath = CONFIG_FILE;
errorCode=svtr.Initialize(initParamOfSVTR); errorCode = svtr.Initialize(initParamOfSVTR);
if(errorCode!=SUCCESS) if(errorCode != SUCCESS)
{ {
LOG_ERROR(stdout, "fail to initialize svtr!\n"); LOG_ERROR(stdout, "fail to initialize svtr!\n");
exit(-1); exit(-1);
...@@ -36,12 +31,13 @@ ErrorCode VLPR::Initialize(InitializationParameterOfDB initParamOfDB, Initializa ...@@ -36,12 +31,13 @@ ErrorCode VLPR::Initialize(InitializationParameterOfDB initParamOfDB, Initializa
LOG_INFO(stdout, "succeed to initialize svtr\n"); LOG_INFO(stdout, "succeed to initialize svtr\n");
} }
ErrorCode VLPR::Infer(cv::Mat &img, std::vector<std::string> &recTexts, std::vector<float> &recTextScores) ErrorCode
VLPR::Infer(cv::Mat& img, std::vector<std::string>& recTexts, std::vector<float>& recTextScores)
{ {
// DB推理 // DB推理
db.Infer(img,imgLists); db.Infer(img, imgLists);
for (int i = 0; i < imgLists.size(); i++) for(int i = 0; i < imgLists.size(); i++)
{ {
float maxWHRatio = float(imgLists[i].cols) / float(imgLists[i].rows); float maxWHRatio = float(imgLists[i].cols) / float(imgLists[i].rows);
...@@ -52,7 +48,6 @@ ErrorCode VLPR::Infer(cv::Mat &img, std::vector<std::string> &recTexts, std::vec ...@@ -52,7 +48,6 @@ ErrorCode VLPR::Infer(cv::Mat &img, std::vector<std::string> &recTexts, std::vec
} }
return SUCCESS; return SUCCESS;
} }
} } // namespace migraphxSamples
\ No newline at end of file \ No newline at end of file
...@@ -12,24 +12,25 @@ namespace migraphxSamples ...@@ -12,24 +12,25 @@ namespace migraphxSamples
class VLPR class VLPR
{ {
public: public:
VLPR(); VLPR();
~VLPR(); ~VLPR();
ErrorCode Initialize(InitializationParameterOfDB initParamOfDB, InitializationParameterOfSVTR initParamOfSVTR); ErrorCode Initialize(InitializationParameterOfDB initParamOfDB,
InitializationParameterOfSVTR initParamOfSVTR);
ErrorCode Infer(cv::Mat &img, std::vector<std::string> &recTexts, std::vector<float> &recTextScores); ErrorCode
Infer(cv::Mat& img, std::vector<std::string>& recTexts, std::vector<float>& recTextScores);
private: private:
DB db; DB db;
SVTR svtr; SVTR svtr;
cv::FileStorage configurationFile; cv::FileStorage configurationFile;
std::vector<cv::Mat> imgLists; std::vector<cv::Mat> imgLists;
std::string recText; std::string recText;
float recTextScore; float recTextScore;
}; };
} } // namespace migraphxSamples
#endif #endif
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
...@@ -25,71 +25,81 @@ ...@@ -25,71 +25,81 @@
#include <sys/stat.h> #include <sys/stat.h>
#endif #endif
namespace migraphxSamples { namespace migraphxSamples
{
std::vector<std::string> Utility::ReadDict(const std::string &path) { std::vector<std::string> Utility::ReadDict(const std::string& path)
{
std::ifstream in(path); std::ifstream in(path);
std::string line; std::string line;
std::vector<std::string> m_vec; std::vector<std::string> m_vec;
if (in) { if(in)
while (getline(in, line)) { {
while(getline(in, line))
{
m_vec.push_back(line); m_vec.push_back(line);
} }
} else { }
std::cout << "no such label file: " << path << ", exit the program..." else
<< std::endl; {
std::cout << "no such label file: " << path << ", exit the program..." << std::endl;
exit(1); exit(1);
} }
return m_vec; return m_vec;
} }
void Utility::VisualizeBboxes(const cv::Mat &srcimg, void Utility::VisualizeBboxes(const cv::Mat& srcimg,
const std::vector<OCRPredictResult> &ocr_result, const std::vector<OCRPredictResult>& ocr_result,
const std::string &save_path) { const std::string& save_path)
{
cv::Mat img_vis; cv::Mat img_vis;
srcimg.copyTo(img_vis); srcimg.copyTo(img_vis);
for (int n = 0; n < ocr_result.size(); n++) { for(int n = 0; n < ocr_result.size(); n++)
{
cv::Point rook_points[4]; cv::Point rook_points[4];
for (int m = 0; m < ocr_result[n].box.size(); m++) { for(int m = 0; m < ocr_result[n].box.size(); m++)
rook_points[m] = {
cv::Point(int(ocr_result[n].box[m][0]), int(ocr_result[n].box[m][1])); rook_points[m] = cv::Point(int(ocr_result[n].box[m][0]), int(ocr_result[n].box[m][1]));
} }
const cv::Point *ppt[1] = {rook_points}; const cv::Point* ppt[1] = {rook_points};
int npt[] = {4}; int npt[] = {4};
cv::polylines(img_vis, ppt, npt, 1, 1, CV_RGB(0, 255, 0), 2, 8, 0); cv::polylines(img_vis, ppt, npt, 1, 1, CV_RGB(0, 255, 0), 2, 8, 0);
} }
cv::imwrite(save_path, img_vis); cv::imwrite(save_path, img_vis);
std::cout << "The detection visualized image saved in " + save_path std::cout << "The detection visualized image saved in " + save_path << std::endl;
<< std::endl;
} }
void Utility::VisualizeBboxes(const cv::Mat &srcimg, void Utility::VisualizeBboxes(const cv::Mat& srcimg,
const StructurePredictResult &structure_result, const StructurePredictResult& structure_result,
const std::string &save_path) { const std::string& save_path)
{
cv::Mat img_vis; cv::Mat img_vis;
srcimg.copyTo(img_vis); srcimg.copyTo(img_vis);
img_vis = crop_image(img_vis, structure_result.box); img_vis = crop_image(img_vis, structure_result.box);
for (int n = 0; n < structure_result.cell_box.size(); n++) { for(int n = 0; n < structure_result.cell_box.size(); n++)
if (structure_result.cell_box[n].size() == 8) { {
if(structure_result.cell_box[n].size() == 8)
{
cv::Point rook_points[4]; cv::Point rook_points[4];
for (int m = 0; m < structure_result.cell_box[n].size(); m += 2) { for(int m = 0; m < structure_result.cell_box[n].size(); m += 2)
rook_points[m / 2] = {
cv::Point(int(structure_result.cell_box[n][m]), rook_points[m / 2] = cv::Point(int(structure_result.cell_box[n][m]),
int(structure_result.cell_box[n][m + 1])); int(structure_result.cell_box[n][m + 1]));
} }
const cv::Point *ppt[1] = {rook_points}; const cv::Point* ppt[1] = {rook_points};
int npt[] = {4}; int npt[] = {4};
cv::polylines(img_vis, ppt, npt, 1, 1, CV_RGB(0, 255, 0), 2, 8, 0); cv::polylines(img_vis, ppt, npt, 1, 1, CV_RGB(0, 255, 0), 2, 8, 0);
} else if (structure_result.cell_box[n].size() == 4) { }
else if(structure_result.cell_box[n].size() == 4)
{
cv::Point rook_points[2]; cv::Point rook_points[2];
rook_points[0] = cv::Point(int(structure_result.cell_box[n][0]), rook_points[0] = cv::Point(int(structure_result.cell_box[n][0]),
int(structure_result.cell_box[n][1])); int(structure_result.cell_box[n][1]));
rook_points[1] = cv::Point(int(structure_result.cell_box[n][2]), rook_points[1] = cv::Point(int(structure_result.cell_box[n][2]),
int(structure_result.cell_box[n][3])); int(structure_result.cell_box[n][3]));
cv::rectangle(img_vis, rook_points[0], rook_points[1], CV_RGB(0, 255, 0), cv::rectangle(img_vis, rook_points[0], rook_points[1], CV_RGB(0, 255, 0), 2, 8, 0);
2, 8, 0);
} }
} }
...@@ -98,40 +108,44 @@ void Utility::VisualizeBboxes(const cv::Mat &srcimg, ...@@ -98,40 +108,44 @@ void Utility::VisualizeBboxes(const cv::Mat &srcimg,
} }
// list all files under a directory // list all files under a directory
void Utility::GetAllFiles(const char *dir_name, void Utility::GetAllFiles(const char* dir_name, std::vector<std::string>& all_inputs)
std::vector<std::string> &all_inputs) { {
if (NULL == dir_name) { if(NULL == dir_name)
{
std::cout << " dir_name is null ! " << std::endl; std::cout << " dir_name is null ! " << std::endl;
return; return;
} }
struct stat s; struct stat s;
stat(dir_name, &s); stat(dir_name, &s);
if (!S_ISDIR(s.st_mode)) { if(!S_ISDIR(s.st_mode))
{
std::cout << "dir_name is not a valid directory !" << std::endl; std::cout << "dir_name is not a valid directory !" << std::endl;
all_inputs.push_back(dir_name); all_inputs.push_back(dir_name);
return; return;
} else { }
struct dirent *filename; // return value for readdir() else
DIR *dir; // return value for opendir() {
struct dirent* filename; // return value for readdir()
DIR* dir; // return value for opendir()
dir = opendir(dir_name); dir = opendir(dir_name);
if (NULL == dir) { if(NULL == dir)
{
std::cout << "Can not open dir " << dir_name << std::endl; std::cout << "Can not open dir " << dir_name << std::endl;
return; return;
} }
std::cout << "Successfully opened the dir !" << std::endl; std::cout << "Successfully opened the dir !" << std::endl;
while ((filename = readdir(dir)) != NULL) { while((filename = readdir(dir)) != NULL)
if (strcmp(filename->d_name, ".") == 0 || {
strcmp(filename->d_name, "..") == 0) if(strcmp(filename->d_name, ".") == 0 || strcmp(filename->d_name, "..") == 0)
continue; continue;
// img_dir + std::string("/") + all_inputs[0]; // img_dir + std::string("/") + all_inputs[0];
all_inputs.push_back(dir_name + std::string("/") + all_inputs.push_back(dir_name + std::string("/") + std::string(filename->d_name));
std::string(filename->d_name));
} }
} }
} }
cv::Mat Utility::GetRotateCropImage(const cv::Mat &srcimage, cv::Mat Utility::GetRotateCropImage(const cv::Mat& srcimage, std::vector<std::vector<int>> box)
std::vector<std::vector<int>> box) { {
cv::Mat image; cv::Mat image;
srcimage.copyTo(image); srcimage.copyTo(image);
std::vector<std::vector<int>> points = box; std::vector<std::vector<int>> points = box;
...@@ -146,15 +160,16 @@ cv::Mat Utility::GetRotateCropImage(const cv::Mat &srcimage, ...@@ -146,15 +160,16 @@ cv::Mat Utility::GetRotateCropImage(const cv::Mat &srcimage,
cv::Mat img_crop; cv::Mat img_crop;
image(cv::Rect(left, top, right - left, bottom - top)).copyTo(img_crop); image(cv::Rect(left, top, right - left, bottom - top)).copyTo(img_crop);
for (int i = 0; i < points.size(); i++) { for(int i = 0; i < points.size(); i++)
{
points[i][0] -= left; points[i][0] -= left;
points[i][1] -= top; points[i][1] -= top;
} }
int img_crop_width = int(sqrt(pow(points[0][0] - points[1][0], 2) + int img_crop_width =
pow(points[0][1] - points[1][1], 2))); int(sqrt(pow(points[0][0] - points[1][0], 2) + pow(points[0][1] - points[1][1], 2)));
int img_crop_height = int(sqrt(pow(points[0][0] - points[3][0], 2) + int img_crop_height =
pow(points[0][1] - points[3][1], 2))); int(sqrt(pow(points[0][0] - points[3][0], 2) + pow(points[0][1] - points[3][1], 2)));
cv::Point2f pts_std[4]; cv::Point2f pts_std[4];
pts_std[0] = cv::Point2f(0., 0.); pts_std[0] = cv::Point2f(0., 0.);
...@@ -171,59 +186,69 @@ cv::Mat Utility::GetRotateCropImage(const cv::Mat &srcimage, ...@@ -171,59 +186,69 @@ cv::Mat Utility::GetRotateCropImage(const cv::Mat &srcimage,
cv::Mat M = cv::getPerspectiveTransform(pointsf, pts_std); cv::Mat M = cv::getPerspectiveTransform(pointsf, pts_std);
cv::Mat dst_img; cv::Mat dst_img;
cv::warpPerspective(img_crop, dst_img, M, cv::warpPerspective(
cv::Size(img_crop_width, img_crop_height), img_crop, dst_img, M, cv::Size(img_crop_width, img_crop_height), cv::BORDER_REPLICATE);
cv::BORDER_REPLICATE);
if (float(dst_img.rows) >= float(dst_img.cols) * 1.5) { if(float(dst_img.rows) >= float(dst_img.cols) * 1.5)
{
cv::Mat srcCopy = cv::Mat(dst_img.rows, dst_img.cols, dst_img.depth()); cv::Mat srcCopy = cv::Mat(dst_img.rows, dst_img.cols, dst_img.depth());
cv::transpose(dst_img, srcCopy); cv::transpose(dst_img, srcCopy);
cv::flip(srcCopy, srcCopy, 0); cv::flip(srcCopy, srcCopy, 0);
return srcCopy; return srcCopy;
} else { }
else
{
return dst_img; return dst_img;
} }
} }
std::vector<int> Utility::argsort(const std::vector<float> &array) { std::vector<int> Utility::argsort(const std::vector<float>& array)
{
const int array_len(array.size()); const int array_len(array.size());
std::vector<int> array_index(array_len, 0); std::vector<int> array_index(array_len, 0);
for (int i = 0; i < array_len; ++i) for(int i = 0; i < array_len; ++i)
array_index[i] = i; array_index[i] = i;
std::sort( std::sort(array_index.begin(), array_index.end(), [&array](int pos1, int pos2) {
array_index.begin(), array_index.end(), return (array[pos1] < array[pos2]);
[&array](int pos1, int pos2) { return (array[pos1] < array[pos2]); }); });
return array_index; return array_index;
} }
std::string Utility::basename(const std::string &filename) { std::string Utility::basename(const std::string& filename)
if (filename.empty()) { {
if(filename.empty())
{
return ""; return "";
} }
auto len = filename.length(); auto len = filename.length();
auto index = filename.find_last_of("/\\"); auto index = filename.find_last_of("/\\");
if (index == std::string::npos) { if(index == std::string::npos)
{
return filename; return filename;
} }
if (index + 1 >= len) { if(index + 1 >= len)
{
len--; len--;
index = filename.substr(0, len).find_last_of("/\\"); index = filename.substr(0, len).find_last_of("/\\");
if (len == 0) { if(len == 0)
{
return filename; return filename;
} }
if (index == 0) { if(index == 0)
{
return filename.substr(1, len - 1); return filename.substr(1, len - 1);
} }
if (index == std::string::npos) { if(index == std::string::npos)
{
return filename.substr(0, len); return filename.substr(0, len);
} }
...@@ -233,7 +258,8 @@ std::string Utility::basename(const std::string &filename) { ...@@ -233,7 +258,8 @@ std::string Utility::basename(const std::string &filename) {
return filename.substr(index + 1, len - index); return filename.substr(index + 1, len - index);
} }
bool Utility::PathExists(const std::string &path) { bool Utility::PathExists(const std::string& path)
{
#ifdef _WIN32 #ifdef _WIN32
struct _stat buffer; struct _stat buffer;
return (_stat(path.c_str(), &buffer) == 0); return (_stat(path.c_str(), &buffer) == 0);
...@@ -243,7 +269,8 @@ bool Utility::PathExists(const std::string &path) { ...@@ -243,7 +269,8 @@ bool Utility::PathExists(const std::string &path) {
#endif // !_WIN32 #endif // !_WIN32
} }
void Utility::CreateDir(const std::string &path) { void Utility::CreateDir(const std::string& path)
{
#ifdef _WIN32 #ifdef _WIN32
_mkdir(path.c_str()); _mkdir(path.c_str());
#else #else
...@@ -251,29 +278,36 @@ void Utility::CreateDir(const std::string &path) { ...@@ -251,29 +278,36 @@ void Utility::CreateDir(const std::string &path) {
#endif // !_WIN32 #endif // !_WIN32
} }
void Utility::print_result(const std::vector<OCRPredictResult> &ocr_result) { void Utility::print_result(const std::vector<OCRPredictResult>& ocr_result)
for (int i = 0; i < ocr_result.size(); i++) { {
for(int i = 0; i < ocr_result.size(); i++)
{
std::cout << i << "\t"; std::cout << i << "\t";
// det // det
std::vector<std::vector<int>> boxes = ocr_result[i].box; std::vector<std::vector<int>> boxes = ocr_result[i].box;
if (boxes.size() > 0) { if(boxes.size() > 0)
{
std::cout << "det boxes: ["; std::cout << "det boxes: [";
for (int n = 0; n < boxes.size(); n++) { for(int n = 0; n < boxes.size(); n++)
{
std::cout << '[' << boxes[n][0] << ',' << boxes[n][1] << "]"; std::cout << '[' << boxes[n][0] << ',' << boxes[n][1] << "]";
if (n != boxes.size() - 1) { if(n != boxes.size() - 1)
{
std::cout << ','; std::cout << ',';
} }
} }
std::cout << "] "; std::cout << "] ";
} }
// rec // rec
if (ocr_result[i].score != -1.0) { if(ocr_result[i].score != -1.0)
std::cout << "rec text: " << ocr_result[i].text {
<< " rec score: " << ocr_result[i].score << " "; std::cout << "rec text: " << ocr_result[i].text << " rec score: " << ocr_result[i].score
<< " ";
} }
// cls // cls
if (ocr_result[i].cls_label != -1) { if(ocr_result[i].cls_label != -1)
{
std::cout << "cls label: " << ocr_result[i].cls_label std::cout << "cls label: " << ocr_result[i].cls_label
<< " cls score: " << ocr_result[i].cls_score; << " cls score: " << ocr_result[i].cls_score;
} }
...@@ -281,7 +315,8 @@ void Utility::print_result(const std::vector<OCRPredictResult> &ocr_result) { ...@@ -281,7 +315,8 @@ void Utility::print_result(const std::vector<OCRPredictResult> &ocr_result) {
} }
} }
cv::Mat Utility::crop_image(cv::Mat &img, const std::vector<int> &box) { cv::Mat Utility::crop_image(cv::Mat& img, const std::vector<int>& box)
{
cv::Mat crop_im; cv::Mat crop_im;
int crop_x1 = std::max(0, box[0]); int crop_x1 = std::max(0, box[0]);
int crop_y1 = std::max(0, box[1]); int crop_y1 = std::max(0, box[1]);
...@@ -289,28 +324,31 @@ cv::Mat Utility::crop_image(cv::Mat &img, const std::vector<int> &box) { ...@@ -289,28 +324,31 @@ cv::Mat Utility::crop_image(cv::Mat &img, const std::vector<int> &box) {
int crop_y2 = std::min(img.rows - 1, box[3] - 1); int crop_y2 = std::min(img.rows - 1, box[3] - 1);
crop_im = cv::Mat::zeros(box[3] - box[1], box[2] - box[0], 16); crop_im = cv::Mat::zeros(box[3] - box[1], box[2] - box[0], 16);
cv::Mat crop_im_window = cv::Mat crop_im_window = crop_im(cv::Range(crop_y1 - box[1], crop_y2 + 1 - box[1]),
crop_im(cv::Range(crop_y1 - box[1], crop_y2 + 1 - box[1]),
cv::Range(crop_x1 - box[0], crop_x2 + 1 - box[0])); cv::Range(crop_x1 - box[0], crop_x2 + 1 - box[0]));
cv::Mat roi_img = cv::Mat roi_img = img(cv::Range(crop_y1, crop_y2 + 1), cv::Range(crop_x1, crop_x2 + 1));
img(cv::Range(crop_y1, crop_y2 + 1), cv::Range(crop_x1, crop_x2 + 1));
crop_im_window += roi_img; crop_im_window += roi_img;
return crop_im; return crop_im;
} }
cv::Mat Utility::crop_image(cv::Mat &img, const std::vector<float> &box) { cv::Mat Utility::crop_image(cv::Mat& img, const std::vector<float>& box)
std::vector<int> box_int = {(int)box[0], (int)box[1], (int)box[2], {
(int)box[3]}; std::vector<int> box_int = {(int)box[0], (int)box[1], (int)box[2], (int)box[3]};
return crop_image(img, box_int); return crop_image(img, box_int);
} }
void Utility::sorted_boxes(std::vector<OCRPredictResult> &ocr_result) { void Utility::sorted_boxes(std::vector<OCRPredictResult>& ocr_result)
{
std::sort(ocr_result.begin(), ocr_result.end(), Utility::comparison_box); std::sort(ocr_result.begin(), ocr_result.end(), Utility::comparison_box);
if (ocr_result.size() > 0) { if(ocr_result.size() > 0)
for (int i = 0; i < ocr_result.size() - 1; i++) { {
for (int j = i; j > 0; j--) { for(int i = 0; i < ocr_result.size() - 1; i++)
if (abs(ocr_result[j + 1].box[0][1] - ocr_result[j].box[0][1]) < 10 && {
(ocr_result[j + 1].box[0][0] < ocr_result[j].box[0][0])) { for(int j = i; j > 0; j--)
{
if(abs(ocr_result[j + 1].box[0][1] - ocr_result[j].box[0][1]) < 10 &&
(ocr_result[j + 1].box[0][0] < ocr_result[j].box[0][0]))
{
std::swap(ocr_result[i], ocr_result[i + 1]); std::swap(ocr_result[i], ocr_result[i + 1]);
} }
} }
...@@ -318,7 +356,8 @@ void Utility::sorted_boxes(std::vector<OCRPredictResult> &ocr_result) { ...@@ -318,7 +356,8 @@ void Utility::sorted_boxes(std::vector<OCRPredictResult> &ocr_result) {
} }
} }
std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<std::vector<int>> &box) { std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<std::vector<int>>& box)
{
int x_collect[4] = {box[0][0], box[1][0], box[2][0], box[3][0]}; int x_collect[4] = {box[0][0], box[1][0], box[2][0], box[3][0]};
int y_collect[4] = {box[0][1], box[1][1], box[2][1], box[3][1]}; int y_collect[4] = {box[0][1], box[1][1], box[2][1], box[3][1]};
int left = int(*std::min_element(x_collect, x_collect + 4)); int left = int(*std::min_element(x_collect, x_collect + 4));
...@@ -333,7 +372,8 @@ std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<std::vector<int>> &box) { ...@@ -333,7 +372,8 @@ std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<std::vector<int>> &box) {
return box1; return box1;
} }
std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<int> &box) { std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<int>& box)
{
int x_collect[4] = {box[0], box[2], box[4], box[6]}; int x_collect[4] = {box[0], box[2], box[4], box[6]};
int y_collect[4] = {box[1], box[3], box[5], box[7]}; int y_collect[4] = {box[1], box[3], box[5], box[7]};
int left = int(*std::min_element(x_collect, x_collect + 4)); int left = int(*std::min_element(x_collect, x_collect + 4));
...@@ -348,8 +388,10 @@ std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<int> &box) { ...@@ -348,8 +388,10 @@ std::vector<int> Utility::xyxyxyxy2xyxy(std::vector<int> &box) {
return box1; return box1;
} }
float Utility::fast_exp(float x) { float Utility::fast_exp(float x)
union { {
union
{
uint32_t i; uint32_t i;
float f; float f;
} v{}; } v{};
...@@ -357,26 +399,29 @@ float Utility::fast_exp(float x) { ...@@ -357,26 +399,29 @@ float Utility::fast_exp(float x) {
return v.f; return v.f;
} }
std::vector<float> std::vector<float> Utility::activation_function_softmax(std::vector<float>& src)
Utility::activation_function_softmax(std::vector<float> &src) { {
int length = src.size(); int length = src.size();
std::vector<float> dst; std::vector<float> dst;
dst.resize(length); dst.resize(length);
const float alpha = float(*std::max_element(&src[0], &src[0 + length])); const float alpha = float(*std::max_element(&src[0], &src[0 + length]));
float denominator{0}; float denominator{0};
for (int i = 0; i < length; ++i) { for(int i = 0; i < length; ++i)
{
dst[i] = fast_exp(src[i] - alpha); dst[i] = fast_exp(src[i] - alpha);
denominator += dst[i]; denominator += dst[i];
} }
for (int i = 0; i < length; ++i) { for(int i = 0; i < length; ++i)
{
dst[i] /= denominator; dst[i] /= denominator;
} }
return dst; return dst;
} }
float Utility::iou(std::vector<int> &box1, std::vector<int> &box2) { float Utility::iou(std::vector<int>& box1, std::vector<int>& box2)
{
int area1 = std::max(0, box1[2] - box1[0]) * std::max(0, box1[3] - box1[1]); int area1 = std::max(0, box1[2] - box1[0]) * std::max(0, box1[3] - box1[1]);
int area2 = std::max(0, box2[2] - box2[0]) * std::max(0, box2[3] - box2[1]); int area2 = std::max(0, box2[2] - box2[0]) * std::max(0, box2[3] - box2[1]);
...@@ -390,19 +435,21 @@ float Utility::iou(std::vector<int> &box1, std::vector<int> &box2) { ...@@ -390,19 +435,21 @@ float Utility::iou(std::vector<int> &box1, std::vector<int> &box2) {
int y2 = std::min(box1[3], box2[3]); int y2 = std::min(box1[3], box2[3]);
// judge if there is an intersect // judge if there is an intersect
if (y1 >= y2 || x1 >= x2) { if(y1 >= y2 || x1 >= x2)
{
return 0.0; return 0.0;
} else { }
else
{
int intersect = (x2 - x1) * (y2 - y1); int intersect = (x2 - x1) * (y2 - y1);
return intersect / (sum_area - intersect + 0.00000001); return intersect / (sum_area - intersect + 0.00000001);
} }
} }
float Utility::iou(std::vector<float> &box1, std::vector<float> &box2) { float Utility::iou(std::vector<float>& box1, std::vector<float>& box2)
float area1 = std::max((float)0.0, box1[2] - box1[0]) * {
std::max((float)0.0, box1[3] - box1[1]); float area1 = std::max((float)0.0, box1[2] - box1[0]) * std::max((float)0.0, box1[3] - box1[1]);
float area2 = std::max((float)0.0, box2[2] - box2[0]) * float area2 = std::max((float)0.0, box2[2] - box2[0]) * std::max((float)0.0, box2[3] - box2[1]);
std::max((float)0.0, box2[3] - box2[1]);
// computing the sum_area // computing the sum_area
float sum_area = area1 + area2; float sum_area = area1 + area2;
...@@ -414,9 +461,12 @@ float Utility::iou(std::vector<float> &box1, std::vector<float> &box2) { ...@@ -414,9 +461,12 @@ float Utility::iou(std::vector<float> &box1, std::vector<float> &box2) {
float y2 = std::min(box1[3], box2[3]); float y2 = std::min(box1[3], box2[3]);
// judge if there is an intersect // judge if there is an intersect
if (y1 >= y2 || x1 >= x2) { if(y1 >= y2 || x1 >= x2)
{
return 0.0; return 0.0;
} else { }
else
{
float intersect = (x2 - x1) * (y2 - y1); float intersect = (x2 - x1) * (y2 - y1);
return intersect / (sum_area - intersect + 0.00000001); return intersect / (sum_area - intersect + 0.00000001);
} }
......
...@@ -30,9 +30,11 @@ ...@@ -30,9 +30,11 @@
#include "opencv2/imgcodecs.hpp" #include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp" #include "opencv2/imgproc.hpp"
namespace migraphxSamples { namespace migraphxSamples
{
struct OCRPredictResult { struct OCRPredictResult
{
std::vector<std::vector<int>> box; std::vector<std::vector<int>> box;
std::string text; std::string text;
float score = -1.0; float score = -1.0;
...@@ -40,7 +42,8 @@ struct OCRPredictResult { ...@@ -40,7 +42,8 @@ struct OCRPredictResult {
int cls_label = -1; int cls_label = -1;
}; };
struct StructurePredictResult { struct StructurePredictResult
{
std::vector<float> box; std::vector<float> box;
std::vector<std::vector<int>> cell_box; std::vector<std::vector<int>> cell_box;
std::string type; std::string type;
...@@ -50,61 +53,65 @@ struct StructurePredictResult { ...@@ -50,61 +53,65 @@ struct StructurePredictResult {
float confidence; float confidence;
}; };
class Utility { class Utility
public: {
static std::vector<std::string> ReadDict(const std::string &path); public:
static std::vector<std::string> ReadDict(const std::string& path);
static void VisualizeBboxes(const cv::Mat &srcimg, static void VisualizeBboxes(const cv::Mat& srcimg,
const std::vector<OCRPredictResult> &ocr_result, const std::vector<OCRPredictResult>& ocr_result,
const std::string &save_path); const std::string& save_path);
static void VisualizeBboxes(const cv::Mat &srcimg, static void VisualizeBboxes(const cv::Mat& srcimg,
const StructurePredictResult &structure_result, const StructurePredictResult& structure_result,
const std::string &save_path); const std::string& save_path);
template <class ForwardIterator> template <class ForwardIterator>
inline static size_t argmax(ForwardIterator first, ForwardIterator last) { inline static size_t argmax(ForwardIterator first, ForwardIterator last)
{
return std::distance(first, std::max_element(first, last)); return std::distance(first, std::max_element(first, last));
} }
static void GetAllFiles(const char *dir_name, static void GetAllFiles(const char* dir_name, std::vector<std::string>& all_inputs);
std::vector<std::string> &all_inputs);
static cv::Mat GetRotateCropImage(const cv::Mat &srcimage, static cv::Mat GetRotateCropImage(const cv::Mat& srcimage, std::vector<std::vector<int>> box);
std::vector<std::vector<int>> box);
static std::vector<int> argsort(const std::vector<float> &array); static std::vector<int> argsort(const std::vector<float>& array);
static std::string basename(const std::string &filename); static std::string basename(const std::string& filename);
static bool PathExists(const std::string &path); static bool PathExists(const std::string& path);
static void CreateDir(const std::string &path); static void CreateDir(const std::string& path);
static void print_result(const std::vector<OCRPredictResult> &ocr_result); static void print_result(const std::vector<OCRPredictResult>& ocr_result);
static cv::Mat crop_image(cv::Mat &img, const std::vector<int> &area); static cv::Mat crop_image(cv::Mat& img, const std::vector<int>& area);
static cv::Mat crop_image(cv::Mat &img, const std::vector<float> &area); static cv::Mat crop_image(cv::Mat& img, const std::vector<float>& area);
static void sorted_boxes(std::vector<OCRPredictResult> &ocr_result); static void sorted_boxes(std::vector<OCRPredictResult>& ocr_result);
static std::vector<int> xyxyxyxy2xyxy(std::vector<std::vector<int>> &box); static std::vector<int> xyxyxyxy2xyxy(std::vector<std::vector<int>>& box);
static std::vector<int> xyxyxyxy2xyxy(std::vector<int> &box); static std::vector<int> xyxyxyxy2xyxy(std::vector<int>& box);
static float fast_exp(float x); static float fast_exp(float x);
static std::vector<float> static std::vector<float> activation_function_softmax(std::vector<float>& src);
activation_function_softmax(std::vector<float> &src); static float iou(std::vector<int>& box1, std::vector<int>& box2);
static float iou(std::vector<int> &box1, std::vector<int> &box2); static float iou(std::vector<float>& box1, std::vector<float>& box2);
static float iou(std::vector<float> &box1, std::vector<float> &box2);
private:
private: static bool comparison_box(const OCRPredictResult& result1, const OCRPredictResult& result2)
static bool comparison_box(const OCRPredictResult &result1, {
const OCRPredictResult &result2) { if(result1.box[0][1] < result2.box[0][1])
if (result1.box[0][1] < result2.box[0][1]) { {
return true; return true;
} else if (result1.box[0][1] == result2.box[0][1]) { }
else if(result1.box[0][1] == result2.box[0][1])
{
return result1.box[0][0] < result2.box[0][0]; return result1.box[0][0] < result2.box[0][0];
} else { }
else
{
return false; return false;
} }
} }
......
...@@ -19,21 +19,21 @@ namespace migraphxSamples ...@@ -19,21 +19,21 @@ namespace migraphxSamples
typedef enum _ErrorCode typedef enum _ErrorCode
{ {
SUCCESS=0, // 0 SUCCESS = 0, // 0
MODEL_NOT_EXIST, // 模型不存在 MODEL_NOT_EXIST, // 模型不存在
CONFIG_FILE_NOT_EXIST, // 配置文件不存在 CONFIG_FILE_NOT_EXIST, // 配置文件不存在
FAIL_TO_LOAD_MODEL, // 加载模型失败 FAIL_TO_LOAD_MODEL, // 加载模型失败
FAIL_TO_OPEN_CONFIG_FILE, // 加载配置文件失败 FAIL_TO_OPEN_CONFIG_FILE, // 加载配置文件失败
IMAGE_ERROR, // 图像错误 IMAGE_ERROR, // 图像错误
}ErrorCode; } ErrorCode;
typedef struct _ResultOfPrediction typedef struct _ResultOfPrediction
{ {
float confidence; float confidence;
int label; int label;
_ResultOfPrediction():confidence(0.0f),label(0){} _ResultOfPrediction() : confidence(0.0f), label(0) {}
}ResultOfPrediction; } ResultOfPrediction;
typedef struct _ResultOfDetection typedef struct _ResultOfDetection
{ {
...@@ -43,15 +43,15 @@ typedef struct _ResultOfDetection ...@@ -43,15 +43,15 @@ typedef struct _ResultOfDetection
std::string className; std::string className;
bool exist; bool exist;
_ResultOfDetection():confidence(0.0f),classID(0),exist(true){} _ResultOfDetection() : confidence(0.0f), classID(0), exist(true) {}
}ResultOfDetection; } ResultOfDetection;
typedef struct _InitializationParameterOfDetector typedef struct _InitializationParameterOfDetector
{ {
std::string parentPath; std::string parentPath;
std::string configFilePath; std::string configFilePath;
}InitializationParameterOfDetector; } InitializationParameterOfDetector;
typedef struct _InitializationParameterOfDetector InitializationParameterOfClassifier; typedef struct _InitializationParameterOfDetector InitializationParameterOfClassifier;
typedef struct _InitializationParameterOfDetector InitializationParameterOfSuperresolution; typedef struct _InitializationParameterOfDetector InitializationParameterOfSuperresolution;
...@@ -61,7 +61,6 @@ typedef struct _InitializationParameterOfDetector InitializationParameterOfOcr; ...@@ -61,7 +61,6 @@ typedef struct _InitializationParameterOfDetector InitializationParameterOfOcr;
typedef struct _InitializationParameterOfDetector InitializationParameterOfDB; typedef struct _InitializationParameterOfDetector InitializationParameterOfDB;
typedef struct _InitializationParameterOfDetector InitializationParameterOfSVTR; typedef struct _InitializationParameterOfDetector InitializationParameterOfSVTR;
} } // namespace migraphxSamples
#endif #endif
...@@ -3,34 +3,37 @@ ...@@ -3,34 +3,37 @@
namespace migraphxSamples namespace migraphxSamples
{ {
bool CompareConfidence(const ResultOfDetection &L,const ResultOfDetection &R) bool CompareConfidence(const ResultOfDetection& L, const ResultOfDetection& R)
{ {
return L.confidence > R.confidence; return L.confidence > R.confidence;
} }
bool CompareArea(const ResultOfDetection &L,const ResultOfDetection &R) bool CompareArea(const ResultOfDetection& L, const ResultOfDetection& R)
{ {
return L.boundingBox.area() > R.boundingBox.area(); return L.boundingBox.area() > R.boundingBox.area();
} }
void NMS(std::vector<ResultOfDetection> &detections, float IOUThreshold) void NMS(std::vector<ResultOfDetection>& detections, float IOUThreshold)
{ {
// sort // sort
std::sort(detections.begin(), detections.end(), CompareConfidence); std::sort(detections.begin(), detections.end(), CompareConfidence);
for (int i = 0; i<detections.size(); ++i) for(int i = 0; i < detections.size(); ++i)
{ {
if (detections[i].exist) if(detections[i].exist)
{ {
for (int j = i + 1; j<detections.size(); ++j) for(int j = i + 1; j < detections.size(); ++j)
{ {
if (detections[j].exist) if(detections[j].exist)
{ {
// compute IOU // compute IOU
float intersectionArea = (detections[i].boundingBox & detections[j].boundingBox).area(); float intersectionArea =
float intersectionRate = intersectionArea / (detections[i].boundingBox.area() + detections[j].boundingBox.area() - intersectionArea); (detections[i].boundingBox & detections[j].boundingBox).area();
float intersectionRate =
intersectionArea / (detections[i].boundingBox.area() +
detections[j].boundingBox.area() - intersectionArea);
if (intersectionRate>IOUThreshold) if(intersectionRate > IOUThreshold)
{ {
detections[j].exist = false; detections[j].exist = false;
} }
...@@ -38,7 +41,6 @@ void NMS(std::vector<ResultOfDetection> &detections, float IOUThreshold) ...@@ -38,7 +41,6 @@ void NMS(std::vector<ResultOfDetection> &detections, float IOUThreshold)
} }
} }
} }
} }
} } // namespace migraphxSamples
...@@ -9,12 +9,12 @@ namespace migraphxSamples ...@@ -9,12 +9,12 @@ namespace migraphxSamples
{ {
// 排序规则: 按照置信度或者按照面积排序 // 排序规则: 按照置信度或者按照面积排序
bool CompareConfidence(const ResultOfDetection &L,const ResultOfDetection &R); bool CompareConfidence(const ResultOfDetection& L, const ResultOfDetection& R);
bool CompareArea(const ResultOfDetection &L,const ResultOfDetection &R); bool CompareArea(const ResultOfDetection& L, const ResultOfDetection& R);
// 非极大抑制 // 非极大抑制
void NMS(std::vector<ResultOfDetection> &detections, float IOUThreshold); void NMS(std::vector<ResultOfDetection>& detections, float IOUThreshold);
} } // namespace migraphxSamples
#endif #endif
This diff is collapsed.
...@@ -10,19 +10,19 @@ namespace migraphxSamples ...@@ -10,19 +10,19 @@ namespace migraphxSamples
{ {
// 路径是否存在 // 路径是否存在
bool Exists(const std::string &path); bool Exists(const std::string& path);
// 路径是否为目录 // 路径是否为目录
bool IsDirectory(const std::string &path); bool IsDirectory(const std::string& path);
// 是否是路径分隔符(Linux:‘/’,Windows:’\\’) // 是否是路径分隔符(Linux:‘/’,Windows:’\\’)
bool IsPathSeparator(char c); bool IsPathSeparator(char c);
// 路径拼接 // 路径拼接
std::string JoinPath(const std::string &base, const std::string &path); std::string JoinPath(const std::string& base, const std::string& path);
// 创建多级目录,注意:创建多级目录的时候,目标目录是不能有文件存在的 // 创建多级目录,注意:创建多级目录的时候,目标目录是不能有文件存在的
bool CreateDirectories(const std::string &directoryPath); bool CreateDirectories(const std::string& directoryPath);
/** 生成符合指定模式的文件名列表(支持递归遍历) /** 生成符合指定模式的文件名列表(支持递归遍历)
* *
...@@ -36,25 +36,33 @@ bool CreateDirectories(const std::string &directoryPath); ...@@ -36,25 +36,33 @@ bool CreateDirectories(const std::string &directoryPath);
5. 不能返回子目录名 5. 不能返回子目录名
* *
*/ */
void GetFileNameList(const std::string &directory, const std::string &pattern, std::vector<std::string> &result, bool recursive, bool addPath); void GetFileNameList(const std::string& directory,
const std::string& pattern,
std::vector<std::string>& result,
bool recursive,
bool addPath);
// 与GetFileNameList的区别在于如果有子目录,在addPath为true的时候会返回子目录路径(目录名最后有"/") // 与GetFileNameList的区别在于如果有子目录,在addPath为true的时候会返回子目录路径(目录名最后有"/")
void GetFileNameList2(const std::string &directory, const std::string &pattern, std::vector<std::string> &result, bool recursive, bool addPath); void GetFileNameList2(const std::string& directory,
const std::string& pattern,
std::vector<std::string>& result,
bool recursive,
bool addPath);
// 删除文件或者目录,支持递归删除 // 删除文件或者目录,支持递归删除
void Remove(const std::string &directory, const std::string &extension=""); void Remove(const std::string& directory, const std::string& extension = "");
/** 获取路径的文件名和扩展名 /** 获取路径的文件名和扩展名
* *
* 示例:path为D:/1/1.txt,则GetFileName()为1.txt,GetFileName_NoExtension()为1,GetExtension()为.txt,GetParentPath()为D:/1/ * 示例:path为D:/1/1.txt,则GetFileName()为1.txt,GetFileName_NoExtension()为1,GetExtension()为.txt,GetParentPath()为D:/1/
*/ */
std::string GetFileName(const std::string &path); std::string GetFileName(const std::string& path);
std::string GetFileName_NoExtension(const std::string &path); std::string GetFileName_NoExtension(const std::string& path);
std::string GetExtension(const std::string &path); std::string GetExtension(const std::string& path);
std::string GetParentPath(const std::string &path); std::string GetParentPath(const std::string& path);
// 拷贝文件 // 拷贝文件
bool CopyFile(const std::string srcPath,const std::string dstPath); bool CopyFile(const std::string srcPath, const std::string dstPath);
/** 拷贝目录 /** 拷贝目录
* *
...@@ -63,8 +71,8 @@ bool CopyFile(const std::string srcPath,const std::string dstPath); ...@@ -63,8 +71,8 @@ bool CopyFile(const std::string srcPath,const std::string dstPath);
1.第一个参数的最后不能加”/” 1.第一个参数的最后不能加”/”
2.不能拷贝隐藏文件 2.不能拷贝隐藏文件
*/ */
bool CopyDirectories(std::string srcPath,const std::string dstPath); bool CopyDirectories(std::string srcPath, const std::string dstPath);
} } // namespace migraphxSamples
#endif #endif
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
#include <map> #include <map>
#include <thread> #include <thread>
#include <mutex> #include <mutex>
#if (defined WIN32 || defined _WIN32) #if(defined WIN32 || defined _WIN32)
#include <Windows.h> #include <Windows.h>
#else #else
#include <sys/time.h> #include <sys/time.h>
...@@ -16,13 +16,13 @@ ...@@ -16,13 +16,13 @@
using namespace std; using namespace std;
/** 简易日志 /** 简易日志
* *
* 不依赖于其他第三方库,只需要包含一个头文件就可以使用。提供了4种日志级别,包括INFO,DEBUG,WARN和ERROR。 * 不依赖于其他第三方库,只需要包含一个头文件就可以使用。提供了4种日志级别,包括INFO,DEBUG,WARN和ERROR。
* *
* 示例1: * 示例1:
// 初始化日志,在./Log/目录下创建两个日志文件log1.log和log2.log(注意:目录./Log/需要存在,否则日志创建失败) //
初始化日志,在./Log/目录下创建两个日志文件log1.log和log2.log(注意:目录./Log/需要存在,否则日志创建失败)
LogManager::GetInstance()->Initialize("./Log/","log1"); LogManager::GetInstance()->Initialize("./Log/","log1");
LogManager::GetInstance()->Initialize("./Log/","log2"); LogManager::GetInstance()->Initialize("./Log/","log2");
...@@ -50,44 +50,43 @@ using namespace std; ...@@ -50,44 +50,43 @@ using namespace std;
class LogManager class LogManager
{ {
private: private:
LogManager(){} LogManager() {}
public: public:
~LogManager(){} ~LogManager() {}
inline void Initialize(const string &parentPath,const string &logName) inline void Initialize(const string& parentPath, const string& logName)
{ {
// 日志名为空表示输出到控制台 // 日志名为空表示输出到控制台
if(logName.size()==0) if(logName.size() == 0)
return; return;
// 查找该日志文件,如果没有则创建 // 查找该日志文件,如果没有则创建
std::map<string, FILE*>::const_iterator iter = logMap.find(logName); std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
if (iter == logMap.end()) if(iter == logMap.end())
{ {
string pathOfLog = parentPath+ logName + ".log"; string pathOfLog = parentPath + logName + ".log";
FILE *logFile = fopen(pathOfLog.c_str(), "a"); // w:覆盖原有文件,a:追加 FILE* logFile = fopen(pathOfLog.c_str(), "a"); // w:覆盖原有文件,a:追加
if(logFile!=NULL) if(logFile != NULL)
{ {
logMap.insert(std::make_pair(logName, logFile)); logMap.insert(std::make_pair(logName, logFile));
} }
} }
} }
inline FILE* GetLogFile(const string &logName) inline FILE* GetLogFile(const string& logName)
{ {
std::map<string, FILE*>::const_iterator iter=logMap.find(logName); std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
if(iter==logMap.end()) if(iter == logMap.end())
{ {
return NULL; return NULL;
} }
return (*iter).second; return (*iter).second;
} }
inline void Close(const string &logName) inline void Close(const string& logName)
{ {
std::map<string, FILE*>::const_iterator iter=logMap.find(logName); std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
if(iter==logMap.end()) if(iter == logMap.end())
{ {
return; return;
} }
...@@ -95,10 +94,7 @@ public: ...@@ -95,10 +94,7 @@ public:
fclose((*iter).second); fclose((*iter).second);
logMap.erase(iter); logMap.erase(iter);
} }
inline std::mutex &GetLogMutex() inline std::mutex& GetLogMutex() { return logMutex; }
{
return logMutex;
}
// Singleton // Singleton
static LogManager* GetInstance() static LogManager* GetInstance()
...@@ -106,17 +102,18 @@ public: ...@@ -106,17 +102,18 @@ public:
static LogManager logManager; static LogManager logManager;
return &logManager; return &logManager;
} }
private:
private:
std::map<string, FILE*> logMap; std::map<string, FILE*> logMap;
std::mutex logMutex; std::mutex logMutex;
}; };
#ifdef LOG_MUTEX #ifdef LOG_MUTEX
#define LOCK LogManager::GetInstance()->GetLogMutex().lock() #define LOCK LogManager::GetInstance()->GetLogMutex().lock()
#define UNLOCK LogManager::GetInstance()->GetLogMutex().unlock() #define UNLOCK LogManager::GetInstance()->GetLogMutex().unlock()
#else #else
#define LOCK #define LOCK
#define UNLOCK #define UNLOCK
#endif #endif
// log time // log time
...@@ -131,53 +128,53 @@ typedef struct _LogTime ...@@ -131,53 +128,53 @@ typedef struct _LogTime
string millisecond; // ms string millisecond; // ms
string microsecond; // us string microsecond; // us
string weekDay; string weekDay;
}LogTime; } LogTime;
inline LogTime GetTime() inline LogTime GetTime()
{ {
LogTime currentTime; LogTime currentTime;
#if (defined WIN32 || defined _WIN32) #if(defined WIN32 || defined _WIN32)
SYSTEMTIME systemTime; SYSTEMTIME systemTime;
GetLocalTime(&systemTime); GetLocalTime(&systemTime);
char temp[8] = { 0 }; char temp[8] = {0};
sprintf(temp, "%04d", systemTime.wYear); sprintf(temp, "%04d", systemTime.wYear);
currentTime.year=string(temp); currentTime.year = string(temp);
sprintf(temp, "%02d", systemTime.wMonth); sprintf(temp, "%02d", systemTime.wMonth);
currentTime.month=string(temp); currentTime.month = string(temp);
sprintf(temp, "%02d", systemTime.wDay); sprintf(temp, "%02d", systemTime.wDay);
currentTime.day=string(temp); currentTime.day = string(temp);
sprintf(temp, "%02d", systemTime.wHour); sprintf(temp, "%02d", systemTime.wHour);
currentTime.hour=string(temp); currentTime.hour = string(temp);
sprintf(temp, "%02d", systemTime.wMinute); sprintf(temp, "%02d", systemTime.wMinute);
currentTime.minute=string(temp); currentTime.minute = string(temp);
sprintf(temp, "%02d", systemTime.wSecond); sprintf(temp, "%02d", systemTime.wSecond);
currentTime.second=string(temp); currentTime.second = string(temp);
sprintf(temp, "%03d", systemTime.wMilliseconds); sprintf(temp, "%03d", systemTime.wMilliseconds);
currentTime.millisecond=string(temp); currentTime.millisecond = string(temp);
sprintf(temp, "%d", systemTime.wDayOfWeek); sprintf(temp, "%d", systemTime.wDayOfWeek);
currentTime.weekDay=string(temp); currentTime.weekDay = string(temp);
#else #else
struct timeval tv; struct timeval tv;
struct tm *p; struct tm* p;
gettimeofday(&tv, NULL); gettimeofday(&tv, NULL);
p = localtime(&tv.tv_sec); p = localtime(&tv.tv_sec);
char temp[8]={0}; char temp[8] = {0};
sprintf(temp,"%04d",1900+p->tm_year); sprintf(temp, "%04d", 1900 + p->tm_year);
currentTime.year=string(temp); currentTime.year = string(temp);
sprintf(temp,"%02d",1+p->tm_mon); sprintf(temp, "%02d", 1 + p->tm_mon);
currentTime.month=string(temp); currentTime.month = string(temp);
sprintf(temp,"%02d",p->tm_mday); sprintf(temp, "%02d", p->tm_mday);
currentTime.day=string(temp); currentTime.day = string(temp);
sprintf(temp,"%02d",p->tm_hour); sprintf(temp, "%02d", p->tm_hour);
currentTime.hour=string(temp); currentTime.hour = string(temp);
sprintf(temp,"%02d",p->tm_min); sprintf(temp, "%02d", p->tm_min);
currentTime.minute=string(temp); currentTime.minute = string(temp);
sprintf(temp,"%02d",p->tm_sec); sprintf(temp, "%02d", p->tm_sec);
currentTime.second=string(temp); currentTime.second = string(temp);
sprintf(temp,"%03d",(int)(tv.tv_usec/1000)); sprintf(temp, "%03d", (int)(tv.tv_usec / 1000));
currentTime.millisecond = string(temp); currentTime.millisecond = string(temp);
sprintf(temp, "%03d", (int)(tv.tv_usec % 1000)); sprintf(temp, "%03d", (int)(tv.tv_usec % 1000));
currentTime.microsecond = string(temp); currentTime.microsecond = string(temp);
...@@ -188,60 +185,82 @@ inline LogTime GetTime() ...@@ -188,60 +185,82 @@ inline LogTime GetTime()
} }
#define LOG_TIME(logFile) \ #define LOG_TIME(logFile) \
do\ do \
{\ { \
LogTime currentTime=GetTime(); \ LogTime currentTime = GetTime(); \
fprintf(((logFile == NULL) ? stdout : logFile), "%s-%s-%s %s:%s:%s.%s\t",currentTime.year.c_str(),currentTime.month.c_str(),currentTime.day.c_str(),currentTime.hour.c_str(),currentTime.minute.c_str(),currentTime.second.c_str(),currentTime.millisecond.c_str()); \ fprintf(((logFile == NULL) ? stdout : logFile), \
}while (0) "%s-%s-%s %s:%s:%s.%s\t", \
currentTime.year.c_str(), \
currentTime.month.c_str(), \
#define LOG_INFO(logFile,logInfo, ...) \ currentTime.day.c_str(), \
do\ currentTime.hour.c_str(), \
{\ currentTime.minute.c_str(), \
currentTime.second.c_str(), \
currentTime.millisecond.c_str()); \
} while(0)
#define LOG_INFO(logFile, logInfo, ...) \
do \
{ \
LOCK; \ LOCK; \
LOG_TIME(logFile); \ LOG_TIME(logFile); \
fprintf(((logFile == NULL) ? stdout : logFile), "INFO\t"); \ fprintf(((logFile == NULL) ? stdout : logFile), "INFO\t"); \
fprintf(((logFile == NULL) ? stdout : logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \ fprintf(((logFile == NULL) ? stdout : logFile), \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ## __VA_ARGS__); \ "[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \ fflush(logFile); \
UNLOCK; \ UNLOCK; \
} while (0) } while(0)
#define LOG_DEBUG(logFile,logInfo, ...) \ #define LOG_DEBUG(logFile, logInfo, ...) \
do\ do \
{\ { \
LOCK; \ LOCK; \
LOG_TIME(logFile);\ LOG_TIME(logFile); \
fprintf(((logFile==NULL)?stdout:logFile), "DEBUG\t"); \ fprintf(((logFile == NULL) ? stdout : logFile), "DEBUG\t"); \
fprintf(((logFile==NULL)?stdout:logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \ fprintf(((logFile == NULL) ? stdout : logFile), \
fprintf(((logFile==NULL)?stdout:logFile),logInfo, ## __VA_ARGS__); \ "[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \ fflush(logFile); \
UNLOCK; \ UNLOCK; \
} while (0) } while(0)
#define LOG_ERROR(logFile,logInfo, ...) \ #define LOG_ERROR(logFile, logInfo, ...) \
do\ do \
{\ { \
LOCK; \ LOCK; \
LOG_TIME(logFile);\ LOG_TIME(logFile); \
fprintf(((logFile==NULL)?stdout:logFile), "ERROR\t"); \ fprintf(((logFile == NULL) ? stdout : logFile), "ERROR\t"); \
fprintf(((logFile==NULL)?stdout:logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \ fprintf(((logFile == NULL) ? stdout : logFile), \
fprintf(((logFile==NULL)?stdout:logFile),logInfo, ## __VA_ARGS__); \ "[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \ fflush(logFile); \
UNLOCK; \ UNLOCK; \
} while (0) } while(0)
#define LOG_WARN(logFile,logInfo, ...) \ #define LOG_WARN(logFile, logInfo, ...) \
do\ do \
{\ { \
LOCK; \ LOCK; \
LOG_TIME(logFile);\ LOG_TIME(logFile); \
fprintf(((logFile==NULL)?stdout:logFile), "WARN\t"); \ fprintf(((logFile == NULL) ? stdout : logFile), "WARN\t"); \
fprintf(((logFile==NULL)?stdout:logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \ fprintf(((logFile == NULL) ? stdout : logFile), \
fprintf(((logFile==NULL)?stdout:logFile),logInfo, ## __VA_ARGS__); \ "[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \ fflush(logFile); \
UNLOCK; \ UNLOCK; \
} while (0) } while(0)
#endif // __SIMPLE_LOG_H__ #endif // __SIMPLE_LOG_H__
...@@ -15,7 +15,7 @@ int main() ...@@ -15,7 +15,7 @@ int main()
vlpr.Initialize(initParamOfDB, initParamOfSVTR); vlpr.Initialize(initParamOfDB, initParamOfSVTR);
// 读取测试图片 // 读取测试图片
cv:: Mat Image=cv::imread("../Resource/Images/vlpr.jpg", 1); cv::Mat Image = cv::imread("../Resource/Images/vlpr.jpg", 1);
// 推理 // 推理
std::vector<std::string> recTexts; std::vector<std::string> recTexts;
...@@ -23,7 +23,7 @@ int main() ...@@ -23,7 +23,7 @@ int main()
vlpr.Infer(Image, recTexts, recTextScores); vlpr.Infer(Image, recTexts, recTextScores);
// 打印结果 // 打印结果
for (int i = 0; i < recTexts.size(); i++) for(int i = 0; i < recTexts.size(); i++)
{ {
printf("VLPR Result:%s\n", recTexts[i].c_str()); printf("VLPR Result:%s\n", recTexts[i].c_str());
} }
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment