Commit c7995096 authored by liucong's avatar liucong
Browse files

重新进行Cpp代码的格式化

parent 29410168
...@@ -9,25 +9,16 @@ ...@@ -9,25 +9,16 @@
namespace migraphxSamples namespace migraphxSamples
{ {
static float Sigmoid(float x) static float Sigmoid(float x) { return (1 / (1 + exp(-x))); }
{
return (1 / (1 + exp(-x)));
}
Unet::Unet() Unet::Unet() {}
{
} Unet::~Unet() { configurationFile.release(); }
Unet::~Unet()
{
configurationFile.release();
}
ErrorCode Unet::Initialize(InitializationParameterOfSegmentation initParamOfSegmentationUnet) ErrorCode Unet::Initialize(InitializationParameterOfSegmentation initParamOfSegmentationUnet)
{ {
// 读取配置文件 // 读取配置文件
std::string configFilePath=initParamOfSegmentationUnet.configFilePath; std::string configFilePath = initParamOfSegmentationUnet.configFilePath;
if(!Exists(configFilePath)) if(!Exists(configFilePath))
{ {
LOG_ERROR(stdout, "no configuration file!\n"); LOG_ERROR(stdout, "no configuration file!\n");
...@@ -42,57 +33,57 @@ ErrorCode Unet::Initialize(InitializationParameterOfSegmentation initParamOfSegm ...@@ -42,57 +33,57 @@ ErrorCode Unet::Initialize(InitializationParameterOfSegmentation initParamOfSegm
// 获取配置文件参数 // 获取配置文件参数
cv::FileNode netNode = configurationFile["Unet"]; cv::FileNode netNode = configurationFile["Unet"];
std::string modelPath=(std::string)netNode["ModelPath"]; std::string modelPath = (std::string)netNode["ModelPath"];
// 设置最大输入shape // 设置最大输入shape
migraphx::onnx_options onnx_options; migraphx::onnx_options onnx_options;
onnx_options.map_input_dims["inputs"]={1,3,256,256}; onnx_options.map_input_dims["inputs"] = {1, 3, 256, 256};
// 加载模型 // 加载模型
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;
} }
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);
// log输出日志信息 // log输出日志信息
LOG_INFO(stdout,"InputSize:%dx%d\n",inputSize.width,inputSize.height); LOG_INFO(stdout, "InputSize:%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 Unet::Segmentation(const cv::Mat &srcImage, cv::Mat &maskImage) ErrorCode Unet::Segmentation(const cv::Mat& srcImage, cv::Mat& maskImage)
{ {
if(srcImage.empty()||srcImage.type()!=CV_8UC3) if(srcImage.empty() || srcImage.type() != CV_8UC3)
{ {
LOG_ERROR(stdout, "image error!\n"); LOG_ERROR(stdout, "image error!\n");
return IMAGE_ERROR; return IMAGE_ERROR;
...@@ -100,34 +91,29 @@ ErrorCode Unet::Segmentation(const cv::Mat &srcImage, cv::Mat &maskImage) ...@@ -100,34 +91,29 @@ ErrorCode Unet::Segmentation(const cv::Mat &srcImage, cv::Mat &maskImage)
// 数据预处理并转换为NCHW格式 // 数据预处理并转换为NCHW格式
cv::Mat inputBlob; cv::Mat inputBlob;
cv::dnn::blobFromImage(srcImage, cv::dnn::blobFromImage(
inputBlob, srcImage, inputBlob, 1 / 255.0, inputSize, cv::Scalar(0, 0, 0), true, false);
1 / 255.0,
inputSize,
cv::Scalar(0, 0, 0),
true,
false);
// 创建输入数据 // 创建输入数据
std::unordered_map<std::string, migraphx::argument> inputData; std::unordered_map<std::string, migraphx::argument> inputData;
inputData[inputName]= migraphx::argument{inputShape, (float*)inputBlob.data}; inputData[inputName] = migraphx::argument{inputShape, (float*)inputBlob.data};
// 推理 // 推理
std::vector<migraphx::argument> results = net.eval(inputData); std::vector<migraphx::argument> results = net.eval(inputData);
// 获取输出节点的属性 // 获取输出节点的属性
migraphx::argument result = results[0]; // 获取第一个输出节点的数据 migraphx::argument result = results[0]; // 获取第一个输出节点的数据
migraphx::shape outputShape=result.get_shape(); // 输出节点的shape migraphx::shape outputShape = result.get_shape(); // 输出节点的shape
std::vector<std::size_t> outputSize=outputShape.lens(); // 每一维大小,维度顺序为(N,C,H,W) std::vector<std::size_t> outputSize = outputShape.lens(); // 每一维大小,维度顺序为(N,C,H,W)
int numberOfOutput=outputShape.elements(); // 输出节点元素的个数 int numberOfOutput = outputShape.elements(); // 输出节点元素的个数
float *data = (float *)result.data(); // 输出节点数据指针 float* data = (float*)result.data(); // 输出节点数据指针
// 计算sigmoid值 // 计算sigmoid值
int value_mask[numberOfOutput]; int value_mask[numberOfOutput];
for(int i=0; i<numberOfOutput; ++i) for(int i = 0; i < numberOfOutput; ++i)
{ {
float num = Sigmoid(data[i]); float num = Sigmoid(data[i]);
if (num > 0.996) if(num > 0.996)
{ {
value_mask[i] = 1; value_mask[i] = 1;
} }
...@@ -138,20 +124,18 @@ ErrorCode Unet::Segmentation(const cv::Mat &srcImage, cv::Mat &maskImage) ...@@ -138,20 +124,18 @@ ErrorCode Unet::Segmentation(const cv::Mat &srcImage, cv::Mat &maskImage)
} }
// 将对应的value_mask[]数组中的值按行依次赋值到outputImage对应位置处 // 将对应的value_mask[]数组中的值按行依次赋值到outputImage对应位置处
cv::Mat outputImage = cv::Mat_<int>(cv::Size(outputShape.lens()[3], outputShape.lens()[2]), CV_32S); cv::Mat outputImage =
for(int i=0;i<outputShape.lens()[2];++i) cv::Mat_<int>(cv::Size(outputShape.lens()[3], outputShape.lens()[2]), CV_32S);
for(int i = 0; i < outputShape.lens()[2]; ++i)
{ {
for(int j=0;j<outputShape.lens()[3];++j) for(int j = 0; j < outputShape.lens()[3]; ++j)
{ {
outputImage.at<int>(i,j)=value_mask[256*i+j]; outputImage.at<int>(i, j) = value_mask[256 * i + j];
} }
} }
outputImage.convertTo(maskImage, CV_8U, 255.0); outputImage.convertTo(maskImage, CV_8U, 255.0);
return SUCCESS; return SUCCESS;
} }
} // namespace migraphxSamples
}
...@@ -10,16 +10,16 @@ namespace migraphxSamples ...@@ -10,16 +10,16 @@ namespace migraphxSamples
class Unet class Unet
{ {
public: public:
Unet(); Unet();
~Unet(); ~Unet();
ErrorCode Initialize(InitializationParameterOfSegmentation initParamOfSegmentationUnet); ErrorCode Initialize(InitializationParameterOfSegmentation initParamOfSegmentationUnet);
ErrorCode Segmentation(const cv::Mat &srcImage, cv::Mat &maskImage); ErrorCode Segmentation(const cv::Mat& srcImage, cv::Mat& maskImage);
private: private:
cv::FileStorage configurationFile; cv::FileStorage configurationFile;
migraphx::program net; migraphx::program net;
...@@ -27,9 +27,8 @@ private: ...@@ -27,9 +27,8 @@ private:
std::string inputName; std::string inputName;
migraphx::shape inputShape; migraphx::shape inputShape;
float scale; float scale;
}; };
} } // namespace migraphxSamples
#endif #endif
...@@ -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,17 +43,16 @@ typedef struct _ResultOfDetection ...@@ -43,17 +43,16 @@ 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 _InitializationParameterOfSegmentation typedef struct _InitializationParameterOfSegmentation
{ {
std::string parentPath; std::string parentPath;
std::string configFilePath; std::string configFilePath;
}InitializationParameterOfSegmentation; } InitializationParameterOfSegmentation;
} } // namespace migraphxSamples
#endif #endif
...@@ -28,32 +28,32 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -28,32 +28,32 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
{ {
std::string::size_type pos; std::string::size_type pos;
std::vector<std::string> result; std::vector<std::string> result;
str+=separator;//扩展字符串以方便操作 str += separator; // 扩展字符串以方便操作
int size=str.size(); int size = str.size();
for(int i=0; i<size; i++) for(int i = 0; i < size; i++)
{ {
pos=str.find(separator,i); pos = str.find(separator, i);
if(pos<size) if(pos < size)
{ {
std::string s=str.substr(i,pos-i); std::string s = str.substr(i, pos - i);
result.push_back(s); result.push_back(s);
i=pos+separator.size()-1; i = pos + separator.size() - 1;
} }
} }
return result; return result;
} }
#if defined _WIN32 || defined WINCE #if defined _WIN32 || defined WINCE
const char dir_separators[] = "/\\"; const char dir_separators[] = "/\\";
struct dirent struct dirent
{ {
const char* d_name; const char* d_name;
}; };
struct DIR struct DIR
{ {
#ifdef WINRT #ifdef WINRT
WIN32_FIND_DATAW data; WIN32_FIND_DATAW data;
#else #else
...@@ -62,17 +62,17 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -62,17 +62,17 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
HANDLE handle; HANDLE handle;
dirent ent; dirent ent;
#ifdef WINRT #ifdef WINRT
DIR() { } DIR() {}
~DIR() ~DIR()
{ {
if (ent.d_name) if(ent.d_name)
delete[] ent.d_name; delete[] ent.d_name;
} }
#endif #endif
}; };
DIR* opendir(const char* path) DIR* opendir(const char* path)
{ {
DIR* dir = new DIR; DIR* dir = new DIR;
dir->ent.d_name = 0; dir->ent.d_name = 0;
#ifdef WINRT #ifdef WINRT
...@@ -80,27 +80,31 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -80,27 +80,31 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
wchar_t wfull_path[MAX_PATH]; wchar_t wfull_path[MAX_PATH];
size_t copied = mbstowcs(wfull_path, full_path.c_str(), MAX_PATH); size_t copied = mbstowcs(wfull_path, full_path.c_str(), MAX_PATH);
CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1)); CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
dir->handle = ::FindFirstFileExW(wfull_path, FindExInfoStandard, dir->handle = ::FindFirstFileExW(
&dir->data, FindExSearchNameMatch, NULL, 0); wfull_path, FindExInfoStandard, &dir->data, FindExSearchNameMatch, NULL, 0);
#else #else
dir->handle = ::FindFirstFileExA((string(path) + "\\*").c_str(), dir->handle = ::FindFirstFileExA((string(path) + "\\*").c_str(),
FindExInfoStandard, &dir->data, FindExSearchNameMatch, NULL, 0); FindExInfoStandard,
&dir->data,
FindExSearchNameMatch,
NULL,
0);
#endif #endif
if (dir->handle == INVALID_HANDLE_VALUE) if(dir->handle == INVALID_HANDLE_VALUE)
{ {
/*closedir will do all cleanup*/ /*closedir will do all cleanup*/
delete dir; delete dir;
return 0; return 0;
} }
return dir; return dir;
} }
dirent* readdir(DIR* dir) dirent* readdir(DIR* dir)
{ {
#ifdef WINRT #ifdef WINRT
if (dir->ent.d_name != 0) if(dir->ent.d_name != 0)
{ {
if (::FindNextFileW(dir->handle, &dir->data) != TRUE) if(::FindNextFileW(dir->handle, &dir->data) != TRUE)
return 0; return 0;
} }
size_t asize = wcstombs(NULL, dir->data.cFileName, 0); size_t asize = wcstombs(NULL, dir->data.cFileName, 0);
...@@ -110,33 +114,33 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -110,33 +114,33 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
wcstombs(aname, dir->data.cFileName, asize); wcstombs(aname, dir->data.cFileName, asize);
dir->ent.d_name = aname; dir->ent.d_name = aname;
#else #else
if (dir->ent.d_name != 0) if(dir->ent.d_name != 0)
{ {
if (::FindNextFileA(dir->handle, &dir->data) != TRUE) if(::FindNextFileA(dir->handle, &dir->data) != TRUE)
return 0; return 0;
} }
dir->ent.d_name = dir->data.cFileName; dir->ent.d_name = dir->data.cFileName;
#endif #endif
return &dir->ent; return &dir->ent;
} }
void closedir(DIR* dir) void closedir(DIR* dir)
{ {
::FindClose(dir->handle); ::FindClose(dir->handle);
delete dir; delete dir;
} }
#else #else
# include <dirent.h> #include <dirent.h>
# include <sys/stat.h> #include <sys/stat.h>
const char dir_separators[] = "/"; const char dir_separators[] = "/";
#endif #endif
static bool isDir(const string &path, DIR* dir) static bool isDir(const string& path, DIR* dir)
{ {
#if defined _WIN32 || defined WINCE #if defined _WIN32 || defined WINCE
DWORD attributes; DWORD attributes;
BOOL status = TRUE; BOOL status = TRUE;
if (dir) if(dir)
attributes = dir->data.dwFileAttributes; attributes = dir->data.dwFileAttributes;
else else
{ {
...@@ -156,20 +160,17 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -156,20 +160,17 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
#else #else
(void)dir; (void)dir;
struct stat stat_buf; struct stat stat_buf;
if (0 != stat(path.c_str(), &stat_buf)) if(0 != stat(path.c_str(), &stat_buf))
return false; return false;
int is_dir = S_ISDIR(stat_buf.st_mode); int is_dir = S_ISDIR(stat_buf.st_mode);
return is_dir != 0; return is_dir != 0;
#endif #endif
} }
bool IsDirectory(const string &path) bool IsDirectory(const string& path) { return isDir(path, NULL); }
{
return isDir(path, NULL);
}
bool Exists(const string& path) bool Exists(const string& path)
{ {
#if defined _WIN32 || defined WINCE #if defined _WIN32 || defined WINCE
BOOL status = TRUE; BOOL status = TRUE;
...@@ -190,28 +191,25 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -190,28 +191,25 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
struct stat stat_buf; struct stat stat_buf;
return (0 == stat(path.c_str(), &stat_buf)); return (0 == stat(path.c_str(), &stat_buf));
#endif #endif
} }
bool IsPathSeparator(char c) bool IsPathSeparator(char c) { return c == '/' || c == '\\'; }
{
return c == '/' || c == '\\';
}
string JoinPath(const string& base, const string& path) string JoinPath(const string& base, const string& path)
{ {
if (base.empty()) if(base.empty())
return path; return path;
if (path.empty()) if(path.empty())
return base; return base;
bool baseSep = IsPathSeparator(base[base.size() - 1]); bool baseSep = IsPathSeparator(base[base.size() - 1]);
bool pathSep = IsPathSeparator(path[0]); bool pathSep = IsPathSeparator(path[0]);
string result; string result;
if (baseSep && pathSep) if(baseSep && pathSep)
{ {
result = base + path.substr(1); result = base + path.substr(1);
} }
else if (!baseSep && !pathSep) else if(!baseSep && !pathSep)
{ {
result = base + PATH_SEPARATOR + path; result = base + PATH_SEPARATOR + path;
} }
...@@ -220,15 +218,15 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -220,15 +218,15 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
result = base + path; result = base + path;
} }
return result; return result;
} }
static bool wildcmp(const char *string, const char *wild) static bool wildcmp(const char* string, const char* wild)
{ {
const char *cp = 0, *mp = 0; const char *cp = 0, *mp = 0;
while ((*string) && (*wild != '*')) while((*string) && (*wild != '*'))
{ {
if ((*wild != *string) && (*wild != '?')) if((*wild != *string) && (*wild != '?'))
{ {
return false; return false;
} }
...@@ -237,11 +235,11 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -237,11 +235,11 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
string++; string++;
} }
while (*string) while(*string)
{ {
if (*wild == '*') if(*wild == '*')
{ {
if (!*++wild) if(!*++wild)
{ {
return true; return true;
} }
...@@ -249,7 +247,7 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -249,7 +247,7 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
mp = wild; mp = wild;
cp = string + 1; cp = string + 1;
} }
else if ((*wild == *string) || (*wild == '?')) else if((*wild == *string) || (*wild == '?'))
{ {
wild++; wild++;
string++; string++;
...@@ -261,47 +259,52 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -261,47 +259,52 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
} }
} }
while (*wild == '*') while(*wild == '*')
{ {
wild++; wild++;
} }
return *wild == 0; return *wild == 0;
} }
static void glob_rec(const string &directory, const string& wildchart, std::vector<string>& result, static void glob_rec(const string& directory,
bool recursive, bool includeDirectories, const string& pathPrefix) const string& wildchart,
{ std::vector<string>& result,
DIR *dir; bool recursive,
bool includeDirectories,
const string& pathPrefix)
{
DIR* dir;
if ((dir = opendir(directory.c_str())) != 0) if((dir = opendir(directory.c_str())) != 0)
{ {
/* find all the files and directories within directory */ /* find all the files and directories within directory */
try try
{ {
struct dirent *ent; struct dirent* ent;
while ((ent = readdir(dir)) != 0) while((ent = readdir(dir)) != 0)
{ {
const char* name = ent->d_name; const char* name = ent->d_name;
if ((name[0] == 0) || (name[0] == '.' && name[1] == 0) || (name[0] == '.' && name[1] == '.' && name[2] == 0)) if((name[0] == 0) || (name[0] == '.' && name[1] == 0) ||
(name[0] == '.' && name[1] == '.' && name[2] == 0))
continue; continue;
string path = JoinPath(directory, name); string path = JoinPath(directory, name);
string entry = JoinPath(pathPrefix, name); string entry = JoinPath(pathPrefix, name);
if (isDir(path, dir)) if(isDir(path, dir))
{ {
if (recursive) if(recursive)
glob_rec(path, wildchart, result, recursive, includeDirectories, entry); glob_rec(path, wildchart, result, recursive, includeDirectories, entry);
if (!includeDirectories) if(!includeDirectories)
continue; continue;
} }
if (wildchart.empty() || wildcmp(name, wildchart.c_str())) if(wildchart.empty() || wildcmp(name, wildchart.c_str()))
result.push_back(entry); result.push_back(entry);
} }
} }
catch (...) catch(...)
{ {
closedir(dir); closedir(dir);
throw; throw;
...@@ -312,23 +315,27 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -312,23 +315,27 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
{ {
printf("could not open directory: %s", directory.c_str()); printf("could not open directory: %s", directory.c_str());
} }
} }
void GetFileNameList(const string &directory, const string &pattern, std::vector<string>& result, bool recursive, bool addPath) void GetFileNameList(const string& directory,
{ const string& pattern,
std::vector<string>& result,
bool recursive,
bool addPath)
{
// split pattern // split pattern
vector<string> patterns=SplitString(pattern,","); vector<string> patterns = SplitString(pattern, ",");
result.clear(); result.clear();
for(int i=0;i<patterns.size();++i) for(int i = 0; i < patterns.size(); ++i)
{ {
string eachPattern=patterns[i]; string eachPattern = patterns[i];
std::vector<string> eachResult; std::vector<string> eachResult;
glob_rec(directory, eachPattern, eachResult, recursive, true, directory); glob_rec(directory, eachPattern, eachResult, recursive, true, directory);
for(int j=0;j<eachResult.size();++j) for(int j = 0; j < eachResult.size(); ++j)
{ {
if (IsDirectory(eachResult[j])) if(IsDirectory(eachResult[j]))
continue; continue;
if(addPath) if(addPath)
{ {
...@@ -341,41 +348,45 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -341,41 +348,45 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
} }
} }
std::sort(result.begin(), result.end()); std::sort(result.begin(), result.end());
} }
void GetFileNameList2(const string &directory, const string &pattern, std::vector<string>& result, bool recursive, bool addPath) void GetFileNameList2(const string& directory,
{ const string& pattern,
std::vector<string>& result,
bool recursive,
bool addPath)
{
// split pattern // split pattern
vector<string> patterns = SplitString(pattern, ","); vector<string> patterns = SplitString(pattern, ",");
result.clear(); result.clear();
for (int i = 0; i<patterns.size(); ++i) for(int i = 0; i < patterns.size(); ++i)
{ {
string eachPattern = patterns[i]; string eachPattern = patterns[i];
std::vector<string> eachResult; std::vector<string> eachResult;
glob_rec(directory, eachPattern, eachResult, recursive, true, directory); glob_rec(directory, eachPattern, eachResult, recursive, true, directory);
for (int j = 0; j<eachResult.size(); ++j) for(int j = 0; j < eachResult.size(); ++j)
{ {
string filePath = eachResult[j]; string filePath = eachResult[j];
if (IsDirectory(filePath)) if(IsDirectory(filePath))
{ {
filePath = filePath + "/"; filePath = filePath + "/";
for (int k = 0; k < filePath.size(); ++k) for(int k = 0; k < filePath.size(); ++k)
{ {
if (IsPathSeparator(filePath[k])) if(IsPathSeparator(filePath[k]))
{ {
filePath[k] = '/'; filePath[k] = '/';
} }
} }
} }
if (addPath) if(addPath)
{ {
result.push_back(filePath); result.push_back(filePath);
} }
else else
{ {
if (!IsDirectory(filePath)) if(!IsDirectory(filePath))
{ {
result.push_back(GetFileName(filePath)); result.push_back(GetFileName(filePath));
} }
...@@ -383,19 +394,19 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -383,19 +394,19 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
} }
} }
std::sort(result.begin(), result.end()); std::sort(result.begin(), result.end());
} }
void RemoveAll(const string& path) void RemoveAll(const string& path)
{ {
if (!Exists(path)) if(!Exists(path))
return; return;
if (IsDirectory(path)) if(IsDirectory(path))
{ {
std::vector<string> entries; std::vector<string> entries;
GetFileNameList2(path, string(), entries, false, true); GetFileNameList2(path, string(), entries, false, true);
for (size_t i = 0; i < entries.size(); i++) for(size_t i = 0; i < entries.size(); i++)
{ {
const string& e = entries[i]; const string& e = entries[i];
RemoveAll(e); RemoveAll(e);
...@@ -405,7 +416,7 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -405,7 +416,7 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
#else #else
bool result = rmdir(path.c_str()) == 0; bool result = rmdir(path.c_str()) == 0;
#endif #endif
if (!result) if(!result)
{ {
printf("can't remove directory: %s\n", path.c_str()); printf("can't remove directory: %s\n", path.c_str());
} }
...@@ -417,50 +428,50 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -417,50 +428,50 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
#else #else
bool result = unlink(path.c_str()) == 0; bool result = unlink(path.c_str()) == 0;
#endif #endif
if (!result) if(!result)
{ {
printf("can't remove file: %s\n", path.c_str()); printf("can't remove file: %s\n", path.c_str());
} }
} }
} }
void Remove(const string &directory, const string &extension) void Remove(const string& directory, const string& extension)
{ {
DIR *dir; DIR* dir;
static int numberOfFiles = 0; static int numberOfFiles = 0;
if ((dir = opendir(directory.c_str())) != 0) if((dir = opendir(directory.c_str())) != 0)
{ {
/* find all the files and directories within directory */ /* find all the files and directories within directory */
try try
{ {
struct dirent *ent; struct dirent* ent;
while ((ent = readdir(dir)) != 0) while((ent = readdir(dir)) != 0)
{ {
const char* name = ent->d_name; const char* name = ent->d_name;
if ((name[0] == 0) || (name[0] == '.' && name[1] == 0) || (name[0] == '.' && name[1] == '.' && name[2] == 0)) if((name[0] == 0) || (name[0] == '.' && name[1] == 0) ||
(name[0] == '.' && name[1] == '.' && name[2] == 0))
continue; continue;
string path = JoinPath(directory, name); string path = JoinPath(directory, name);
if (isDir(path, dir)) if(isDir(path, dir))
{ {
Remove(path, extension); Remove(path, extension);
} }
// �ж���չ�� // �ж���չ��
if (extension.empty() || wildcmp(name, extension.c_str())) if(extension.empty() || wildcmp(name, extension.c_str()))
{ {
RemoveAll(path); RemoveAll(path);
++numberOfFiles; ++numberOfFiles;
printf("%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);
} }
} }
} }
catch (...) catch(...)
{ {
closedir(dir); closedir(dir);
throw; throw;
...@@ -474,49 +485,49 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -474,49 +485,49 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
// ����RemoveAllɾ��Ŀ¼ // ����RemoveAllɾ��Ŀ¼
RemoveAll(directory); RemoveAll(directory);
} }
string GetFileName(const string &path) string GetFileName(const string& path)
{ {
string fileName; string fileName;
int indexOfPathSeparator = -1; int indexOfPathSeparator = -1;
for (int i = path.size() - 1; i >= 0; --i) for(int i = path.size() - 1; i >= 0; --i)
{ {
if (IsPathSeparator(path[i])) if(IsPathSeparator(path[i]))
{ {
fileName = path.substr(i + 1, path.size() - i - 1); fileName = path.substr(i + 1, path.size() - i - 1);
indexOfPathSeparator = i; indexOfPathSeparator = i;
break; break;
} }
} }
if (indexOfPathSeparator == -1) if(indexOfPathSeparator == -1)
{ {
fileName = path; fileName = path;
} }
return fileName; return fileName;
} }
string GetFileName_NoExtension(const string &path) string GetFileName_NoExtension(const string& path)
{ {
string fileName=GetFileName(path); string fileName = GetFileName(path);
string fileName_NoExtension; string fileName_NoExtension;
for(int i=fileName.size()-1;i>0;--i) for(int i = fileName.size() - 1; i > 0; --i)
{ {
if(fileName[i]=='.') if(fileName[i] == '.')
{ {
fileName_NoExtension=fileName.substr(0,i); fileName_NoExtension = fileName.substr(0, i);
break; break;
} }
} }
return fileName_NoExtension; return fileName_NoExtension;
} }
string GetExtension(const string &path) string GetExtension(const string& path)
{ {
string fileName; string fileName;
for (int i = path.size() - 1; i >= 0; --i) for(int i = path.size() - 1; i >= 0; --i)
{ {
if (path[i]=='.') if(path[i] == '.')
{ {
fileName = path.substr(i, path.size() - i); fileName = path.substr(i, path.size() - i);
break; break;
...@@ -524,56 +535,55 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -524,56 +535,55 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
} }
return fileName; return fileName;
}
} string GetParentPath(const string& path)
{
string GetParentPath(const string &path)
{
string fileName; string fileName;
for (int i = path.size() - 1; i >= 0; --i) for(int i = path.size() - 1; i >= 0; --i)
{ {
if (IsPathSeparator(path[i])) if(IsPathSeparator(path[i]))
{ {
fileName = path.substr(0, i+1); fileName = path.substr(0, i + 1);
break; break;
} }
} }
return fileName; return fileName;
} }
static bool CreateDirectory(const string &path) static bool CreateDirectory(const string& path)
{ {
#if defined WIN32 || defined _WIN32 || defined WINCE #if defined WIN32 || defined _WIN32 || defined WINCE
#ifdef WINRT #ifdef WINRT
wchar_t wpath[MAX_PATH]; wchar_t wpath[MAX_PATH];
size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH); size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1)); CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
int result = CreateDirectoryA(wpath, NULL) ? 0 : -1; int result = CreateDirectoryA(wpath, NULL) ? 0 : -1;
#else #else
int result = _mkdir(path.c_str()); int result = _mkdir(path.c_str());
#endif #endif
#elif defined __linux__ || defined __APPLE__ #elif defined __linux__ || defined __APPLE__
int result = mkdir(path.c_str(), 0777); int result = mkdir(path.c_str(), 0777);
#else #else
int result = -1; int result = -1;
#endif #endif
if (result == -1) if(result == -1)
{ {
return IsDirectory(path); return IsDirectory(path);
} }
return true; return true;
} }
bool CreateDirectories(const string &directoryPath) bool CreateDirectories(const string& directoryPath)
{ {
string path = directoryPath; string path = directoryPath;
for (;;) for(;;)
{ {
char last_char = path.empty() ? 0 : path[path.length() - 1]; char last_char = path.empty() ? 0 : path[path.length() - 1];
if (IsPathSeparator(last_char)) if(IsPathSeparator(last_char))
{ {
path = path.substr(0, path.length() - 1); path = path.substr(0, path.length() - 1);
continue; continue;
...@@ -581,35 +591,35 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -581,35 +591,35 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
break; break;
} }
if (path.empty() || path == "./" || path == ".\\" || path == ".") if(path.empty() || path == "./" || path == ".\\" || path == ".")
return true; return true;
if (IsDirectory(path)) if(IsDirectory(path))
return true; return true;
size_t pos = path.rfind('/'); size_t pos = path.rfind('/');
if (pos == string::npos) if(pos == string::npos)
pos = path.rfind('\\'); pos = path.rfind('\\');
if (pos != string::npos) if(pos != string::npos)
{ {
string parent_directory = path.substr(0, pos); string parent_directory = path.substr(0, pos);
if (!parent_directory.empty()) if(!parent_directory.empty())
{ {
if (!CreateDirectories(parent_directory)) if(!CreateDirectories(parent_directory))
return false; return false;
} }
} }
return CreateDirectory(path); return CreateDirectory(path);
} }
bool CopyFile(const string srcPath, const string dstPath) bool CopyFile(const string srcPath, const string dstPath)
{ {
std::ifstream srcFile(srcPath,ios::binary); std::ifstream srcFile(srcPath, ios::binary);
std::ofstream dstFile(dstPath,ios::binary); std::ofstream dstFile(dstPath, ios::binary);
if(!srcFile.is_open()) if(!srcFile.is_open())
{ {
printf("can not open %s\n",srcPath.c_str()); printf("can not open %s\n", srcPath.c_str());
return false; return false;
} }
if(!dstFile.is_open()) if(!dstFile.is_open())
...@@ -617,27 +627,27 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -617,27 +627,27 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
printf("can not open %s\n", dstPath.c_str()); printf("can not open %s\n", dstPath.c_str());
return false; return false;
} }
if(srcPath==dstPath) if(srcPath == dstPath)
{ {
printf("src can not be same with dst\n"); printf("src can not be same with dst\n");
return false; return false;
} }
char buffer[2048]; char buffer[2048];
unsigned int numberOfBytes=0; unsigned int numberOfBytes = 0;
while(srcFile) while(srcFile)
{ {
srcFile.read(buffer,2048); srcFile.read(buffer, 2048);
dstFile.write(buffer,srcFile.gcount()); dstFile.write(buffer, srcFile.gcount());
numberOfBytes+=srcFile.gcount(); numberOfBytes += srcFile.gcount();
} }
srcFile.close(); srcFile.close();
dstFile.close(); dstFile.close();
return true; return true;
} }
bool CopyDirectories(string srcPath, const string dstPath) bool CopyDirectories(string srcPath, const string dstPath)
{ {
if(srcPath==dstPath) if(srcPath == dstPath)
{ {
printf("src can not be same with dst\n"); printf("src can not be same with dst\n");
return false; return false;
...@@ -649,45 +659,41 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -649,45 +659,41 @@ static std::vector<std::string> SplitString(std::string str, std::string separat
vector<string> fileNameList; vector<string> fileNameList;
GetFileNameList2(srcPath, "", fileNameList, true, true); GetFileNameList2(srcPath, "", fileNameList, true, true);
string parentPathOfSrc=GetParentPath(srcPath); string parentPathOfSrc = GetParentPath(srcPath);
int length=parentPathOfSrc.size(); int length = parentPathOfSrc.size();
// create all directories // create all directories
for(int i=0;i<fileNameList.size();++i) for(int i = 0; i < fileNameList.size(); ++i)
{ {
// create directory // create directory
string srcFilePath=fileNameList[i]; string srcFilePath = fileNameList[i];
string subStr=srcFilePath.substr(length,srcFilePath.size()-length); string subStr = srcFilePath.substr(length, srcFilePath.size() - length);
string dstFilePath=dstPath+subStr; string dstFilePath = dstPath + subStr;
string parentPathOfDst=GetParentPath(dstFilePath); string parentPathOfDst = GetParentPath(dstFilePath);
CreateDirectories(parentPathOfDst); CreateDirectories(parentPathOfDst);
} }
// copy file // copy file
for(int i=0;i<fileNameList.size();++i) for(int i = 0; i < fileNameList.size(); ++i)
{ {
string srcFilePath=fileNameList[i]; string srcFilePath = fileNameList[i];
if (IsDirectory(srcFilePath)) if(IsDirectory(srcFilePath))
{ {
continue; continue;
} }
string subStr=srcFilePath.substr(length,srcFilePath.size()-length); string subStr = srcFilePath.substr(length, srcFilePath.size() - length);
string dstFilePath=dstPath+subStr; string dstFilePath = dstPath + subStr;
// copy file // copy file
CopyFile(srcFilePath,dstFilePath); CopyFile(srcFilePath, dstFilePath);
// process // process
double process = (1.0*(i + 1) / fileNameList.size()) * 100; double process = (1.0 * (i + 1) / fileNameList.size()) * 100;
printf("%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process); printf("%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
} }
printf("all done!(the number of files:%d)\n", fileNameList.size()); printf("all done!(the number of files:%d)\n", fileNameList.size());
return true; return true;
}
} }
} // namespace migraphxSamples
...@@ -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__
...@@ -11,8 +11,8 @@ int main() ...@@ -11,8 +11,8 @@ int main()
migraphxSamples::Unet unet; migraphxSamples::Unet unet;
migraphxSamples::InitializationParameterOfSegmentation initParamOfSegmentationUnet; migraphxSamples::InitializationParameterOfSegmentation initParamOfSegmentationUnet;
initParamOfSegmentationUnet.configFilePath = CONFIG_FILE; initParamOfSegmentationUnet.configFilePath = CONFIG_FILE;
migraphxSamples::ErrorCode errorCode=unet.Initialize(initParamOfSegmentationUnet); migraphxSamples::ErrorCode errorCode = unet.Initialize(initParamOfSegmentationUnet);
if(errorCode!=migraphxSamples::SUCCESS) if(errorCode != migraphxSamples::SUCCESS)
{ {
LOG_ERROR(stdout, "fail to initialize Unet!\n"); LOG_ERROR(stdout, "fail to initialize Unet!\n");
exit(-1); exit(-1);
...@@ -20,13 +20,13 @@ int main() ...@@ -20,13 +20,13 @@ int main()
LOG_INFO(stdout, "succeed to initialize Unet\n"); LOG_INFO(stdout, "succeed to initialize Unet\n");
// 读取图像 // 读取图像
cv::Mat srcImage =cv::imread("../Resource/Images/car1.jpeg", 1); cv::Mat srcImage = cv::imread("../Resource/Images/car1.jpeg", 1);
// 推理 // 推理
cv::Mat maskImage; cv::Mat maskImage;
unet.Segmentation(srcImage, maskImage); unet.Segmentation(srcImage, maskImage);
LOG_INFO(stdout,"========== Segmentation Results ==========\n"); LOG_INFO(stdout, "========== Segmentation Results ==========\n");
LOG_INFO(stdout,"Segmentation results have been saved to ./Result.jpg\n"); LOG_INFO(stdout, "Segmentation results have been saved to ./Result.jpg\n");
cv::imwrite("./Result.jpg", maskImage); cv::imwrite("./Result.jpg", maskImage);
return 0; return 0;
......
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