Commit 441457e7 authored by liucong's avatar liucong
Browse files

精简代码

parent 62415db5
#include <Crnn.h>
#include <migraphx/onnx.hpp>
#include <migraphx/gpu/target.hpp>
#include <migraphx/gpu/hip.hpp>
#include <migraphx/generate.hpp>
#include <migraphx/quantization.hpp>
#include <migraphx/reshape2.hpp>
#include <opencv2/dnn.hpp>
#include <CommonUtility.h>
#include <Filesystem.h>
#include <SimpleLog.h>
using namespace cv::dnn;
namespace migraphxSamples
{
Crnn::Crnn():logFile(NULL)
Crnn::Crnn()
{
}
......@@ -29,24 +24,28 @@ Crnn::~Crnn()
ErrorCode Crnn::Initialize(InitializationParameterOfOcr initializationParameterOfOcr, bool dynamic)
{
// 初始化(获取日志文件,加载配置文件等)
ErrorCode errorCode = DoCommonInitialization(initializationParameterOfOcr);
if(errorCode!=SUCCESS)
// 读取配置文件
std::string configFilePath=initializationParameterOfOcr.configFilePath;
if(Exists(configFilePath)==false)
{
LOG_ERROR(logFile,"fail to DoCommonInitialization\n");
return errorCode;
LOG_ERROR(stdout, "no configuration file!\n");
return CONFIG_FILE_NOT_EXIST;
}
LOG_INFO(logFile,"succeed to DoCommonInitialization\n");
if(!configurationFile.open(configFilePath, cv::FileStorage::READ))
{
LOG_ERROR(stdout, "fail to open configuration file\n");
return FAIL_TO_OPEN_CONFIG_FILE;
}
LOG_INFO(stdout, "succeed to open configuration file\n");
// 获取配置文件参数
std::string modelPath;
FileNode netNode = configurationFile["CrnnDynamic"];
modelPath = initializationParameter.parentPath + (string)netNode["ModelPath"];
cv::FileNode netNode = configurationFile["CrnnDynamic"];
std::string modelPath=(std::string)netNode["ModelPath"];
// 加载模型
if(Exists(modelPath)==false)
{
LOG_ERROR(logFile,"%s not exist!\n",modelPath.c_str());
LOG_ERROR(stdout,"%s not exist!\n",modelPath.c_str());
return MODEL_NOT_EXIST;
}
......@@ -56,17 +55,21 @@ ErrorCode Crnn::Initialize(InitializationParameterOfOcr initializationParameterO
onnx_options.map_input_dims["input"]={1,1,32,512};
net = migraphx::parse_onnx(modelPath, onnx_options);
LOG_INFO(logFile,"succeed to load model: %s\n",GetFileName(modelPath).c_str());
LOG_INFO(stdout,"succeed to load model: %s\n",GetFileName(modelPath).c_str());
// 获取模型输入属性
std::pair<std::string, migraphx::shape> inputAttribute=*(net.get_parameter_shapes().begin());
inputName=inputAttribute.first;
inputShape=inputAttribute.second;
inputSize=cv::Size(inputShape.lens()[3],inputShape.lens()[2]);
std::unordered_map<std::string, migraphx::shape> inputMap=net.get_parameter_shapes();
inputName=inputMap.begin()->first;
inputShape=inputMap.begin()->second;
int N=inputShape.lens()[0];
int C=inputShape.lens()[1];
int H=inputShape.lens()[2];
int W=inputShape.lens()[3];
inputSize=cv::Size(W,H);
// log输出日志信息
LOG_INFO(logFile,"InputMaxSize:%dx%d\n",inputSize.width,inputSize.height);
LOG_INFO(logFile,"InputName:%s\n",inputName.c_str());
LOG_INFO(stdout,"InputMaxSize:%dx%d\n",inputSize.width,inputSize.height);
LOG_INFO(stdout,"InputName:%s\n",inputName.c_str());
}
else
{
......@@ -74,17 +77,21 @@ ErrorCode Crnn::Initialize(InitializationParameterOfOcr initializationParameterO
onnx_options.map_input_dims["input"]={1,1,32,100};
net = migraphx::parse_onnx(modelPath, onnx_options);
LOG_INFO(logFile,"succeed to load model: %s\n",GetFileName(modelPath).c_str());
LOG_INFO(stdout,"succeed to load model: %s\n",GetFileName(modelPath).c_str());
// 获取模型输入属性
std::pair<std::string, migraphx::shape> inputAttribute=*(net.get_parameter_shapes().begin());
inputName=inputAttribute.first;
inputShape=inputAttribute.second;
inputSize=cv::Size(inputShape.lens()[3],inputShape.lens()[2]);
std::unordered_map<std::string, migraphx::shape> inputMap=net.get_parameter_shapes();
inputName=inputMap.begin()->first;
inputShape=inputMap.begin()->second;
int N=inputShape.lens()[0];
int C=inputShape.lens()[1];
int H=inputShape.lens()[2];
int W=inputShape.lens()[3];
inputSize=cv::Size(W,H);
// log输出日志信息
LOG_INFO(logFile,"InputSize:%dx%d\n",inputSize.width,inputSize.height);
LOG_INFO(logFile,"InputName:%s\n",inputName.c_str());
LOG_INFO(stdout,"InputSize:%dx%d\n",inputSize.width,inputSize.height);
LOG_INFO(stdout,"InputName:%s\n",inputName.c_str());
}
// 设置模型为GPU模式
......@@ -93,14 +100,14 @@ ErrorCode Crnn::Initialize(InitializationParameterOfOcr initializationParameterO
// 编译模型
migraphx::compile_options options;
options.device_id=0; // 设置GPU设备,默认为0号设备
options.offload_copy=true; // 设置offload_copy
options.offload_copy=true;
net.compile(gpuTarget,options);
LOG_INFO(logFile,"succeed to compile model: %s\n",GetFileName(modelPath).c_str());
LOG_INFO(stdout,"succeed to compile model: %s\n",GetFileName(modelPath).c_str());
// Run once by itself
migraphx::parameter_map inputData;
inputData[inputName]=migraphx::generate_argument(inputShape);
net.eval(inputData);
// warm up
std::unordered_map<std::string, migraphx::argument> inputData;
inputData[inputName]=migraphx::argument{inputShape};
net.eval(inputData);
return SUCCESS;
}
......@@ -109,7 +116,7 @@ ErrorCode Crnn::Infer(const cv::Mat &srcImage, std::vector<char> &resultsChar, b
{
if(srcImage.empty() || srcImage.type()!=CV_8UC3)
{
LOG_ERROR(logFile, "image error!\n");
LOG_ERROR(stdout, "image error!\n");
return IMAGE_ERROR;
}
......@@ -135,8 +142,8 @@ ErrorCode Crnn::Infer(const cv::Mat &srcImage, std::vector<char> &resultsChar, b
*((float*)inputBlob.data+i) = ((*((float*)inputBlob.data+i))/255.f - 0.5)/0.5;
}
// 输入数据
migraphx::parameter_map inputData;
// 创建输入数据
std::unordered_map<std::string, migraphx::argument> inputData;
if(dynamic)
{
std::vector<std::size_t> dynamicShape = {1, 1, 32, width};
......@@ -167,7 +174,7 @@ ErrorCode Crnn::Infer(const cv::Mat &srcImage, std::vector<char> &resultsChar, b
//获取字符索引序列
for(uint i = 0; i < outs[0].size[0]; i++)
{
cv::Mat scores = Mat(1,outs[0].size[2],CV_32F,outs[0].ptr<float>(i));
cv::Mat scores = cv::Mat(1,outs[0].size[2],CV_32F,outs[0].ptr<float>(i));
cv::Point charIdPoint;
double maxCharScore;
cv::minMaxLoc(scores, 0, &maxCharScore, 0, &charIdPoint);
......@@ -196,40 +203,4 @@ ErrorCode Crnn::Infer(const cv::Mat &srcImage, std::vector<char> &resultsChar, b
return SUCCESS;
}
ErrorCode Crnn::DoCommonInitialization(InitializationParameterOfOcr initializationParameterOfOcr)
{
initializationParameter=initializationParameterOfOcr;
// 获取日志文件
logFile=LogManager::GetInstance()->GetLogFile(initializationParameter.logName);
// 加载配置文件
std::string configFilePath=initializationParameter.configFilePath;
if(!Exists(configFilePath))
{
LOG_ERROR(logFile, "no configuration file!\n");
return CONFIG_FILE_NOT_EXIST;
}
if(!configurationFile.open(configFilePath, FileStorage::READ))
{
LOG_ERROR(logFile, "fail to open configuration file\n");
return FAIL_TO_OPEN_CONFIG_FILE;
}
LOG_INFO(logFile, "succeed to open configuration file\n");
// 修改父路径
std::string &parentPath = initializationParameter.parentPath;
if (!parentPath.empty())
{
if(!IsPathSeparator(parentPath[parentPath.size() - 1]))
{
parentPath+=PATH_SEPARATOR;
}
}
return SUCCESS;
}
}
#ifndef __OCR_CRNN_H__
#define __OCR_CRNN_H__
#include <string>
#include <migraphx/program.hpp>
#include <opencv2/opencv.hpp>
#include <CommonDefinition.h>
using namespace std;
using namespace cv;
using namespace migraphx;
#include <CommonDefinition.h>
namespace migraphxSamples
{
......@@ -24,19 +19,12 @@ public:
ErrorCode Infer(const cv::Mat &srcImage, std::vector<char> &resultsChar, bool raw, bool dynamic);
ErrorCode Reshape(const cv::Mat &srcImage);
private:
ErrorCode DoCommonInitialization(InitializationParameterOfOcr initializationParameterOfOcr);
private:
cv::FileStorage configurationFile;
InitializationParameterOfOcr initializationParameter;
FILE *logFile;
migraphx::program net;
cv::Size inputSize;
string inputName;
std::string inputName;
migraphx::shape inputShape;
};
......
#include <Sample.h>
#include <opencv2/dnn.hpp>
#include <SimpleLog.h>
#include <Filesystem.h>
#include <Crnn.h>
#include <fstream>
using namespace std;
using namespace cv;
using namespace cv::dnn;
using namespace migraphx;
using namespace migraphxSamples;
void Sample_Crnn()
{
// 创建CRNN文本识别
Crnn crnn;
InitializationParameterOfOcr initParamOfOcrCRNN;
initParamOfOcrCRNN.parentPath = "";
initParamOfOcrCRNN.configFilePath = CONFIG_FILE;
initParamOfOcrCRNN.logName = "";
ErrorCode errorCode=crnn.Initialize(initParamOfOcrCRNN, false);
if(errorCode!=SUCCESS)
{
LOG_ERROR(stdout, "fail to initialize crnn!\n");
exit(-1);
}
LOG_INFO(stdout, "succeed to initialize crnn\n");
// 读取测试图片
cv:: Mat srcImage=cv::imread("../Resource/Images/text.jpg", 1);
// 推理
std::vector<char> resultRaw;
std::vector<char> resultSim;
double time1 = getTickCount();
crnn.Infer(srcImage,resultRaw, true, false);
crnn.Infer(srcImage,resultSim, false, false);
double time2 = getTickCount();
double elapsedTime = (time2 - time1)*1000*0.5 / getTickFrequency();
LOG_INFO(stdout, "inference time:%f ms\n", elapsedTime);
// 获取推理结果
LOG_INFO(stdout,"========== Ocr Results ==========\n");
for(int i = 0; i < resultRaw.size(); i++)
{
std::cout << resultRaw.at(i);
}
std::cout << " => ";
for(int i = 0; i < resultSim.size(); i++)
{
std::cout << resultSim.at(i);
}
std::cout << std::endl;
}
void Sample_Crnn_Dynamic()
{
// 创建CRNN文本识别
Crnn crnn;
InitializationParameterOfOcr initParamOfOcrCRNN;
initParamOfOcrCRNN.parentPath = "";
initParamOfOcrCRNN.configFilePath = CONFIG_FILE;
initParamOfOcrCRNN.logName = "";
ErrorCode errorCode=crnn.Initialize(initParamOfOcrCRNN, true);
if(errorCode!=SUCCESS)
{
LOG_ERROR(stdout, "fail to initialize crnn!\n");
exit(-1);
}
LOG_INFO(stdout, "succeed to initialize crnn\n");
// 读取测试图片
std::vector<cv::Mat> srcImages;
cv::String folder = "../Resource/Images/CrnnDynamicPic";
std::vector<cv::String> imagePathList;
cv::glob(folder,imagePathList);
for (int i = 0; i < imagePathList.size(); ++i)
{
cv:: Mat srcImage=cv::imread(imagePathList[i], 1);
srcImages.push_back(srcImage);
}
// 获取推理结果
LOG_INFO(stdout,"========== Ocr Results ==========\n");
for(int i=0; i<srcImages.size(); ++i)
{
std::vector<char> resultSim;
crnn.Infer(srcImages[i],resultSim, false, true);
for(int i = 0; i < resultSim.size(); i++)
{
std::cout << resultSim.at(i);
}
std::cout << std::endl;
}
}
\ No newline at end of file
// 示例程序
#ifndef __SAMPLE_H__
#define __SAMPLE_H__
// Crnn sample
void Sample_Crnn();
// Crnn Dynamic sample
void Sample_Crnn_Dynamic();
#endif
\ No newline at end of file
// 常用数据类型和宏定义
// 常用定义
#ifndef __COMMON_DEFINITION_H__
#define __COMMON_DEFINITION_H__
#include <string>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
namespace migraphxSamples
{
......@@ -21,20 +17,7 @@ namespace migraphxSamples
#define CONFIG_FILE "../Resource/Configuration.xml"
typedef struct __Time
{
string year;
string month;
string day;
string hour;
string minute;
string second;
string millisecond; // ms
string microsecond; // us
string weekDay;
}_Time;
typedef enum _ErrorCode
typedef enum _ErrorCode
{
SUCCESS=0, // 0
MODEL_NOT_EXIST, // 模型不存在
......@@ -44,7 +27,7 @@ typedef enum _ErrorCode
IMAGE_ERROR, // 图像错误
}ErrorCode;
typedef struct _ResultOfPrediction
typedef struct _ResultOfPrediction
{
float confidence;
int label;
......@@ -52,27 +35,31 @@ typedef struct _ResultOfPrediction
}ResultOfPrediction;
typedef struct _ResultOfDetection
typedef struct _ResultOfDetection
{
Rect boundingBox;
cv::Rect boundingBox;
float confidence;
int classID;
string className;
std::string className;
bool exist;
_ResultOfDetection():confidence(0.0f),classID(0),exist(true){}
}ResultOfDetection;
typedef struct _InitializationParameterOfDetector
typedef struct _InitializationParameterOfDetector
{
std::string parentPath;
std::string configFilePath;
cv::Size inputSize;
std::string logName;
}InitializationParameterOfDetector;
typedef struct _InitializationParameterOfDetector InitializationParameterOfClassifier;
typedef struct _InitializationParameterOfDetector InitializationParameterOfSuperresolution;
typedef struct _InitializationParameterOfDetector InitializationParameterOfSegmentation;
typedef struct _InitializationParameterOfDetector InitializationParameterOfNLP;
typedef struct _InitializationParameterOfDetector InitializationParameterOfOcr;
typedef struct _InitializationParameterOfDetector InitializationParameterOfDB;
typedef struct _InitializationParameterOfDetector InitializationParameterOfSVTR;
}
......
#include <CommonUtility.h>
#include <assert.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
#include <sstream>
#include <vector>
#ifdef _WIN32
#include <io.h>
#include <direct.h>
#include <Windows.h>
#else
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/time.h>
#endif
#include <SimpleLog.h>
namespace migraphxSamples
{
_Time GetCurrentTime3()
{
_Time currentTime;
#if (defined WIN32 || defined _WIN32)
SYSTEMTIME systemTime;
GetLocalTime(&systemTime);
char temp[8] = { 0 };
sprintf(temp, "%04d", systemTime.wYear);
currentTime.year=string(temp);
sprintf(temp, "%02d", systemTime.wMonth);
currentTime.month=string(temp);
sprintf(temp, "%02d", systemTime.wDay);
currentTime.day=string(temp);
sprintf(temp, "%02d", systemTime.wHour);
currentTime.hour=string(temp);
sprintf(temp, "%02d", systemTime.wMinute);
currentTime.minute=string(temp);
sprintf(temp, "%02d", systemTime.wSecond);
currentTime.second=string(temp);
sprintf(temp, "%03d", systemTime.wMilliseconds);
currentTime.millisecond=string(temp);
sprintf(temp, "%d", systemTime.wDayOfWeek);
currentTime.weekDay=string(temp);
#else
struct timeval tv;
struct tm *p;
gettimeofday(&tv, NULL);
p = localtime(&tv.tv_sec);
char temp[8]={0};
sprintf(temp,"%04d",1900+p->tm_year);
currentTime.year=string(temp);
sprintf(temp,"%02d",1+p->tm_mon);
currentTime.month=string(temp);
sprintf(temp,"%02d",p->tm_mday);
currentTime.day=string(temp);
sprintf(temp,"%02d",p->tm_hour);
currentTime.hour=string(temp);
sprintf(temp,"%02d",p->tm_min);
currentTime.minute=string(temp);
sprintf(temp,"%02d",p->tm_sec);
currentTime.second=string(temp);
sprintf(temp,"%03d",tv.tv_usec/1000);
currentTime.millisecond = string(temp);
sprintf(temp, "%03d", tv.tv_usec % 1000);
currentTime.microsecond = string(temp);
sprintf(temp, "%d", p->tm_wday);
currentTime.weekDay = string(temp);
#endif
return currentTime;
}
std::vector<std::string> SplitString(std::string str, std::string separator)
{
std::string::size_type pos;
std::vector<std::string> result;
str+=separator;//扩展字符串以方便操作
int size=str.size();
for(int i=0; i<size; i++)
{
pos=str.find(separator,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+separator.size()-1;
}
}
return result;
}
bool CompareConfidence(const ResultOfDetection &L,const ResultOfDetection &R)
{
return L.confidence > R.confidence;
......@@ -109,7 +13,7 @@ bool CompareArea(const ResultOfDetection &L,const ResultOfDetection &R)
return L.boundingBox.area() > R.boundingBox.area();
}
void NMS(vector<ResultOfDetection> &detections, float IOUThreshold)
void NMS(std::vector<ResultOfDetection> &detections, float IOUThreshold)
{
// sort
std::sort(detections.begin(), detections.end(), CompareConfidence);
......
......@@ -3,23 +3,16 @@
#ifndef __COMMON_UTILITY_H__
#define __COMMON_UTILITY_H__
#include <mutex>
#include <string>
#include <vector>
#include <CommonDefinition.h>
using namespace std;
namespace migraphxSamples
{
// 分割字符串
std::vector<std::string> SplitString(std::string str,std::string separator);
// 排序规则: 按照置信度或者按照面积排序
bool CompareConfidence(const ResultOfDetection &L,const ResultOfDetection &R);
bool CompareArea(const ResultOfDetection &L,const ResultOfDetection &R);
// 非极大抑制
void NMS(std::vector<ResultOfDetection> &detections, float IOUThreshold);
}
......
......@@ -11,12 +11,7 @@
#include <unistd.h>
#include <dirent.h>
#endif
#include <CommonUtility.h>
#include <opencv2/opencv.hpp>
#include <SimpleLog.h>
using namespace cv;
// 路径分隔符(Linux:‘/’,Windows:’\\’)
#ifdef _WIN32
#define PATH_SEPARATOR '\\'
......@@ -24,9 +19,31 @@ using namespace cv;
#define PATH_SEPARATOR '/'
#endif
using namespace std;
namespace migraphxSamples
{
static std::vector<std::string> SplitString(std::string str, std::string separator)
{
std::string::size_type pos;
std::vector<std::string> result;
str+=separator;//扩展字符串以方便操作
int size=str.size();
for(int i=0; i<size; i++)
{
pos=str.find(separator,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+separator.size()-1;
}
}
return result;
}
#if defined _WIN32 || defined WINCE
const char dir_separators[] = "/\\";
......@@ -293,7 +310,7 @@ namespace migraphxSamples
}
else
{
LOG_INFO(stdout, "could not open directory: %s", directory.c_str());
printf("could not open directory: %s", directory.c_str());
}
}
......@@ -390,7 +407,7 @@ namespace migraphxSamples
#endif
if (!result)
{
LOG_INFO(stdout, "can't remove directory: %s\n", path.c_str());
printf("can't remove directory: %s\n", path.c_str());
}
}
else
......@@ -402,7 +419,7 @@ namespace migraphxSamples
#endif
if (!result)
{
LOG_INFO(stdout, "can't remove file: %s\n", path.c_str());
printf("can't remove file: %s\n", path.c_str());
}
}
}
......@@ -438,7 +455,7 @@ namespace migraphxSamples
{
RemoveAll(path);
++numberOfFiles;
LOG_INFO(stdout, "%s deleted! number of deleted files:%d\n", path.c_str(), numberOfFiles);
printf("%s deleted! number of deleted files:%d\n", path.c_str(), numberOfFiles);
}
}
......@@ -452,7 +469,7 @@ namespace migraphxSamples
}
else
{
LOG_INFO(stdout, "could not open directory: %s", directory.c_str());
printf("could not open directory: %s", directory.c_str());
}
// ����RemoveAllɾ��Ŀ¼
......@@ -592,17 +609,17 @@ namespace migraphxSamples
if(!srcFile.is_open())
{
LOG_ERROR(stdout,"can not open %s\n",srcPath.c_str());
printf("can not open %s\n",srcPath.c_str());
return false;
}
if(!dstFile.is_open())
{
LOG_ERROR(stdout, "can not open %s\n", dstPath.c_str());
printf("can not open %s\n", dstPath.c_str());
return false;
}
if(srcPath==dstPath)
{
LOG_ERROR(stdout, "src can not be same with dst\n");
printf("src can not be same with dst\n");
return false;
}
char buffer[2048];
......@@ -622,7 +639,7 @@ namespace migraphxSamples
{
if(srcPath==dstPath)
{
LOG_ERROR(stdout, "src can not be same with dst\n");
printf("src can not be same with dst\n");
return false;
}
......@@ -662,9 +679,9 @@ namespace migraphxSamples
// process
double process = (1.0*(i + 1) / fileNameList.size()) * 100;
LOG_INFO(stdout, "%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
printf("%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
}
LOG_INFO(stdout, "all done!(the number of files:%d)\n", fileNameList.size());
printf("all done!(the number of files:%d)\n", fileNameList.size());
return true;
......
......@@ -3,10 +3,8 @@
#ifndef __FILE_SYSTEM_H__
#define __FILE_SYSTEM_H__
#include <vector>
#include <string>
using namespace std;
#include <vector>
namespace migraphxSamples
{
......@@ -21,7 +19,7 @@ bool IsDirectory(const std::string &path);
bool IsPathSeparator(char c);
// 路径拼接
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);
......@@ -49,14 +47,13 @@ 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/
*/
string GetFileName(const std::string &path); // 1.txt
string GetFileName_NoExtension(const std::string &path); // 1
string GetExtension(const std::string &path);// .txt
string GetParentPath(const std::string &path);// D:/1/
std::string GetFileName(const std::string &path);
std::string GetFileName_NoExtension(const std::string &path);
std::string GetExtension(const std::string &path);
std::string GetParentPath(const std::string &path);
// 拷贝文件:CopyFile("D:/1.txt","D:/2.txt");将1.txt拷贝为2.txt
// 拷贝文件
bool CopyFile(const std::string srcPath,const std::string dstPath);
/** 拷贝目录
......
......@@ -19,7 +19,7 @@ using namespace std;
/** 简易日志
*
* 轻量级日志系统,不依赖于其他第三方库,只需要包含一个头文件就可以使用。提供了4种日志级别,包括INFO,DEBUG,WARN和ERROR。
* 不依赖于其他第三方库,只需要包含一个头文件就可以使用。提供了4种日志级别,包括INFO,DEBUG,WARN和ERROR。
*
* 示例1:
// 初始化日志,在./Log/目录下创建两个日志文件log1.log和log2.log(注意:目录./Log/需要存在,否则日志创建失败)
......
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Sample.h>
#include <Crnn.h>
#include <SimpleLog.h>
#include <Filesystem.h>
void MIGraphXSamplesUsage(char* programName)
{
printf("Usage : %s <index> \n", programName);
printf("index:\n");
printf("\t a) Crnn sample.\n");
printf("\t b) Crnn Dynamic sample.\n");
printf("\t 0) Crnn sample.\n");
printf("\t 1) Crnn Dynamic sample.\n");
}
void Sample_Crnn();
void Sample_Crnn_Dynamic();
int main(int argc, char *argv[])
{
if (argc < 2 || argc > 2)
......@@ -25,12 +30,12 @@ int main(int argc, char *argv[])
}
switch (*argv[1])
{
case 'a':
case '0':
{
Sample_Crnn();
break;
}
case 'b':
case '1':
{
Sample_Crnn_Dynamic();
break;
......@@ -42,4 +47,86 @@ int main(int argc, char *argv[])
}
}
return 0;
}
void Sample_Crnn()
{
// 创建CRNN文本识别
migraphxSamples::Crnn crnn;
migraphxSamples::InitializationParameterOfOcr initParamOfOcrCRNN;
initParamOfOcrCRNN.configFilePath = CONFIG_FILE;
migraphxSamples::ErrorCode errorCode=crnn.Initialize(initParamOfOcrCRNN, false);
if(errorCode!=migraphxSamples::SUCCESS)
{
LOG_ERROR(stdout, "fail to initialize crnn!\n");
exit(-1);
}
LOG_INFO(stdout, "succeed to initialize crnn\n");
// 读取测试图片
cv:: Mat srcImage=cv::imread("../Resource/Images/text.jpg", 1);
// 推理
std::vector<char> resultRaw;
std::vector<char> resultSim;
double time1 = cv::getTickCount();
crnn.Infer(srcImage,resultRaw, true, false);
crnn.Infer(srcImage,resultSim, false, false);
double time2 = cv::getTickCount();
double elapsedTime = (time2 - time1)*1000*0.5 / cv::getTickFrequency();
LOG_INFO(stdout, "inference time:%f ms\n", elapsedTime);
// 获取推理结果
LOG_INFO(stdout,"========== Ocr Results ==========\n");
for(int i = 0; i < resultRaw.size(); i++)
{
std::cout << resultRaw.at(i);
}
std::cout << " => ";
for(int i = 0; i < resultSim.size(); i++)
{
std::cout << resultSim.at(i);
}
std::cout << std::endl;
}
void Sample_Crnn_Dynamic()
{
// 创建CRNN文本识别
migraphxSamples::Crnn crnn;
migraphxSamples::InitializationParameterOfOcr initParamOfOcrCRNN;
initParamOfOcrCRNN.configFilePath = CONFIG_FILE;
migraphxSamples::ErrorCode errorCode=crnn.Initialize(initParamOfOcrCRNN, true);
if(errorCode!=migraphxSamples::SUCCESS)
{
LOG_ERROR(stdout, "fail to initialize crnn!\n");
exit(-1);
}
LOG_INFO(stdout, "succeed to initialize crnn\n");
// 读取测试图片
std::vector<cv::Mat> srcImages;
cv::String folder = "../Resource/Images/CrnnDynamicPic";
std::vector<cv::String> imagePathList;
cv::glob(folder,imagePathList);
for (int i = 0; i < imagePathList.size(); ++i)
{
cv:: Mat srcImage=cv::imread(imagePathList[i], 1);
srcImages.push_back(srcImage);
}
// 获取推理结果
LOG_INFO(stdout,"========== Ocr Results ==========\n");
for(int i=0; i<srcImages.size(); ++i)
{
std::vector<char> resultSim;
crnn.Infer(srcImages[i],resultSim, false, true);
for(int i = 0; i < resultSim.size(); i++)
{
std::cout << resultSim.at(i);
}
std::cout << std::endl;
}
}
\ No newline at end of file
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