Commit 906376c1 authored by liucong's avatar liucong
Browse files

重新进行Cpp代码的格式化

parent 474298d4
...@@ -9,36 +9,34 @@ ...@@ -9,36 +9,34 @@
namespace migraphxSamples namespace migraphxSamples
{ {
#define SSD_QUANT_BASE 4096 // 基数 #define SSD_QUANT_BASE 4096 // 基数
#define SSD_COORDI_NUM 4 // 坐标个数(x1,y1,x2,y2) #define SSD_COORDI_NUM 4 // 坐标个数(x1,y1,x2,y2)
#define SSD_PROPOSAL_WIDTH 6 #define SSD_PROPOSAL_WIDTH 6
#define SSD_HALF 0.5 #define SSD_HALF 0.5
#define SSD_ASPECT_RATIO_NUM 6 // 默认最大的宽高比个数 #define SSD_ASPECT_RATIO_NUM 6 // 默认最大的宽高比个数
#define SSD_MAX(a,b) (((a) > (b)) ? (a) : (b)) #define SSD_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define SSD_MIN(a,b) (((a) < (b)) ? (a) : (b)) #define SSD_MIN(a, b) (((a) < (b)) ? (a) : (b))
// 16字节对齐 // 16字节对齐
#define SSD_ALIGN_16 16 #define SSD_ALIGN_16 16
#define SSD_ALIGN16(number) ((number + SSD_ALIGN_16-1) / SSD_ALIGN_16*SSD_ALIGN_16) #define SSD_ALIGN16(number) ((number + SSD_ALIGN_16 - 1) / SSD_ALIGN_16 * SSD_ALIGN_16)
DetectorRetinaFace::DetectorRetinaFace() DetectorRetinaFace::DetectorRetinaFace() {}
{
}
DetectorRetinaFace::~DetectorRetinaFace() DetectorRetinaFace::~DetectorRetinaFace()
{ {
configurationFile.release(); configurationFile.release();
// 释放SSD参数的内存空间 // 释放SSD参数的内存空间
delete[] ssdParameter.buffer; delete[] ssdParameter.buffer;
} }
ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initializationParameterOfDetector) ErrorCode
DetectorRetinaFace::Initialize(InitializationParameterOfDetector initializationParameterOfDetector)
{ {
// 读取配置文件 // 读取配置文件
std::string configFilePath=initializationParameterOfDetector.configFilePath; std::string configFilePath = initializationParameterOfDetector.configFilePath;
if(!Exists(configFilePath)) if(!Exists(configFilePath))
{ {
LOG_ERROR(stdout, "no configuration file!\n"); LOG_ERROR(stdout, "no configuration file!\n");
...@@ -46,43 +44,43 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi ...@@ -46,43 +44,43 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi
} }
if(!configurationFile.open(configFilePath, cv::FileStorage::READ)) if(!configurationFile.open(configFilePath, cv::FileStorage::READ))
{ {
LOG_ERROR(stdout, "fail to open configuration file\n"); LOG_ERROR(stdout, "fail to open configuration file\n");
return FAIL_TO_OPEN_CONFIG_FILE; return FAIL_TO_OPEN_CONFIG_FILE;
} }
LOG_INFO(stdout, "succeed to open configuration file\n"); LOG_INFO(stdout, "succeed to open configuration file\n");
// 获取配置文件参数 // 获取配置文件参数
cv::FileNode netNode = configurationFile["DetectorRetinaFace"]; cv::FileNode netNode = configurationFile["DetectorRetinaFace"];
string modelPath=(string)netNode["ModelPath"]; string modelPath = (string)netNode["ModelPath"];
scale=(float)netNode["Scale"]; scale = (float)netNode["Scale"];
meanValue.val[0]=(float)netNode["MeanValue1"]; meanValue.val[0] = (float)netNode["MeanValue1"];
meanValue.val[1]=(float)netNode["MeanValue2"]; meanValue.val[1] = (float)netNode["MeanValue2"];
meanValue.val[2]=(float)netNode["MeanValue3"]; meanValue.val[2] = (float)netNode["MeanValue3"];
swapRB=(bool)(int)netNode["SwapRB"]; swapRB = (bool)(int)netNode["SwapRB"];
crop=(bool)(int)netNode["Crop"]; crop = (bool)(int)netNode["Crop"];
useInt8=(bool)(int)netNode["UseInt8"]; useInt8 = (bool)(int)netNode["UseInt8"];
useFP16=(bool)(int)netNode["UseFP16"]; useFP16 = (bool)(int)netNode["UseFP16"];
// 加载模型 // 加载模型
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); net = migraphx::parse_onnx(modelPath);
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{};
...@@ -90,25 +88,20 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi ...@@ -90,25 +88,20 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi
if(useInt8) if(useInt8)
{ {
// 创建量化校准数据,建议使用测试集中的多张典型图像 // 创建量化校准数据,建议使用测试集中的多张典型图像
cv::Mat srcImage=cv::imread("../Resource/Images/FaceDetect_2.jpg",1); cv::Mat srcImage = cv::imread("../Resource/Images/FaceDetect_2.jpg", 1);
std::vector<cv::Mat> srcImages; std::vector<cv::Mat> srcImages;
for(int i=0;i<inputShape.lens()[0];++i) for(int i = 0; i < inputShape.lens()[0]; ++i)
{ {
srcImages.push_back(srcImage); srcImages.push_back(srcImage);
} }
cv::Mat inputBlob; cv::Mat inputBlob;
cv::dnn::blobFromImages(srcImages, cv::dnn::blobFromImages(srcImages, inputBlob, scale, inputSize, meanValue, swapRB, false);
inputBlob,
scale,
inputSize,
meanValue,
swapRB,
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<std::unordered_map<std::string, migraphx::argument>> calibrationData = {inputData}; std::vector<std::unordered_map<std::string, migraphx::argument>> calibrationData = {
inputData};
// INT8量化 // INT8量化
migraphx::quantize_int8(net, gpuTarget, calibrationData); migraphx::quantize_int8(net, gpuTarget, calibrationData);
...@@ -120,10 +113,10 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi ...@@ -120,10 +113,10 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi
// 编译模型 // 编译模型
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;
...@@ -131,14 +124,14 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi ...@@ -131,14 +124,14 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi
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());
LOG_INFO(stdout,"Scale:%.6f\n",scale); LOG_INFO(stdout, "Scale:%.6f\n", scale);
LOG_INFO(stdout,"Mean:%.2f,%.2f,%.2f\n",meanValue.val[0],meanValue.val[1],meanValue.val[2]); LOG_INFO(stdout, "Mean:%.2f,%.2f,%.2f\n", meanValue.val[0], meanValue.val[1], meanValue.val[2]);
LOG_INFO(stdout,"SwapRB:%d\n",(int)swapRB); LOG_INFO(stdout, "SwapRB:%d\n", (int)swapRB);
LOG_INFO(stdout,"Crop:%d\n",(int)crop); LOG_INFO(stdout, "Crop:%d\n", (int)crop);
LOG_INFO(stdout,"UseInt8:%d\n",(int)useInt8); LOG_INFO(stdout, "UseInt8:%d\n", (int)useInt8);
LOG_INFO(stdout,"UseFP16:%d\n",(int)useFP16); LOG_INFO(stdout, "UseFP16:%d\n", (int)useFP16);
// 读取SSD 参数 // 读取SSD 参数
GetSSDParameter(); GetSSDParameter();
...@@ -146,10 +139,11 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi ...@@ -146,10 +139,11 @@ ErrorCode DetectorRetinaFace::Initialize(InitializationParameterOfDetector initi
return SUCCESS; return SUCCESS;
} }
ErrorCode DetectorRetinaFace::Detect(const cv::Mat &srcImage,std::vector<ResultOfDetection> &resultsOfDetection) ErrorCode DetectorRetinaFace::Detect(const cv::Mat& srcImage,
std::vector<ResultOfDetection>& resultsOfDetection)
{ {
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;
...@@ -157,410 +151,423 @@ ErrorCode DetectorRetinaFace::Detect(const cv::Mat &srcImage,std::vector<ResultO ...@@ -157,410 +151,423 @@ ErrorCode DetectorRetinaFace::Detect(const cv::Mat &srcImage,std::vector<ResultO
// 数据预处理并转换为NCHW格式 // 数据预处理并转换为NCHW格式
cv::Mat inputBlob; cv::Mat inputBlob;
cv::dnn::blobFromImage(srcImage, cv::dnn::blobFromImage(srcImage, inputBlob, scale, inputSize, meanValue, swapRB, false);
inputBlob,
scale,
inputSize,
meanValue,
swapRB,
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> inferenceResults=net.eval(inputData); std::vector<migraphx::argument> inferenceResults = net.eval(inputData);
std::vector<std::vector<float>> regressions; std::vector<std::vector<float>> regressions;
std::vector<std::vector<float>> classifications; std::vector<std::vector<float>> classifications;
for(int i=0;i<ssdParameter.numberOfPriorBoxLayer;++i) // 执行Permute操作 for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) // 执行Permute操作
{ {
int numberOfPriorBox=ssdParameter.detectInputChn[i]/(4*(ssdParameter.priorBoxHeight[i] * ssdParameter.priorBoxWidth[i])); int numberOfPriorBox =
ssdParameter.detectInputChn[i] /
(4 * (ssdParameter.priorBoxHeight[i] * ssdParameter.priorBoxWidth[i]));
// BboxHead // BboxHead
std::vector<float> regression; std::vector<float> regression;
migraphx::argument result0 = inferenceResults[2*i]; migraphx::argument result0 = inferenceResults[2 * i];
result0.visit([&](auto output) { regression.assign(output.begin(), output.end()); }); result0.visit([&](auto output) { regression.assign(output.begin(), output.end()); });
regression=PermuteLayer(regression,ssdParameter.priorBoxWidth[i],ssdParameter.priorBoxHeight[i],numberOfPriorBox*4); regression = PermuteLayer(regression,
ssdParameter.priorBoxWidth[i],
ssdParameter.priorBoxHeight[i],
numberOfPriorBox * 4);
regressions.push_back(regression); regressions.push_back(regression);
// ClassHead // ClassHead
std::vector<float> classification; std::vector<float> classification;
migraphx::argument result1 = inferenceResults[2*i+1]; migraphx::argument result1 = inferenceResults[2 * i + 1];
result1.visit([&](auto output) { classification.assign(output.begin(), output.end()); }); result1.visit([&](auto output) { classification.assign(output.begin(), output.end()); });
classification=PermuteLayer(classification,ssdParameter.priorBoxWidth[i],ssdParameter.priorBoxHeight[i],numberOfPriorBox*ssdParameter.classNum); classification = PermuteLayer(classification,
ssdParameter.priorBoxWidth[i],
ssdParameter.priorBoxHeight[i],
numberOfPriorBox * ssdParameter.classNum);
classifications.push_back(classification); classifications.push_back(classification);
} }
// 对推理结果进行处理,得到最后SSD检测的结果 // 对推理结果进行处理,得到最后SSD检测的结果
GetResult(classifications,regressions,resultsOfDetection); GetResult(classifications, regressions, resultsOfDetection);
// 转换到原图坐标 // 转换到原图坐标
for(int i=0;i<resultsOfDetection.size();++i) for(int i = 0; i < resultsOfDetection.size(); ++i)
{ {
float ratioOfWidth=(1.0*srcImage.cols)/inputSize.width; float ratioOfWidth = (1.0 * srcImage.cols) / inputSize.width;
float ratioOfHeight=(1.0*srcImage.rows)/inputSize.height; float ratioOfHeight = (1.0 * srcImage.rows) / inputSize.height;
resultsOfDetection[i].boundingBox.x*=ratioOfWidth; resultsOfDetection[i].boundingBox.x *= ratioOfWidth;
resultsOfDetection[i].boundingBox.width*=ratioOfWidth; resultsOfDetection[i].boundingBox.width *= ratioOfWidth;
resultsOfDetection[i].boundingBox.y*=ratioOfHeight; resultsOfDetection[i].boundingBox.y *= ratioOfHeight;
resultsOfDetection[i].boundingBox.height*=ratioOfHeight; resultsOfDetection[i].boundingBox.height *= ratioOfHeight;
} }
// 按照置信度排序 // 按照置信度排序
sort(resultsOfDetection.begin(), resultsOfDetection.end(),CompareConfidence); sort(resultsOfDetection.begin(), resultsOfDetection.end(), CompareConfidence);
return SUCCESS; return SUCCESS;
} }
void DetectorRetinaFace::GetSSDParameter() void DetectorRetinaFace::GetSSDParameter()
{ {
cv::FileNode rootNode = configurationFile["DetectorRetinaFace"]; cv::FileNode rootNode = configurationFile["DetectorRetinaFace"];
ssdParameter.numberOfPriorBoxLayer=(int)rootNode["PriorBoxLayerNumber"]; ssdParameter.numberOfPriorBoxLayer = (int)rootNode["PriorBoxLayerNumber"];
ssdParameter.srcImageHeight = inputSize.height; ssdParameter.srcImageHeight = inputSize.height;
ssdParameter.srcImageWidth = inputSize.width; ssdParameter.srcImageWidth = inputSize.width;
// MinSize,MaxSize // MinSize,MaxSize
ssdParameter.priorBoxMinSize.resize(ssdParameter.numberOfPriorBoxLayer); ssdParameter.priorBoxMinSize.resize(ssdParameter.numberOfPriorBoxLayer);
ssdParameter.priorBoxMaxSize.resize(ssdParameter.numberOfPriorBoxLayer); ssdParameter.priorBoxMaxSize.resize(ssdParameter.numberOfPriorBoxLayer);
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
char nodeName[256] = { 0 }; char nodeName[256] = {0};
// miniSize // miniSize
{ {
int j=0; int j = 0;
while(true) while(true)
{ {
sprintf(nodeName, "MinSize%d%d", (i + 1),++j); sprintf(nodeName, "MinSize%d%d", (i + 1), ++j);
cv::FileNode miniSizeNode = rootNode[nodeName]; cv::FileNode miniSizeNode = rootNode[nodeName];
if(miniSizeNode.empty()) if(miniSizeNode.empty())
{ {
break; break;
} }
else else
{ {
ssdParameter.priorBoxMinSize[i].push_back((float)rootNode[nodeName]); ssdParameter.priorBoxMinSize[i].push_back((float)rootNode[nodeName]);
} }
} }
} }
// maxSize // maxSize
{ {
int j=0; int j = 0;
while(true) while(true)
{ {
sprintf(nodeName, "MaxSize%d%d", (i + 1),++j); sprintf(nodeName, "MaxSize%d%d", (i + 1), ++j);
cv::FileNode maxSizeNode = rootNode[nodeName]; cv::FileNode maxSizeNode = rootNode[nodeName];
if(maxSizeNode.empty()) if(maxSizeNode.empty())
{ {
break; break;
} }
else else
{ {
ssdParameter.priorBoxMaxSize[i].push_back((float)rootNode[nodeName]); ssdParameter.priorBoxMaxSize[i].push_back((float)rootNode[nodeName]);
} }
} }
} }
} }
// MinSizeNumber,MaxSizeNumber // MinSizeNumber,MaxSizeNumber
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
ssdParameter.minSizeNum[i] = ssdParameter.priorBoxMinSize[i].size(); ssdParameter.minSizeNum[i] = ssdParameter.priorBoxMinSize[i].size();
ssdParameter.maxSizeNum[i] = ssdParameter.priorBoxMaxSize[i].size();; ssdParameter.maxSizeNum[i] = ssdParameter.priorBoxMaxSize[i].size();
;
} }
// Flip,Clip // Flip,Clip
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
char nodeName[256] = { 0 }; char nodeName[256] = {0};
// Flip // Flip
sprintf(nodeName, "Flip%d", i + 1); sprintf(nodeName, "Flip%d", i + 1);
int flip = (int)rootNode[nodeName]; int flip = (int)rootNode[nodeName];
ssdParameter.flip[i] = flip; ssdParameter.flip[i] = flip;
// Clip // Clip
sprintf(nodeName, "Clip%d", i + 1); sprintf(nodeName, "Clip%d", i + 1);
int clip = (int)rootNode[nodeName]; int clip = (int)rootNode[nodeName];
ssdParameter.clip[i] = clip; ssdParameter.clip[i] = clip;
} }
// AspectRatio // AspectRatio
ssdParameter.priorBoxAspectRatio.resize(ssdParameter.numberOfPriorBoxLayer); ssdParameter.priorBoxAspectRatio.resize(ssdParameter.numberOfPriorBoxLayer);
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
char nodeName[256] = { 0 }; char nodeName[256] = {0};
int j=0; int j = 0;
while(true) while(true)
{ {
sprintf(nodeName, "AspectRatio%d%d", (i + 1),++j); sprintf(nodeName, "AspectRatio%d%d", (i + 1), ++j);
cv::FileNode aspectRatioNode = rootNode[nodeName]; cv::FileNode aspectRatioNode = rootNode[nodeName];
if(aspectRatioNode.empty()) if(aspectRatioNode.empty())
{ {
break; break;
} }
else else
{ {
ssdParameter.priorBoxAspectRatio[i].push_back((float)rootNode[nodeName]); ssdParameter.priorBoxAspectRatio[i].push_back((float)rootNode[nodeName]);
} }
} }
} }
// aspect ratio number // aspect ratio number
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
ssdParameter.inputAspectRatioNum[i] = ssdParameter.priorBoxAspectRatio[i].size(); ssdParameter.inputAspectRatioNum[i] = ssdParameter.priorBoxAspectRatio[i].size();
} }
// PriorBoxStep // PriorBoxStep
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
char nodeName[256] = { 0 }; char nodeName[256] = {0};
// width
sprintf(nodeName, "PriorBoxStepWidth%d", i + 1);
int width = (int)rootNode[nodeName];
ssdParameter.priorBoxStepWidth[i] = width;
// height // width
sprintf(nodeName, "PriorBoxStepHeight%d", i + 1); sprintf(nodeName, "PriorBoxStepWidth%d", i + 1);
int height = (int)rootNode[nodeName]; int width = (int)rootNode[nodeName];
ssdParameter.priorBoxStepHeight[i] = height; ssdParameter.priorBoxStepWidth[i] = width;
} // height
sprintf(nodeName, "PriorBoxStepHeight%d", i + 1);
int height = (int)rootNode[nodeName];
ssdParameter.priorBoxStepHeight[i] = height;
}
// PriorBoxWidth,PriorBoxHeight // PriorBoxWidth,PriorBoxHeight
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
ssdParameter.priorBoxWidth[i] = ssdParameter.srcImageWidth/ssdParameter.priorBoxStepWidth[i]; ssdParameter.priorBoxWidth[i] =
ssdParameter.priorBoxHeight[i] = ssdParameter.srcImageHeight/ssdParameter.priorBoxStepHeight[i]; ssdParameter.srcImageWidth / ssdParameter.priorBoxStepWidth[i];
ssdParameter.priorBoxHeight[i] =
ssdParameter.srcImageHeight / ssdParameter.priorBoxStepHeight[i];
} }
ssdParameter.offset = (float)rootNode["Offset"]; ssdParameter.offset = (float)rootNode["Offset"];
ssdParameter.priorBoxVar[0] = (int)(0.1f*SSD_QUANT_BASE); ssdParameter.priorBoxVar[0] = (int)(0.1f * SSD_QUANT_BASE);
ssdParameter.priorBoxVar[1] = (int)(0.1f*SSD_QUANT_BASE); ssdParameter.priorBoxVar[1] = (int)(0.1f * SSD_QUANT_BASE);
ssdParameter.priorBoxVar[2] = (int)(0.2f*SSD_QUANT_BASE); ssdParameter.priorBoxVar[2] = (int)(0.2f * SSD_QUANT_BASE);
ssdParameter.priorBoxVar[3] = (int)(0.2f*SSD_QUANT_BASE); ssdParameter.priorBoxVar[3] = (int)(0.2f * SSD_QUANT_BASE);
int classNumber = (int)rootNode["ClassNumber"]; int classNumber = (int)rootNode["ClassNumber"];
ssdParameter.softMaxInHeight = classNumber; ssdParameter.softMaxInHeight = classNumber;
ssdParameter.concatNum = ssdParameter.numberOfPriorBoxLayer; ssdParameter.concatNum = ssdParameter.numberOfPriorBoxLayer;
ssdParameter.softMaxOutWidth = 1; ssdParameter.softMaxOutWidth = 1;
ssdParameter.softMaxOutHeight = classNumber; ssdParameter.softMaxOutHeight = classNumber;
int totalSizeOfClasReg=0;// 分类和回归一共需要的内存空间大小 int totalSizeOfClasReg = 0; // 分类和回归一共需要的内存空间大小
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{ {
int priorBoxNumber=0; int priorBoxNumber = 0;
priorBoxNumber+=1;// aspect ratio=1 priorBoxNumber += 1; // aspect ratio=1
for (int j = 0; j < ssdParameter.inputAspectRatioNum[i]; j++) for(int j = 0; j < ssdParameter.inputAspectRatioNum[i]; j++)
{ {
++priorBoxNumber; ++priorBoxNumber;
if (ssdParameter.flip[j]==1) if(ssdParameter.flip[j] == 1)
{ {
++priorBoxNumber; ++priorBoxNumber;
} }
} }
priorBoxNumber = ssdParameter.minSizeNum[i] * priorBoxNumber + ssdParameter.maxSizeNum[i]; priorBoxNumber = ssdParameter.minSizeNum[i] * priorBoxNumber + ssdParameter.maxSizeNum[i];
int totalPriorBoxNumber = priorBoxNumber*ssdParameter.priorBoxHeight[i] * ssdParameter.priorBoxWidth[i]; int totalPriorBoxNumber =
ssdParameter.softMaxInChn[i] = totalPriorBoxNumber * classNumber; priorBoxNumber * ssdParameter.priorBoxHeight[i] * ssdParameter.priorBoxWidth[i];
ssdParameter.softMaxOutChn += totalPriorBoxNumber; ssdParameter.softMaxInChn[i] = totalPriorBoxNumber * classNumber;
ssdParameter.detectInputChn[i] = totalPriorBoxNumber * 4; ssdParameter.softMaxOutChn += totalPriorBoxNumber;
ssdParameter.detectInputChn[i] = totalPriorBoxNumber * 4;
totalSizeOfClasReg+=(ssdParameter.softMaxInChn[i]+ssdParameter.detectInputChn[i]);
} totalSizeOfClasReg += (ssdParameter.softMaxInChn[i] + ssdParameter.detectInputChn[i]);
}
// DetectionOut // DetectionOut
ssdParameter.classNum = classNumber; ssdParameter.classNum = classNumber;
ssdParameter.topK = (int)rootNode["TopK"];; ssdParameter.topK = (int)rootNode["TopK"];
ssdParameter.keepTopK = (int)rootNode["KeepTopK"]; ;
ssdParameter.NMSThresh = (int)((float)rootNode["NMSThreshold"]* SSD_QUANT_BASE); ssdParameter.keepTopK = (int)rootNode["KeepTopK"];
ssdParameter.confThresh=(int)((float)rootNode["ConfidenceThreshold"]*SSD_QUANT_BASE); ssdParameter.NMSThresh = (int)((float)rootNode["NMSThreshold"] * SSD_QUANT_BASE);
ssdParameter.confThresh = (int)((float)rootNode["ConfidenceThreshold"] * SSD_QUANT_BASE);
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer ; i++)
for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; i++)
{ {
int numberOfPriorBox=ssdParameter.detectInputChn[i]/(4*(ssdParameter.priorBoxHeight[i] * ssdParameter.priorBoxWidth[i])); int numberOfPriorBox =
ssdParameter.detectInputChn[i] /
(4 * (ssdParameter.priorBoxHeight[i] * ssdParameter.priorBoxWidth[i]));
ssdParameter.convHeight[2*i]=ssdParameter.priorBoxHeight[i]; ssdParameter.convHeight[2 * i] = ssdParameter.priorBoxHeight[i];
ssdParameter.convWidth[2*i]=ssdParameter.priorBoxWidth[i]; ssdParameter.convWidth[2 * i] = ssdParameter.priorBoxWidth[i];
ssdParameter.convChannel[2*i]=numberOfPriorBox*4; ssdParameter.convChannel[2 * i] = numberOfPriorBox * 4;
ssdParameter.convHeight[2*i+1]=ssdParameter.priorBoxHeight[i]; ssdParameter.convHeight[2 * i + 1] = ssdParameter.priorBoxHeight[i];
ssdParameter.convWidth[2*i+1]=ssdParameter.priorBoxWidth[i]; ssdParameter.convWidth[2 * i + 1] = ssdParameter.priorBoxWidth[i];
ssdParameter.convChannel[2*i+1]=numberOfPriorBox*ssdParameter.classNum; ssdParameter.convChannel[2 * i + 1] = numberOfPriorBox * ssdParameter.classNum;
ssdParameter.convStride[i] = SSD_ALIGN16(ssdParameter.convChannel[2*i+1] * sizeof(int)) / sizeof(int); ssdParameter.convStride[i] =
SSD_ALIGN16(ssdParameter.convChannel[2 * i + 1] * sizeof(int)) / sizeof(int);
} }
// 计算softMaxOutputData内存空间大小 // 计算softMaxOutputData内存空间大小
int softMaxSize=0; int softMaxSize = 0;
for(int i = 0; i < ssdParameter.concatNum; i++) for(int i = 0; i < ssdParameter.concatNum; i++)
{ {
softMaxSize += ssdParameter.softMaxInChn[i]; softMaxSize += ssdParameter.softMaxInChn[i];
} }
// 计算getResultBuffer内存空间大小 // 计算getResultBuffer内存空间大小
int priorNum = 0; int priorNum = 0;
int detectionSize = 0; int detectionSize = 0;
for(int i = 0; i < ssdParameter.concatNum; i++) for(int i = 0; i < ssdParameter.concatNum; i++)
{ {
priorNum+=ssdParameter.detectInputChn[i]/SSD_COORDI_NUM; priorNum += ssdParameter.detectInputChn[i] / SSD_COORDI_NUM;
} }
detectionSize+=priorNum*SSD_COORDI_NUM; detectionSize += priorNum * SSD_COORDI_NUM;
detectionSize+=priorNum*SSD_PROPOSAL_WIDTH*2; detectionSize += priorNum * SSD_PROPOSAL_WIDTH * 2;
detectionSize+=priorNum*2; detectionSize += priorNum * 2;
// 计算dstRoi,classRoiNum,dstScore内存空间大小 // 计算dstRoi,classRoiNum,dstScore内存空间大小
int dstRoiSize = 0; int dstRoiSize = 0;
int dstScoreSize = 0; int dstScoreSize = 0;
int classRoiNumSize = 0; int classRoiNumSize = 0;
dstRoiSize = SSD_ALIGN16(ssdParameter.classNum*ssdParameter.topK*SSD_COORDI_NUM); dstRoiSize = SSD_ALIGN16(ssdParameter.classNum * ssdParameter.topK * SSD_COORDI_NUM);
dstScoreSize = SSD_ALIGN16(ssdParameter.classNum*ssdParameter.topK); dstScoreSize = SSD_ALIGN16(ssdParameter.classNum * ssdParameter.topK);
classRoiNumSize = SSD_ALIGN16(ssdParameter.classNum); classRoiNumSize = SSD_ALIGN16(ssdParameter.classNum);
// 申请内存,并分配 // 申请内存,并分配
int totalSize=totalSizeOfClasReg+SSD_COORDI_NUM*2*ssdParameter.softMaxOutChn+softMaxSize+detectionSize+dstRoiSize+classRoiNumSize+dstScoreSize; int totalSize = totalSizeOfClasReg + SSD_COORDI_NUM * 2 * ssdParameter.softMaxOutChn +
ssdParameter.buffer=new int[totalSize]; softMaxSize + detectionSize + dstRoiSize + classRoiNumSize + dstScoreSize;
int *data=ssdParameter.buffer; ssdParameter.buffer = new int[totalSize];
memset(data,0,totalSize*sizeof(int));// 初始化0 int* data = ssdParameter.buffer;
int offset=0; memset(data, 0, totalSize * sizeof(int)); // 初始化0
for (int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i) int offset = 0;
{ for(int i = 0; i < ssdParameter.numberOfPriorBoxLayer; ++i)
{
int *dataOfClasReg=data+offset;
ssdParameter.classification[i]=dataOfClasReg;
ssdParameter.regression[i]=dataOfClasReg+ssdParameter.softMaxInChn[i];
offset+=(ssdParameter.softMaxInChn[i]+ssdParameter.detectInputChn[i]);
} int* dataOfClasReg = data + offset;
ssdParameter.priorboxOutputData=data+totalSizeOfClasReg; ssdParameter.classification[i] = dataOfClasReg;
ssdParameter.softMaxOutputData=ssdParameter.priorboxOutputData+SSD_COORDI_NUM*2*ssdParameter.softMaxOutChn; ssdParameter.regression[i] = dataOfClasReg + ssdParameter.softMaxInChn[i];
ssdParameter.getResultBuffer=ssdParameter.softMaxOutputData+softMaxSize;
ssdParameter.dstRoi=ssdParameter.getResultBuffer+detectionSize;
ssdParameter.classRoiNum=ssdParameter.dstRoi+dstRoiSize;
ssdParameter.dstScore=ssdParameter.classRoiNum+classRoiNumSize;
offset += (ssdParameter.softMaxInChn[i] + ssdParameter.detectInputChn[i]);
}
ssdParameter.priorboxOutputData = data + totalSizeOfClasReg;
ssdParameter.softMaxOutputData =
ssdParameter.priorboxOutputData + SSD_COORDI_NUM * 2 * ssdParameter.softMaxOutChn;
ssdParameter.getResultBuffer = ssdParameter.softMaxOutputData + softMaxSize;
ssdParameter.dstRoi = ssdParameter.getResultBuffer + detectionSize;
ssdParameter.classRoiNum = ssdParameter.dstRoi + dstRoiSize;
ssdParameter.dstScore = ssdParameter.classRoiNum + classRoiNumSize;
} }
void DetectorRetinaFace::GetResult(const vector<vector<float>> &classifications,const vector<vector<float>> &regressions,vector<ResultOfDetection> &resultsOfDetection) void DetectorRetinaFace::GetResult(const vector<vector<float>>& classifications,
const vector<vector<float>>& regressions,
vector<ResultOfDetection>& resultsOfDetection)
{ {
int numberOfPriorBoxLayer=ssdParameter.numberOfPriorBoxLayer; int numberOfPriorBoxLayer = ssdParameter.numberOfPriorBoxLayer;
// 类型转换 // 类型转换
for(int i = 0; i < numberOfPriorBoxLayer; i++) for(int i = 0; i < numberOfPriorBoxLayer; i++)
{ {
// 分类 // 分类
vector<float> classificationOfEachLayer=classifications[i]; vector<float> classificationOfEachLayer = classifications[i];
for(int j=0;j<classificationOfEachLayer.size();++j) for(int j = 0; j < classificationOfEachLayer.size(); ++j)
{ {
(ssdParameter.classification[i])[j]=classificationOfEachLayer[j]*SSD_QUANT_BASE; (ssdParameter.classification[i])[j] = classificationOfEachLayer[j] * SSD_QUANT_BASE;
} }
// 回归 // 回归
vector<float> regressionOfEachLayer=regressions[i]; vector<float> regressionOfEachLayer = regressions[i];
for(int j=0;j<regressionOfEachLayer.size();++j) for(int j = 0; j < regressionOfEachLayer.size(); ++j)
{ {
(ssdParameter.regression[i])[j]=regressionOfEachLayer[j]*SSD_QUANT_BASE; (ssdParameter.regression[i])[j] = regressionOfEachLayer[j] * SSD_QUANT_BASE;
} }
} }
int* priorboxOutputData[SSD_MAX_PRIORBOX_LAYER_NUM]; int* priorboxOutputData[SSD_MAX_PRIORBOX_LAYER_NUM];
int* softMaxInputData[SSD_MAX_PRIORBOX_LAYER_NUM]; int* softMaxInputData[SSD_MAX_PRIORBOX_LAYER_NUM];
int* detectionLocData[SSD_MAX_PRIORBOX_LAYER_NUM]; int* detectionLocData[SSD_MAX_PRIORBOX_LAYER_NUM];
int* softMaxOutputData = NULL; int* softMaxOutputData = NULL;
int* detectionOutTmpBuf = NULL; int* detectionOutTmpBuf = NULL;
int softMaxWidth[SSD_MAX_PRIORBOX_LAYER_NUM]; int softMaxWidth[SSD_MAX_PRIORBOX_LAYER_NUM];
int size = 0; int size = 0;
int i = 0; int i = 0;
/////////////////////////////////// PriorBoxLayer:生成所有priorbox /////////////////////////////////// /////////////////////////////////// PriorBoxLayer:生成所有priorbox
//////////////////////////////////////
// 分配priorboxOutputData内存空间 // 分配priorboxOutputData内存空间
priorboxOutputData[0] = ssdParameter.priorboxOutputData; priorboxOutputData[0] = ssdParameter.priorboxOutputData;
for (i = 1; i < numberOfPriorBoxLayer; i++) for(i = 1; i < numberOfPriorBoxLayer; i++)
{ {
size=ssdParameter.softMaxInChn[i-1]/ssdParameter.classNum*SSD_COORDI_NUM*2; size = ssdParameter.softMaxInChn[i - 1] / ssdParameter.classNum * SSD_COORDI_NUM * 2;
priorboxOutputData[i] = priorboxOutputData[i - 1] + size; priorboxOutputData[i] = priorboxOutputData[i - 1] + size;
} }
for (i = 0; i < numberOfPriorBoxLayer; i++) for(i = 0; i < numberOfPriorBoxLayer; i++)
{ {
PriorBoxLayer(i,priorboxOutputData[i]); PriorBoxLayer(i, priorboxOutputData[i]);
} }
/////////////////////////////////// SoftmaxLayer:计算所有priorbox的置信度 /////////////////////////////////// /////////////////////////////////// SoftmaxLayer:计算所有priorbox的置信度
//////////////////////////////////////
// 分配softMaxOutputData内存空间 // 分配softMaxOutputData内存空间
softMaxOutputData =ssdParameter.softMaxOutputData; softMaxOutputData = ssdParameter.softMaxOutputData;
for(i = 0; i < numberOfPriorBoxLayer; i++) for(i = 0; i < numberOfPriorBoxLayer; i++)
{ {
softMaxInputData[i] = ssdParameter.classification[i]; softMaxInputData[i] = ssdParameter.classification[i];
softMaxWidth[i] = ssdParameter.convChannel[i*2+1]; softMaxWidth[i] = ssdParameter.convChannel[i * 2 + 1];
} }
SoftmaxLayer(softMaxWidth,softMaxInputData, softMaxOutputData); SoftmaxLayer(softMaxWidth, softMaxInputData, softMaxOutputData);
/////////////////////////////////// DetectionOutputLayer:对网络输出值解码并经过NMS得到最后的检测结果 /////////////////////////////////// ///////////////////////////////////
///DetectionOutputLayer:对网络输出值解码并经过NMS得到最后的检测结果
//////////////////////////////////////
// 分配DetectionOut内存空间 // 分配DetectionOut内存空间
detectionOutTmpBuf = ssdParameter.getResultBuffer; detectionOutTmpBuf = ssdParameter.getResultBuffer;
for(i = 0; i < numberOfPriorBoxLayer; i++) for(i = 0; i < numberOfPriorBoxLayer; i++)
{ {
detectionLocData[i] = ssdParameter.regression[i]; detectionLocData[i] = ssdParameter.regression[i];
} }
DetectionOutputLayer(detectionLocData, priorboxOutputData, softMaxOutputData,detectionOutTmpBuf); DetectionOutputLayer(
detectionLocData, priorboxOutputData, softMaxOutputData, detectionOutTmpBuf);
// 获取最后的检测结果 // 获取最后的检测结果
CreateDetectionResults(resultsOfDetection); CreateDetectionResults(resultsOfDetection);
} }
void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer, int* priorboxOutputData)
void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData)
{ {
// 参数赋值 // 参数赋值
int priorBoxWidth=ssdParameter.priorBoxWidth[indexOfLayer]; int priorBoxWidth = ssdParameter.priorBoxWidth[indexOfLayer];
int priorBoxHeight=ssdParameter.priorBoxHeight[indexOfLayer]; int priorBoxHeight = ssdParameter.priorBoxHeight[indexOfLayer];
int srcImageWidth=ssdParameter.srcImageWidth; int srcImageWidth = ssdParameter.srcImageWidth;
int srcImageHeight=ssdParameter.srcImageHeight; int srcImageHeight = ssdParameter.srcImageHeight;
vector<float> priorBoxMinSize=ssdParameter.priorBoxMinSize[indexOfLayer]; vector<float> priorBoxMinSize = ssdParameter.priorBoxMinSize[indexOfLayer];
int minSizeNum=ssdParameter.minSizeNum[indexOfLayer]; int minSizeNum = ssdParameter.minSizeNum[indexOfLayer];
vector<float> priorBoxMaxSize=ssdParameter.priorBoxMaxSize[indexOfLayer]; vector<float> priorBoxMaxSize = ssdParameter.priorBoxMaxSize[indexOfLayer];
int maxSizeNum=ssdParameter.maxSizeNum[indexOfLayer]; int maxSizeNum = ssdParameter.maxSizeNum[indexOfLayer];
int flip=ssdParameter.flip[indexOfLayer]; int flip = ssdParameter.flip[indexOfLayer];
int clip=ssdParameter.clip[indexOfLayer]; int clip = ssdParameter.clip[indexOfLayer];
int inputAspectRatioNum=ssdParameter.inputAspectRatioNum[indexOfLayer]; int inputAspectRatioNum = ssdParameter.inputAspectRatioNum[indexOfLayer];
vector<float> priorBoxAspectRatio=ssdParameter.priorBoxAspectRatio[indexOfLayer]; vector<float> priorBoxAspectRatio = ssdParameter.priorBoxAspectRatio[indexOfLayer];
float priorBoxStepWidth=ssdParameter.priorBoxStepWidth[indexOfLayer]; float priorBoxStepWidth = ssdParameter.priorBoxStepWidth[indexOfLayer];
float priorBoxStepHeight= ssdParameter.priorBoxStepHeight[indexOfLayer]; float priorBoxStepHeight = ssdParameter.priorBoxStepHeight[indexOfLayer];
float offset=ssdParameter.offset; float offset = ssdParameter.offset;
int *priorBoxVar=ssdParameter.priorBoxVar; int* priorBoxVar = ssdParameter.priorBoxVar;
int aspectRatioNum = 0; int aspectRatioNum = 0;
int index = 0; int index = 0;
float aspectRatio[SSD_ASPECT_RATIO_NUM] = { 0 }; float aspectRatio[SSD_ASPECT_RATIO_NUM] = {0};
int numPrior = 0; int numPrior = 0;
float centerX = 0; float centerX = 0;
float centerY = 0; float centerY = 0;
float boxHeight = 0; float boxHeight = 0;
float boxWidth = 0; float boxWidth = 0;
float maxBoxWidth = 0; float maxBoxWidth = 0;
int i = 0; int i = 0;
int j = 0; int j = 0;
int n = 0; int n = 0;
int h = 0; int h = 0;
int w = 0; int w = 0;
aspectRatioNum = 0; aspectRatioNum = 0;
aspectRatio[0] = 1; aspectRatio[0] = 1;
aspectRatioNum++; aspectRatioNum++;
for (i = 0; i < inputAspectRatioNum; i++) for(i = 0; i < inputAspectRatioNum; i++)
{ {
aspectRatio[aspectRatioNum++] = priorBoxAspectRatio[i]; aspectRatio[aspectRatioNum++] = priorBoxAspectRatio[i];
if (flip) if(flip)
{ {
aspectRatio[aspectRatioNum++] = 1.0f / priorBoxAspectRatio[i]; aspectRatio[aspectRatioNum++] = 1.0f / priorBoxAspectRatio[i];
} }
...@@ -568,28 +575,28 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData) ...@@ -568,28 +575,28 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData)
numPrior = minSizeNum * aspectRatioNum + maxSizeNum; numPrior = minSizeNum * aspectRatioNum + maxSizeNum;
index = 0; index = 0;
for (h = 0; h < priorBoxHeight; h++) for(h = 0; h < priorBoxHeight; h++)
{ {
for (w = 0; w < priorBoxWidth; w++) for(w = 0; w < priorBoxWidth; w++)
{ {
centerX = (w + offset) * priorBoxStepWidth; centerX = (w + offset) * priorBoxStepWidth;
centerY = (h + offset) * priorBoxStepHeight; centerY = (h + offset) * priorBoxStepHeight;
for (n = 0; n < minSizeNum; n++) for(n = 0; n < minSizeNum; n++)
{ {
// 首先产生宽高比为1的priorbox // 首先产生宽高比为1的priorbox
boxHeight = priorBoxMinSize[n]; boxHeight = priorBoxMinSize[n];
boxWidth = priorBoxMinSize[n]; boxWidth = priorBoxMinSize[n];
priorboxOutputData[index++] = (int)(centerX - boxWidth * SSD_HALF); priorboxOutputData[index++] = (int)(centerX - boxWidth * SSD_HALF);
priorboxOutputData[index++] = (int)(centerY - boxHeight * SSD_HALF); priorboxOutputData[index++] = (int)(centerY - boxHeight * SSD_HALF);
priorboxOutputData[index++] = (int)(centerX + boxWidth * SSD_HALF); priorboxOutputData[index++] = (int)(centerX + boxWidth * SSD_HALF);
priorboxOutputData[index++] = (int)(centerY + boxHeight * SSD_HALF); priorboxOutputData[index++] = (int)(centerY + boxHeight * SSD_HALF);
// 对于max_size,生成宽高比为1的priorbox,宽高为sqrt(min_size * max_size) // 对于max_size,生成宽高比为1的priorbox,宽高为sqrt(min_size * max_size)
if(maxSizeNum>0) if(maxSizeNum > 0)
{ {
maxBoxWidth = sqrt(priorBoxMinSize[n] * priorBoxMaxSize[n]); maxBoxWidth = sqrt(priorBoxMinSize[n] * priorBoxMaxSize[n]);
boxHeight = maxBoxWidth; boxHeight = maxBoxWidth;
boxWidth = maxBoxWidth; boxWidth = maxBoxWidth;
priorboxOutputData[index++] = (int)(centerX - boxWidth * SSD_HALF); priorboxOutputData[index++] = (int)(centerX - boxWidth * SSD_HALF);
priorboxOutputData[index++] = (int)(centerY - boxHeight * SSD_HALF); priorboxOutputData[index++] = (int)(centerY - boxHeight * SSD_HALF);
priorboxOutputData[index++] = (int)(centerX + boxWidth * SSD_HALF); priorboxOutputData[index++] = (int)(centerX + boxWidth * SSD_HALF);
...@@ -597,10 +604,10 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData) ...@@ -597,10 +604,10 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData)
} }
// 剩下的priorbox // 剩下的priorbox
for (i = 1; i < aspectRatioNum; i++) for(i = 1; i < aspectRatioNum; i++)
{ {
boxWidth = (float)(priorBoxMinSize[n] * sqrt( aspectRatio[i] )); boxWidth = (float)(priorBoxMinSize[n] * sqrt(aspectRatio[i]));
boxHeight = (float)(priorBoxMinSize[n]/sqrt( aspectRatio[i] )); boxHeight = (float)(priorBoxMinSize[n] / sqrt(aspectRatio[i]));
priorboxOutputData[index++] = (int)(centerX - boxWidth * SSD_HALF); priorboxOutputData[index++] = (int)(centerX - boxWidth * SSD_HALF);
priorboxOutputData[index++] = (int)(centerY - boxHeight * SSD_HALF); priorboxOutputData[index++] = (int)(centerY - boxHeight * SSD_HALF);
...@@ -611,23 +618,25 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData) ...@@ -611,23 +618,25 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData)
} }
} }
// 越界处理 [0, srcImageWidth] & [0, srcImageHeight] // 越界处理 [0, srcImageWidth] & [0, srcImageHeight]
if (clip) if(clip)
{ {
for (i = 0; i < (int)(priorBoxWidth * priorBoxHeight * SSD_COORDI_NUM*numPrior / 2); i++) for(i = 0; i < (int)(priorBoxWidth * priorBoxHeight * SSD_COORDI_NUM * numPrior / 2); i++)
{ {
priorboxOutputData[2 * i] = SSD_MIN((int)SSD_MAX(priorboxOutputData[2 * i], 0), srcImageWidth); priorboxOutputData[2 * i] =
priorboxOutputData[2 * i + 1] = SSD_MIN((int)SSD_MAX(priorboxOutputData[2 * i + 1], 0), srcImageHeight); SSD_MIN((int)SSD_MAX(priorboxOutputData[2 * i], 0), srcImageWidth);
priorboxOutputData[2 * i + 1] =
SSD_MIN((int)SSD_MAX(priorboxOutputData[2 * i + 1], 0), srcImageHeight);
} }
} }
// var // var
for (h = 0; h < priorBoxHeight; h++) for(h = 0; h < priorBoxHeight; h++)
{ {
for (w = 0; w < priorBoxWidth; w++) for(w = 0; w < priorBoxWidth; w++)
{ {
for (i = 0; i < numPrior; i++) for(i = 0; i < numPrior; i++)
{ {
for (j = 0; j < SSD_COORDI_NUM; j++) for(j = 0; j < SSD_COORDI_NUM; j++)
{ {
priorboxOutputData[index++] = (int)priorBoxVar[j]; priorboxOutputData[index++] = (int)priorBoxVar[j];
} }
...@@ -636,38 +645,40 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData) ...@@ -636,38 +645,40 @@ void DetectorRetinaFace::PriorBoxLayer(int indexOfLayer,int* priorboxOutputData)
} }
} }
void DetectorRetinaFace::SoftmaxLayer(int softMaxWidth[],int* softMaxInputData[], int* softMaxOutputData) void DetectorRetinaFace::SoftmaxLayer(int softMaxWidth[],
int* softMaxInputData[],
int* softMaxOutputData)
{ {
// 参数赋值 // 参数赋值
int softMaxInHeight=ssdParameter.softMaxInHeight; int softMaxInHeight = ssdParameter.softMaxInHeight;
int *softMaxInChn=ssdParameter.softMaxInChn; int* softMaxInChn = ssdParameter.softMaxInChn;
int concatNum=ssdParameter.concatNum; int concatNum = ssdParameter.concatNum;
int *convStride=ssdParameter.convStride; int* convStride = ssdParameter.convStride;
int* inputData = NULL; int* inputData = NULL;
int* outputTmp = NULL; int* outputTmp = NULL;
int outerNum = 0; int outerNum = 0;
int innerNum = 0; int innerNum = 0;
int inputChannel = 0; int inputChannel = 0;
int i = 0; int i = 0;
int concatCnt = 0; int concatCnt = 0;
int stride = 0; int stride = 0;
int skip = 0; int skip = 0;
int left = 0; int left = 0;
outputTmp = softMaxOutputData; outputTmp = softMaxOutputData;
for (concatCnt = 0; concatCnt < concatNum; concatCnt++) for(concatCnt = 0; concatCnt < concatNum; concatCnt++)
{ {
inputData = softMaxInputData[concatCnt]; inputData = softMaxInputData[concatCnt];
stride = convStride[concatCnt]; stride = convStride[concatCnt];
inputChannel = softMaxInChn[concatCnt]; inputChannel = softMaxInChn[concatCnt];
outerNum = inputChannel / softMaxInHeight; outerNum = inputChannel / softMaxInHeight;
innerNum = softMaxInHeight; innerNum = softMaxInHeight;
skip = softMaxWidth[concatCnt] / innerNum; skip = softMaxWidth[concatCnt] / innerNum;
left = stride - softMaxWidth[concatCnt]; left = stride - softMaxWidth[concatCnt];
for (i = 0; i < outerNum; i++) for(i = 0; i < outerNum; i++)
{ {
ComputeSoftMax(inputData, (int)innerNum,outputTmp); ComputeSoftMax(inputData, (int)innerNum, outputTmp);
inputData += innerNum; inputData += innerNum;
outputTmp += innerNum; outputTmp += innerNum;
} }
...@@ -678,71 +689,73 @@ void DetectorRetinaFace::ComputeSoftMax(int* src, int size, int* dst) ...@@ -678,71 +689,73 @@ void DetectorRetinaFace::ComputeSoftMax(int* src, int size, int* dst)
{ {
int max = 0; int max = 0;
int sum = 0; int sum = 0;
int i = 0; int i = 0;
for (i = 0; i < size; ++i) for(i = 0; i < size; ++i)
{ {
if (max < src[i]) if(max < src[i])
{ {
max = src[i]; max = src[i];
} }
} }
for (i = 0; i < size; ++i) for(i = 0; i < size; ++i)
{ {
dst[i] = (int)(SSD_QUANT_BASE* exp((float)(src[i] - max) / SSD_QUANT_BASE)); dst[i] = (int)(SSD_QUANT_BASE * exp((float)(src[i] - max) / SSD_QUANT_BASE));
sum += dst[i]; sum += dst[i];
} }
for (i = 0; i < size; ++i) for(i = 0; i < size; ++i)
{ {
dst[i] = (int)(((float)dst[i] / (float)sum) * SSD_QUANT_BASE); dst[i] = (int)(((float)dst[i] / (float)sum) * SSD_QUANT_BASE);
} }
} }
void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorBoxes[],int* confScores, int* assistMemPool) void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[],
int* allPriorBoxes[],
int* confScores,
int* assistMemPool)
{ {
// 参数赋值 // 参数赋值
int concatNum=ssdParameter.concatNum; int concatNum = ssdParameter.concatNum;
int confThresh=ssdParameter.confThresh; int confThresh = ssdParameter.confThresh;
int classNum=ssdParameter.classNum; int classNum = ssdParameter.classNum;
int topK=ssdParameter.topK; int topK = ssdParameter.topK;
int keepTopK=ssdParameter.keepTopK; int keepTopK = ssdParameter.keepTopK;
int NMSThresh=ssdParameter.NMSThresh; int NMSThresh = ssdParameter.NMSThresh;
int *detectInputChn=ssdParameter.detectInputChn; int* detectInputChn = ssdParameter.detectInputChn;
int* dstScoreSrc=ssdParameter.dstScore; int* dstScoreSrc = ssdParameter.dstScore;
int* dstBboxSrc=ssdParameter.dstRoi; int* dstBboxSrc = ssdParameter.dstRoi;
int* roiOutCntSrc=ssdParameter.classRoiNum; int* roiOutCntSrc = ssdParameter.classRoiNum;
int* locPreds = NULL; int* locPreds = NULL;
int* priorBoxes = NULL; int* priorBoxes = NULL;
int* priorVar = NULL; int* priorVar = NULL;
int* allDecodeBoxes = NULL; int* allDecodeBoxes = NULL;
int* dstScore = NULL; int* dstScore = NULL;
int* dstBbox = NULL; int* dstBbox = NULL;
int* classRoiNum = NULL; int* classRoiNum = NULL;
int roiOutCnt = 0; int roiOutCnt = 0;
int* singleProposal = NULL; int* singleProposal = NULL;
int* afterTopK = NULL; int* afterTopK = NULL;
QuickSortStack* stack = NULL; QuickSortStack* stack = NULL;
int priorNum = 0; int priorNum = 0;
int numPredsPerClass = 0; int numPredsPerClass = 0;
float priorWidth = 0; float priorWidth = 0;
float priorHeight = 0; float priorHeight = 0;
float priorCenterX = 0; float priorCenterX = 0;
float priorCenterY = 0; float priorCenterY = 0;
float decodeBoxCenterX = 0; float decodeBoxCenterX = 0;
float decodeBoxCenterY = 0; float decodeBoxCenterY = 0;
float decodeBoxWidth = 0; float decodeBoxWidth = 0;
float decodeBoxHeight = 0; float decodeBoxHeight = 0;
int srcIdx = 0; int srcIdx = 0;
int afterFilter = 0; int afterFilter = 0;
int afterTopK2 = 0; int afterTopK2 = 0;
int keepCnt = 0; int keepCnt = 0;
int i = 0; int i = 0;
int j = 0; int j = 0;
int offset = 0; int offset = 0;
priorNum = 0; priorNum = 0;
for (i = 0; i < concatNum; i++) for(i = 0; i < concatNum; i++)
{ {
priorNum += detectInputChn[i] / SSD_COORDI_NUM; priorNum += detectInputChn[i] / SSD_COORDI_NUM;
} }
...@@ -750,36 +763,47 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB ...@@ -750,36 +763,47 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB
// 缓存 // 缓存
allDecodeBoxes = assistMemPool; allDecodeBoxes = assistMemPool;
singleProposal = allDecodeBoxes + priorNum * SSD_COORDI_NUM; singleProposal = allDecodeBoxes + priorNum * SSD_COORDI_NUM;
afterTopK = singleProposal + SSD_PROPOSAL_WIDTH * priorNum; afterTopK = singleProposal + SSD_PROPOSAL_WIDTH * priorNum;
stack = (QuickSortStack*)(afterTopK + priorNum * SSD_PROPOSAL_WIDTH); stack = (QuickSortStack*)(afterTopK + priorNum * SSD_PROPOSAL_WIDTH);
srcIdx = 0; srcIdx = 0;
for (i = 0; i < concatNum; i++) for(i = 0; i < concatNum; i++)
{ {
// 回归预测值 // 回归预测值
locPreds = allLocPreds[i]; locPreds = allLocPreds[i];
numPredsPerClass = detectInputChn[i] / SSD_COORDI_NUM; numPredsPerClass = detectInputChn[i] / SSD_COORDI_NUM;
// 获取priorbox // 获取priorbox
priorBoxes = allPriorBoxes[i]; priorBoxes = allPriorBoxes[i];
priorVar = priorBoxes + numPredsPerClass*SSD_COORDI_NUM; priorVar = priorBoxes + numPredsPerClass * SSD_COORDI_NUM;
for (j = 0; j < numPredsPerClass; j++) for(j = 0; j < numPredsPerClass; j++)
{ {
priorWidth = (float)(priorBoxes[j*SSD_COORDI_NUM+2] - priorBoxes[j*SSD_COORDI_NUM]); priorWidth =
priorHeight = (float)(priorBoxes[j*SSD_COORDI_NUM+3] - priorBoxes[j*SSD_COORDI_NUM + 1]); (float)(priorBoxes[j * SSD_COORDI_NUM + 2] - priorBoxes[j * SSD_COORDI_NUM]);
priorCenterX = (priorBoxes[j*SSD_COORDI_NUM+2] + priorBoxes[j*SSD_COORDI_NUM])*SSD_HALF; priorHeight =
priorCenterY = (priorBoxes[j*SSD_COORDI_NUM+3] + priorBoxes[j*SSD_COORDI_NUM+1])*SSD_HALF; (float)(priorBoxes[j * SSD_COORDI_NUM + 3] - priorBoxes[j * SSD_COORDI_NUM + 1]);
priorCenterX =
decodeBoxCenterX = ((float)priorVar[j*SSD_COORDI_NUM]/SSD_QUANT_BASE)* (priorBoxes[j * SSD_COORDI_NUM + 2] + priorBoxes[j * SSD_COORDI_NUM]) * SSD_HALF;
((float)locPreds[j*SSD_COORDI_NUM]/SSD_QUANT_BASE)*priorWidth+priorCenterX; priorCenterY =
(priorBoxes[j * SSD_COORDI_NUM + 3] + priorBoxes[j * SSD_COORDI_NUM + 1]) *
decodeBoxCenterY = ((float)priorVar[j*SSD_COORDI_NUM+1]/SSD_QUANT_BASE)* SSD_HALF;
((float)locPreds[j*SSD_COORDI_NUM+1]/SSD_QUANT_BASE)*priorHeight+priorCenterY;
decodeBoxCenterX = ((float)priorVar[j * SSD_COORDI_NUM] / SSD_QUANT_BASE) *
decodeBoxWidth = exp(((float)priorVar[j*SSD_COORDI_NUM+2]/SSD_QUANT_BASE)* ((float)locPreds[j * SSD_COORDI_NUM] / SSD_QUANT_BASE) *
((float)locPreds[j*SSD_COORDI_NUM+2]/SSD_QUANT_BASE))*priorWidth; priorWidth +
priorCenterX;
decodeBoxHeight = exp(((float)priorVar[j*SSD_COORDI_NUM+3]/SSD_QUANT_BASE)*
((float)locPreds[j*SSD_COORDI_NUM+3]/SSD_QUANT_BASE))*priorHeight; decodeBoxCenterY = ((float)priorVar[j * SSD_COORDI_NUM + 1] / SSD_QUANT_BASE) *
((float)locPreds[j * SSD_COORDI_NUM + 1] / SSD_QUANT_BASE) *
priorHeight +
priorCenterY;
decodeBoxWidth = exp(((float)priorVar[j * SSD_COORDI_NUM + 2] / SSD_QUANT_BASE) *
((float)locPreds[j * SSD_COORDI_NUM + 2] / SSD_QUANT_BASE)) *
priorWidth;
decodeBoxHeight = exp(((float)priorVar[j * SSD_COORDI_NUM + 3] / SSD_QUANT_BASE) *
((float)locPreds[j * SSD_COORDI_NUM + 3] / SSD_QUANT_BASE)) *
priorHeight;
allDecodeBoxes[srcIdx++] = (int)(decodeBoxCenterX - decodeBoxWidth * SSD_HALF); allDecodeBoxes[srcIdx++] = (int)(decodeBoxCenterX - decodeBoxWidth * SSD_HALF);
allDecodeBoxes[srcIdx++] = (int)(decodeBoxCenterY - decodeBoxHeight * SSD_HALF); allDecodeBoxes[srcIdx++] = (int)(decodeBoxCenterY - decodeBoxHeight * SSD_HALF);
...@@ -790,39 +814,42 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB ...@@ -790,39 +814,42 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB
// 对每一类做NMS // 对每一类做NMS
afterTopK2 = 0; afterTopK2 = 0;
for (i = 0; i < classNum; i++) for(i = 0; i < classNum; i++)
{ {
if(i==0) if(i == 0)
continue; continue;
for (j = 0; j < priorNum; j++) for(j = 0; j < priorNum; j++)
{ {
singleProposal[j * SSD_PROPOSAL_WIDTH] = allDecodeBoxes[j * SSD_COORDI_NUM]; singleProposal[j * SSD_PROPOSAL_WIDTH] = allDecodeBoxes[j * SSD_COORDI_NUM];
singleProposal[j * SSD_PROPOSAL_WIDTH + 1] = allDecodeBoxes[j * SSD_COORDI_NUM + 1]; singleProposal[j * SSD_PROPOSAL_WIDTH + 1] = allDecodeBoxes[j * SSD_COORDI_NUM + 1];
singleProposal[j * SSD_PROPOSAL_WIDTH + 2] = allDecodeBoxes[j * SSD_COORDI_NUM + 2]; singleProposal[j * SSD_PROPOSAL_WIDTH + 2] = allDecodeBoxes[j * SSD_COORDI_NUM + 2];
singleProposal[j * SSD_PROPOSAL_WIDTH + 3] = allDecodeBoxes[j * SSD_COORDI_NUM + 3]; singleProposal[j * SSD_PROPOSAL_WIDTH + 3] = allDecodeBoxes[j * SSD_COORDI_NUM + 3];
singleProposal[j * SSD_PROPOSAL_WIDTH + 4] = confScores[j*classNum + i]; singleProposal[j * SSD_PROPOSAL_WIDTH + 4] = confScores[j * classNum + i];
singleProposal[j * SSD_PROPOSAL_WIDTH + 5] = 0; singleProposal[j * SSD_PROPOSAL_WIDTH + 5] = 0;
} }
QuickSort(singleProposal, 0, priorNum - 1, stack,topK); QuickSort(singleProposal, 0, priorNum - 1, stack, topK);
afterFilter = (priorNum < topK) ? priorNum : topK; afterFilter = (priorNum < topK) ? priorNum : topK;
NonMaxSuppression(singleProposal, afterFilter, NMSThresh, afterFilter); NonMaxSuppression(singleProposal, afterFilter, NMSThresh, afterFilter);
roiOutCnt = 0; roiOutCnt = 0;
dstScore = (int*)dstScoreSrc; dstScore = (int*)dstScoreSrc;
dstBbox = (int*)dstBboxSrc; dstBbox = (int*)dstBboxSrc;
classRoiNum = (int*)roiOutCntSrc; classRoiNum = (int*)roiOutCntSrc;
dstScore += (int)afterTopK2; dstScore += (int)afterTopK2;
dstBbox += (int)(afterTopK2 * SSD_COORDI_NUM); dstBbox += (int)(afterTopK2 * SSD_COORDI_NUM);
for (j = 0; j < topK; j++) for(j = 0; j < topK; j++)
{ {
if (singleProposal[j * SSD_PROPOSAL_WIDTH + 5] == 0 && if(singleProposal[j * SSD_PROPOSAL_WIDTH + 5] == 0 &&
singleProposal[j * SSD_PROPOSAL_WIDTH + 4] > (int)confThresh) singleProposal[j * SSD_PROPOSAL_WIDTH + 4] > (int)confThresh)
{ {
dstScore[roiOutCnt] = singleProposal[j * 6 + 4]; dstScore[roiOutCnt] = singleProposal[j * 6 + 4];
dstBbox[roiOutCnt * SSD_COORDI_NUM] = singleProposal[j * SSD_PROPOSAL_WIDTH]; dstBbox[roiOutCnt * SSD_COORDI_NUM] = singleProposal[j * SSD_PROPOSAL_WIDTH];
dstBbox[roiOutCnt * SSD_COORDI_NUM + 1] = singleProposal[j * SSD_PROPOSAL_WIDTH + 1]; dstBbox[roiOutCnt * SSD_COORDI_NUM + 1] =
dstBbox[roiOutCnt * SSD_COORDI_NUM + 2] = singleProposal[j * SSD_PROPOSAL_WIDTH + 2]; singleProposal[j * SSD_PROPOSAL_WIDTH + 1];
dstBbox[roiOutCnt * SSD_COORDI_NUM + 3] = singleProposal[j * SSD_PROPOSAL_WIDTH + 3]; dstBbox[roiOutCnt * SSD_COORDI_NUM + 2] =
singleProposal[j * SSD_PROPOSAL_WIDTH + 2];
dstBbox[roiOutCnt * SSD_COORDI_NUM + 3] =
singleProposal[j * SSD_PROPOSAL_WIDTH + 3];
roiOutCnt++; roiOutCnt++;
} }
} }
...@@ -831,20 +858,20 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB ...@@ -831,20 +858,20 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB
} }
keepCnt = 0; keepCnt = 0;
offset = 0; offset = 0;
if (afterTopK2 > keepTopK) if(afterTopK2 > keepTopK)
{ {
offset = classRoiNum[0]; offset = classRoiNum[0];
for (i = 1; i < classNum; i++) for(i = 1; i < classNum; i++)
{ {
dstScore = (int*)dstScoreSrc; dstScore = (int*)dstScoreSrc;
dstBbox = (int*)dstBboxSrc; dstBbox = (int*)dstBboxSrc;
classRoiNum = (int*)roiOutCntSrc; classRoiNum = (int*)roiOutCntSrc;
dstScore += (int)(offset); dstScore += (int)(offset);
dstBbox += (int)(offset * SSD_COORDI_NUM); dstBbox += (int)(offset * SSD_COORDI_NUM);
for (j = 0; j < (int)classRoiNum[i]; j++) for(j = 0; j < (int)classRoiNum[i]; j++)
{ {
afterTopK[keepCnt * SSD_PROPOSAL_WIDTH] = dstBbox[j * SSD_COORDI_NUM]; afterTopK[keepCnt * SSD_PROPOSAL_WIDTH] = dstBbox[j * SSD_COORDI_NUM];
afterTopK[keepCnt * SSD_PROPOSAL_WIDTH + 1] = dstBbox[j * SSD_COORDI_NUM + 1]; afterTopK[keepCnt * SSD_PROPOSAL_WIDTH + 1] = dstBbox[j * SSD_COORDI_NUM + 1];
afterTopK[keepCnt * SSD_PROPOSAL_WIDTH + 2] = dstBbox[j * SSD_COORDI_NUM + 2]; afterTopK[keepCnt * SSD_PROPOSAL_WIDTH + 2] = dstBbox[j * SSD_COORDI_NUM + 2];
afterTopK[keepCnt * SSD_PROPOSAL_WIDTH + 3] = dstBbox[j * SSD_COORDI_NUM + 3]; afterTopK[keepCnt * SSD_PROPOSAL_WIDTH + 3] = dstBbox[j * SSD_COORDI_NUM + 3];
...@@ -854,24 +881,24 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB ...@@ -854,24 +881,24 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB
} }
offset = offset + classRoiNum[i]; offset = offset + classRoiNum[i];
} }
QuickSort(afterTopK, 0, keepCnt - 1, stack,keepCnt); QuickSort(afterTopK, 0, keepCnt - 1, stack, keepCnt);
offset = 0; offset = 0;
offset = classRoiNum[0]; offset = classRoiNum[0];
for (i = 1; i < classNum; i++) for(i = 1; i < classNum; i++)
{ {
roiOutCnt = 0; roiOutCnt = 0;
dstScore = (int*)dstScoreSrc; dstScore = (int*)dstScoreSrc;
dstBbox = (int*)dstBboxSrc; dstBbox = (int*)dstBboxSrc;
classRoiNum = (int*)roiOutCntSrc; classRoiNum = (int*)roiOutCntSrc;
dstScore += (int)(offset); dstScore += (int)(offset);
dstBbox += (int)(offset * SSD_COORDI_NUM); dstBbox += (int)(offset * SSD_COORDI_NUM);
for (j = 0; j < keepTopK; j++) for(j = 0; j < keepTopK; j++)
{ {
if (afterTopK[j * SSD_PROPOSAL_WIDTH + 5] == i) if(afterTopK[j * SSD_PROPOSAL_WIDTH + 5] == i)
{ {
dstScore[roiOutCnt] = afterTopK[j * SSD_PROPOSAL_WIDTH + 4]; dstScore[roiOutCnt] = afterTopK[j * SSD_PROPOSAL_WIDTH + 4];
dstBbox[roiOutCnt * SSD_COORDI_NUM] = afterTopK[j * SSD_PROPOSAL_WIDTH]; dstBbox[roiOutCnt * SSD_COORDI_NUM] = afterTopK[j * SSD_PROPOSAL_WIDTH];
dstBbox[roiOutCnt * SSD_COORDI_NUM + 1] = afterTopK[j * SSD_PROPOSAL_WIDTH + 1]; dstBbox[roiOutCnt * SSD_COORDI_NUM + 1] = afterTopK[j * SSD_PROPOSAL_WIDTH + 1];
dstBbox[roiOutCnt * SSD_COORDI_NUM + 2] = afterTopK[j * SSD_PROPOSAL_WIDTH + 2]; dstBbox[roiOutCnt * SSD_COORDI_NUM + 2] = afterTopK[j * SSD_PROPOSAL_WIDTH + 2];
dstBbox[roiOutCnt * SSD_COORDI_NUM + 3] = afterTopK[j * SSD_PROPOSAL_WIDTH + 3]; dstBbox[roiOutCnt * SSD_COORDI_NUM + 3] = afterTopK[j * SSD_PROPOSAL_WIDTH + 3];
...@@ -884,40 +911,40 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB ...@@ -884,40 +911,40 @@ void DetectorRetinaFace::DetectionOutputLayer(int* allLocPreds[], int* allPriorB
} }
} }
vector<float> DetectorRetinaFace::PermuteLayer(const vector<float> &data,int width,int height,int channels) vector<float>
DetectorRetinaFace::PermuteLayer(const vector<float>& data, int width, int height, int channels)
{ {
vector<float> result(data.size()); vector<float> result(data.size());
int index=0; int index = 0;
int channelStep=width*height; int channelStep = width * height;
for(int h=0; h<height;h++) for(int h = 0; h < height; h++)
{ {
for(int w=0;w<width;w++) for(int w = 0; w < width; w++)
{ {
for(int c = 0;c < channels;c++) for(int c = 0; c < channels; c++)
{ {
result[index++] = data[c*channelStep + h*width + w]; result[index++] = data[c * channelStep + h * width + w];
} }
} }
} }
return result; return result;
} }
void DetectorRetinaFace::QuickSort(int* src,int low, int high, QuickSortStack *stack,int maxNum) void DetectorRetinaFace::QuickSort(int* src, int low, int high, QuickSortStack* stack, int maxNum)
{ {
int i = low; int i = low;
int j = high; int j = high;
int top = 0; int top = 0;
int keyConfidence = src[SSD_PROPOSAL_WIDTH * low + 4]; int keyConfidence = src[SSD_PROPOSAL_WIDTH * low + 4];
stack[top].min = low; stack[top].min = low;
stack[top].max = high; stack[top].max = high;
while(top > -1) while(top > -1)
{ {
low = stack[top].min; low = stack[top].min;
high = stack[top].max; high = stack[top].max;
i = low; i = low;
j = high; j = high;
top--; top--;
keyConfidence = src[SSD_PROPOSAL_WIDTH * low + 4]; keyConfidence = src[SSD_PROPOSAL_WIDTH * low + 4];
...@@ -930,88 +957,102 @@ void DetectorRetinaFace::QuickSort(int* src,int low, int high, QuickSortStack *s ...@@ -930,88 +957,102 @@ void DetectorRetinaFace::QuickSort(int* src,int low, int high, QuickSortStack *s
} }
if(i < j) if(i < j)
{ {
Swap(&src[i*SSD_PROPOSAL_WIDTH], &src[j*SSD_PROPOSAL_WIDTH]); Swap(&src[i * SSD_PROPOSAL_WIDTH], &src[j * SSD_PROPOSAL_WIDTH]);
i++; i++;
} }
while((i < j) && (keyConfidence < src[i*SSD_PROPOSAL_WIDTH + 4])) while((i < j) && (keyConfidence < src[i * SSD_PROPOSAL_WIDTH + 4]))
{ {
i++; i++;
} }
if(i < j) if(i < j)
{ {
Swap(&src[i*SSD_PROPOSAL_WIDTH], &src[j*SSD_PROPOSAL_WIDTH]); Swap(&src[i * SSD_PROPOSAL_WIDTH], &src[j * SSD_PROPOSAL_WIDTH]);
j--; j--;
} }
} }
if(low <= maxNum) if(low <= maxNum)
{ {
if(low < i-1) if(low < i - 1)
{ {
top++; top++;
stack[top].min = low; stack[top].min = low;
stack[top].max = i-1; stack[top].max = i - 1;
} }
if(high > i+1) if(high > i + 1)
{ {
top++; top++;
stack[top].min = i+1; stack[top].min = i + 1;
stack[top].max = high; stack[top].max = high;
} }
} }
} }
} }
void DetectorRetinaFace::NonMaxSuppression( int* proposals, int anchorsNum,int NMSThresh,int maxRoiNum) void DetectorRetinaFace::NonMaxSuppression(int* proposals,
int anchorsNum,
int NMSThresh,
int maxRoiNum)
{ {
int xMin1 = 0; int xMin1 = 0;
int yMin1 = 0; int yMin1 = 0;
int xMax1 = 0; int xMax1 = 0;
int yMax1 = 0; int yMax1 = 0;
int xMin2 = 0; int xMin2 = 0;
int yMin2 = 0; int yMin2 = 0;
int xMax2 = 0; int xMax2 = 0;
int yMax2 = 0; int yMax2 = 0;
int areaTotal = 0; int areaTotal = 0;
int areaInter = 0; int areaInter = 0;
int i = 0; int i = 0;
int j = 0; int j = 0;
int num = 0; int num = 0;
int NoOverlap = 1; int NoOverlap = 1;
for (i = 0; i < anchorsNum && num < maxRoiNum; i++) for(i = 0; i < anchorsNum && num < maxRoiNum; i++)
{ {
if( proposals[SSD_PROPOSAL_WIDTH*i+5] == 0 ) if(proposals[SSD_PROPOSAL_WIDTH * i + 5] == 0)
{ {
num++; num++;
xMin1 = proposals[SSD_PROPOSAL_WIDTH*i]; xMin1 = proposals[SSD_PROPOSAL_WIDTH * i];
yMin1 = proposals[SSD_PROPOSAL_WIDTH*i+1]; yMin1 = proposals[SSD_PROPOSAL_WIDTH * i + 1];
xMax1 = proposals[SSD_PROPOSAL_WIDTH*i+2]; xMax1 = proposals[SSD_PROPOSAL_WIDTH * i + 2];
yMax1 = proposals[SSD_PROPOSAL_WIDTH*i+3]; yMax1 = proposals[SSD_PROPOSAL_WIDTH * i + 3];
for(j= i+1;j< anchorsNum; j++) for(j = i + 1; j < anchorsNum; j++)
{ {
if( proposals[SSD_PROPOSAL_WIDTH*j+5] == 0 ) if(proposals[SSD_PROPOSAL_WIDTH * j + 5] == 0)
{ {
xMin2 = proposals[SSD_PROPOSAL_WIDTH*j]; xMin2 = proposals[SSD_PROPOSAL_WIDTH * j];
yMin2 = proposals[SSD_PROPOSAL_WIDTH*j+1]; yMin2 = proposals[SSD_PROPOSAL_WIDTH * j + 1];
xMax2 = proposals[SSD_PROPOSAL_WIDTH*j+2]; xMax2 = proposals[SSD_PROPOSAL_WIDTH * j + 2];
yMax2 = proposals[SSD_PROPOSAL_WIDTH*j+3]; yMax2 = proposals[SSD_PROPOSAL_WIDTH * j + 3];
NoOverlap = (xMin2>xMax1)||(xMax2<xMin1)||(yMin2>yMax1)||(yMax2<yMin1); NoOverlap =
(xMin2 > xMax1) || (xMax2 < xMin1) || (yMin2 > yMax1) || (yMax2 < yMin1);
if(NoOverlap) if(NoOverlap)
{ {
continue; continue;
} }
ComputeOverlap(xMin1, yMin1, xMax1, yMax1, xMin2, yMin2, xMax2, yMax2, &areaTotal, &areaInter); ComputeOverlap(xMin1,
if(areaInter*SSD_QUANT_BASE > ((int)NMSThresh*areaTotal)) yMin1,
xMax1,
yMax1,
xMin2,
yMin2,
xMax2,
yMax2,
&areaTotal,
&areaInter);
if(areaInter * SSD_QUANT_BASE > ((int)NMSThresh * areaTotal))
{ {
if( proposals[SSD_PROPOSAL_WIDTH*i+4] >= proposals[SSD_PROPOSAL_WIDTH*j+4] ) if(proposals[SSD_PROPOSAL_WIDTH * i + 4] >=
proposals[SSD_PROPOSAL_WIDTH * j + 4])
{ {
proposals[SSD_PROPOSAL_WIDTH*j+5] = 1; proposals[SSD_PROPOSAL_WIDTH * j + 5] = 1;
} }
else else
{ {
proposals[SSD_PROPOSAL_WIDTH*i+5] = 1; proposals[SSD_PROPOSAL_WIDTH * i + 5] = 1;
} }
} }
} }
...@@ -1020,19 +1061,27 @@ void DetectorRetinaFace::NonMaxSuppression( int* proposals, int anchorsNum,int N ...@@ -1020,19 +1061,27 @@ void DetectorRetinaFace::NonMaxSuppression( int* proposals, int anchorsNum,int N
} }
} }
void DetectorRetinaFace::ComputeOverlap(int xMin1, int yMin1, int xMax1, int yMax1, int xMin2, void DetectorRetinaFace::ComputeOverlap(int xMin1,
int yMin2, int xMax2, int yMax2, int* areaSum, int* areaInter) int yMin1,
int xMax1,
int yMax1,
int xMin2,
int yMin2,
int xMax2,
int yMax2,
int* areaSum,
int* areaInter)
{ {
int inter = 0; int inter = 0;
int s32Total = 0; int s32Total = 0;
int xMin = 0; int xMin = 0;
int yMin = 0; int yMin = 0;
int xMax = 0; int xMax = 0;
int yMax = 0; int yMax = 0;
int area1 = 0; int area1 = 0;
int area2 = 0; int area2 = 0;
int interWidth = 0; int interWidth = 0;
int interHeight = 0; int interHeight = 0;
xMin = SSD_MAX(xMin1, xMin2); xMin = SSD_MAX(xMin1, xMin2);
...@@ -1040,11 +1089,11 @@ void DetectorRetinaFace::ComputeOverlap(int xMin1, int yMin1, int xMax1, int yMa ...@@ -1040,11 +1089,11 @@ void DetectorRetinaFace::ComputeOverlap(int xMin1, int yMin1, int xMax1, int yMa
xMax = SSD_MIN(xMax1, xMax2); xMax = SSD_MIN(xMax1, xMax2);
yMax = SSD_MIN(yMax1, yMax2); yMax = SSD_MIN(yMax1, yMax2);
interWidth = xMax - xMin + 1; interWidth = xMax - xMin + 1;
interHeight = yMax - yMin + 1; interHeight = yMax - yMin + 1;
interWidth = ( interWidth >= 0 ) ? interWidth : 0; interWidth = (interWidth >= 0) ? interWidth : 0;
interHeight = ( interHeight >= 0 ) ? interHeight : 0; interHeight = (interHeight >= 0) ? interHeight : 0;
inter = interWidth * interHeight; inter = interWidth * interHeight;
area1 = (xMax1 - xMin1 + 1) * (yMax1 - yMin1 + 1); area1 = (xMax1 - xMin1 + 1) * (yMax1 - yMin1 + 1);
...@@ -1052,72 +1101,71 @@ void DetectorRetinaFace::ComputeOverlap(int xMin1, int yMin1, int xMax1, int yMa ...@@ -1052,72 +1101,71 @@ void DetectorRetinaFace::ComputeOverlap(int xMin1, int yMin1, int xMax1, int yMa
s32Total = area1 + area2 - inter; s32Total = area1 + area2 - inter;
*areaSum = s32Total; *areaSum = s32Total;
*areaInter = inter; *areaInter = inter;
} }
void DetectorRetinaFace::Swap(int* src1, int* src2) void DetectorRetinaFace::Swap(int* src1, int* src2)
{ {
int i = 0; int i = 0;
int temp = 0; int temp = 0;
for( i = 0; i < SSD_PROPOSAL_WIDTH; i++ ) for(i = 0; i < SSD_PROPOSAL_WIDTH; i++)
{ {
temp = src1[i]; temp = src1[i];
src1[i] = src2[i]; src1[i] = src2[i];
src2[i] = temp; src2[i] = temp;
} }
} }
void DetectorRetinaFace::CreateDetectionResults(std::vector<ResultOfDetection> &resultsOfDetection) void DetectorRetinaFace::CreateDetectionResults(std::vector<ResultOfDetection>& resultsOfDetection)
{ {
// 参数赋值 // 参数赋值
int* score=ssdParameter.dstScore; int* score = ssdParameter.dstScore;
int* roi=ssdParameter.dstRoi; int* roi = ssdParameter.dstRoi;
int* classRoiNum=ssdParameter.classRoiNum; int* classRoiNum = ssdParameter.classRoiNum;
float printResultThresh=((float)ssdParameter.confThresh)/SSD_QUANT_BASE; float printResultThresh = ((float)ssdParameter.confThresh) / SSD_QUANT_BASE;
int classNum=ssdParameter.classNum; int classNum = ssdParameter.classNum;
int i = 0, j = 0; int i = 0, j = 0;
int roiNumBias = 0; int roiNumBias = 0;
int scoreBias = 0; int scoreBias = 0;
int bboxBias = 0; int bboxBias = 0;
float score2 = 0.0f; float score2 = 0.0f;
int xMin = 0,yMin= 0,xMax = 0,yMax = 0; int xMin = 0, yMin = 0, xMax = 0, yMax = 0;
roiNumBias += classRoiNum[0]; roiNumBias += classRoiNum[0];
for (i = 1; i < classNum; i++) for(i = 1; i < classNum; i++)
{ {
scoreBias = roiNumBias; scoreBias = roiNumBias;
bboxBias = roiNumBias * SSD_COORDI_NUM; bboxBias = roiNumBias * SSD_COORDI_NUM;
if((float)score[scoreBias] / SSD_QUANT_BASE >= if((float)score[scoreBias] / SSD_QUANT_BASE >= printResultThresh && classRoiNum[i] != 0)
printResultThresh && classRoiNum[i]!=0)
{ {
//printf("==== The %d th class box info====\n", i); // printf("==== The %d th class box info====\n", i);
} }
for (j = 0; j < (int)classRoiNum[i]; j++) for(j = 0; j < (int)classRoiNum[i]; j++)
{ {
score2 = (float)score[scoreBias + j] / SSD_QUANT_BASE; score2 = (float)score[scoreBias + j] / SSD_QUANT_BASE;
if (score2 < printResultThresh) if(score2 < printResultThresh)
{ {
break; break;
} }
xMin = roi[bboxBias + j*SSD_COORDI_NUM]; xMin = roi[bboxBias + j * SSD_COORDI_NUM];
yMin = roi[bboxBias + j*SSD_COORDI_NUM + 1]; yMin = roi[bboxBias + j * SSD_COORDI_NUM + 1];
xMax = roi[bboxBias + j*SSD_COORDI_NUM + 2]; xMax = roi[bboxBias + j * SSD_COORDI_NUM + 2];
yMax = roi[bboxBias + j*SSD_COORDI_NUM + 3]; yMax = roi[bboxBias + j * SSD_COORDI_NUM + 3];
ResultOfDetection result; ResultOfDetection result;
result.boundingBox.x=xMin; result.boundingBox.x = xMin;
result.boundingBox.y=yMin; result.boundingBox.y = yMin;
result.boundingBox.width=xMax-xMin+1; result.boundingBox.width = xMax - xMin + 1;
result.boundingBox.height=yMax-yMin+1; result.boundingBox.height = yMax - yMin + 1;
result.classID=i; result.classID = i;
result.confidence=score2; result.confidence = score2;
resultsOfDetection.push_back(result); resultsOfDetection.push_back(result);
} }
roiNumBias += classRoiNum[i]; roiNumBias += classRoiNum[i];
} }
} }
} } // namespace migraphxSamples
...@@ -10,34 +10,49 @@ namespace migraphxSamples ...@@ -10,34 +10,49 @@ namespace migraphxSamples
class DetectorRetinaFace class DetectorRetinaFace
{ {
public: public:
DetectorRetinaFace(); DetectorRetinaFace();
~DetectorRetinaFace(); ~DetectorRetinaFace();
ErrorCode Initialize(InitializationParameterOfDetector initializationParameterOfDetector); ErrorCode Initialize(InitializationParameterOfDetector initializationParameterOfDetector);
ErrorCode Detect(const cv::Mat &srcImage,std::vector<ResultOfDetection> &resultsOfDetection); ErrorCode Detect(const cv::Mat& srcImage, std::vector<ResultOfDetection>& resultsOfDetection);
private: private:
void GetSSDParameter(); void GetSSDParameter();
void GetResult(const std::vector<std::vector<float>> &classification,const std::vector<std::vector<float>> &regression,std::vector<ResultOfDetection> &resultsOfDetection); void GetResult(const std::vector<std::vector<float>>& classification,
const std::vector<std::vector<float>>& regression,
std::vector<ResultOfDetection>& resultsOfDetection);
std::vector<float> PermuteLayer(const std::vector<float> &data,int width,int height,int channels); std::vector<float>
void PriorBoxLayer(int indexOfLayer,int* priorboxOutputData); PermuteLayer(const std::vector<float>& data, int width, int height, int channels);
void SoftmaxLayer(int softMaxWidth[],int* softMaxInputData[], int* softMaxOutputData); void PriorBoxLayer(int indexOfLayer, int* priorboxOutputData);
void DetectionOutputLayer(int* allLocPreds[], int* allPriorBoxes[],int* confScores, int* assistMemPool); void SoftmaxLayer(int softMaxWidth[], int* softMaxInputData[], int* softMaxOutputData);
void DetectionOutputLayer(int* allLocPreds[],
int* allPriorBoxes[],
int* confScores,
int* assistMemPool);
void ComputeSoftMax(int* src, int size, int* dst); void ComputeSoftMax(int* src, int size, int* dst);
void QuickSort(int* src,int low, int high, QuickSortStack *stack,int maxNum); void QuickSort(int* src, int low, int high, QuickSortStack* stack, int maxNum);
void NonMaxSuppression( int* proposals, int anchorsNum,int NMSThresh,int maxRoiNum); void NonMaxSuppression(int* proposals, int anchorsNum, int NMSThresh, int maxRoiNum);
void Swap(int* src1, int* src2); void Swap(int* src1, int* src2);
void ComputeOverlap(int xMin1, int yMin1, int xMax1, int yMax1, int xMin2,int yMin2, int xMax2, int yMax2, int* areaSum, int* areaInter); void ComputeOverlap(int xMin1,
void CreateDetectionResults(std::vector<ResultOfDetection> &resultsOfDetection); int yMin1,
int xMax1,
int yMax1,
int xMin2,
int yMin2,
int xMax2,
int yMax2,
int* areaSum,
int* areaInter);
void CreateDetectionResults(std::vector<ResultOfDetection>& resultsOfDetection);
private: private:
cv::FileStorage configurationFile; cv::FileStorage configurationFile;
migraphx::program net; migraphx::program net;
cv::Size inputSize; cv::Size inputSize;
std::string inputName; std::string inputName;
...@@ -51,10 +66,8 @@ private: ...@@ -51,10 +66,8 @@ private:
bool useFP16; bool useFP16;
SSDParameter ssdParameter; SSDParameter ssdParameter;
}; };
} } // namespace migraphxSamples
#endif #endif
...@@ -7,33 +7,33 @@ ...@@ -7,33 +7,33 @@
namespace migraphxSamples namespace migraphxSamples
{ {
// 路径分隔符(Linux:‘/’,Windows:’\\’) // 路径分隔符(Linux:‘/’,Windows:’\\’)
#ifdef _WIN32 #ifdef _WIN32
#define PATH_SEPARATOR '\\' #define PATH_SEPARATOR '\\'
#else #else
#define PATH_SEPARATOR '/' #define PATH_SEPARATOR '/'
#endif #endif
#define CONFIG_FILE "../Resource/Configuration.xml" #define CONFIG_FILE "../Resource/Configuration.xml"
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 _InitializationParameterOfDetector typedef struct _InitializationParameterOfDetector
{ {
std::string parentPath; std::string parentPath;
std::string configFilePath; std::string configFilePath;
}InitializationParameterOfDetector; } InitializationParameterOfDetector;
} } // 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
...@@ -14,9 +14,9 @@ ...@@ -14,9 +14,9 @@
// 路径分隔符(Linux:‘/’,Windows:’\\’) // 路径分隔符(Linux:‘/’,Windows:’\\’)
#ifdef _WIN32 #ifdef _WIN32
#define PATH_SEPARATOR '\\' #define PATH_SEPARATOR '\\'
#else #else
#define PATH_SEPARATOR '/' #define PATH_SEPARATOR '/'
#endif #endif
using namespace std; using namespace std;
...@@ -28,666 +28,672 @@ static std::vector<std::string> SplitString(std::string str, std::string separat ...@@ -28,666 +28,672 @@ 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
WIN32_FIND_DATAA data; WIN32_FIND_DATAA data;
#endif #endif
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
string full_path = string(path) + "\\*"; string full_path = string(path) + "\\*";
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);
CV_Assert((asize != 0) && (asize != (size_t)-1)); CV_Assert((asize != 0) && (asize != (size_t)-1));
char* aname = new char[asize + 1]; char* aname = new char[asize + 1];
aname[asize] = 0; aname[asize] = 0;
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
{ {
WIN32_FILE_ATTRIBUTE_DATA all_attrs; WIN32_FILE_ATTRIBUTE_DATA all_attrs;
#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));
status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs); status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
#else #else
status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs); status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
#endif #endif
attributes = all_attrs.dwFileAttributes; attributes = all_attrs.dwFileAttributes;
} }
return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0); return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
#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;
{ {
WIN32_FILE_ATTRIBUTE_DATA all_attrs; WIN32_FILE_ATTRIBUTE_DATA all_attrs;
#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));
status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs); status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
#else #else
status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs); status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
#endif #endif
} }
return !!status; return !!status;
#else #else
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)
} {
if(base.empty())
string JoinPath(const string& base, const string& path) return path;
{ if(path.empty())
if (base.empty()) return base;
return path;
if (path.empty()) bool baseSep = IsPathSeparator(base[base.size() - 1]);
return base; bool pathSep = IsPathSeparator(path[0]);
string result;
bool baseSep = IsPathSeparator(base[base.size() - 1]); if(baseSep && pathSep)
bool pathSep = IsPathSeparator(path[0]); {
string result; result = base + path.substr(1);
if (baseSep && pathSep) }
{ else if(!baseSep && !pathSep)
result = base + path.substr(1); {
} result = base + PATH_SEPARATOR + path;
else if (!baseSep && !pathSep) }
{ else
result = base + PATH_SEPARATOR + path; {
} result = base + path;
else }
{ return result;
result = base + path; }
}
return result; static bool wildcmp(const char* string, const char* wild)
} {
const char *cp = 0, *mp = 0;
static bool wildcmp(const char *string, const char *wild)
{ while((*string) && (*wild != '*'))
const char *cp = 0, *mp = 0; {
if((*wild != *string) && (*wild != '?'))
while ((*string) && (*wild != '*'))
{
if ((*wild != *string) && (*wild != '?'))
{
return false;
}
wild++;
string++;
}
while (*string)
{
if (*wild == '*')
{
if (!*++wild)
{
return true;
}
mp = wild;
cp = string + 1;
}
else if ((*wild == *string) || (*wild == '?'))
{
wild++;
string++;
}
else
{
wild = mp;
string = cp++;
}
}
while (*wild == '*')
{
wild++;
}
return *wild == 0;
}
static void glob_rec(const string &directory, const string& wildchart, std::vector<string>& result,
bool recursive, bool includeDirectories, const string& pathPrefix)
{
DIR *dir;
if ((dir = opendir(directory.c_str())) != 0)
{
/* find all the files and directories within directory */
try
{
struct dirent *ent;
while ((ent = readdir(dir)) != 0)
{
const char* name = ent->d_name;
if ((name[0] == 0) || (name[0] == '.' && name[1] == 0) || (name[0] == '.' && name[1] == '.' && name[2] == 0))
continue;
string path = JoinPath(directory, name);
string entry = JoinPath(pathPrefix, name);
if (isDir(path, dir))
{
if (recursive)
glob_rec(path, wildchart, result, recursive, includeDirectories, entry);
if (!includeDirectories)
continue;
}
if (wildchart.empty() || wildcmp(name, wildchart.c_str()))
result.push_back(entry);
}
}
catch (...)
{
closedir(dir);
throw;
}
closedir(dir);
}
else
{
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)
{
// split pattern
vector<string> patterns=SplitString(pattern,",");
result.clear();
for(int i=0;i<patterns.size();++i)
{ {
string eachPattern=patterns[i]; return false;
std::vector<string> eachResult; }
glob_rec(directory, eachPattern, eachResult, recursive, true, directory);
for(int j=0;j<eachResult.size();++j) wild++;
string++;
}
while(*string)
{
if(*wild == '*')
{
if(!*++wild)
{ {
if (IsDirectory(eachResult[j])) return true;
continue; }
if(addPath)
mp = wild;
cp = string + 1;
}
else if((*wild == *string) || (*wild == '?'))
{
wild++;
string++;
}
else
{
wild = mp;
string = cp++;
}
}
while(*wild == '*')
{
wild++;
}
return *wild == 0;
}
static void glob_rec(const string& directory,
const string& wildchart,
std::vector<string>& result,
bool recursive,
bool includeDirectories,
const string& pathPrefix)
{
DIR* dir;
if((dir = opendir(directory.c_str())) != 0)
{
/* find all the files and directories within directory */
try
{
struct dirent* ent;
while((ent = readdir(dir)) != 0)
{
const char* name = ent->d_name;
if((name[0] == 0) || (name[0] == '.' && name[1] == 0) ||
(name[0] == '.' && name[1] == '.' && name[2] == 0))
continue;
string path = JoinPath(directory, name);
string entry = JoinPath(pathPrefix, name);
if(isDir(path, dir))
{
if(recursive)
glob_rec(path, wildchart, result, recursive, includeDirectories, entry);
if(!includeDirectories)
continue;
}
if(wildchart.empty() || wildcmp(name, wildchart.c_str()))
result.push_back(entry);
}
}
catch(...)
{
closedir(dir);
throw;
}
closedir(dir);
}
else
{
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)
{
// split pattern
vector<string> patterns = SplitString(pattern, ",");
result.clear();
for(int i = 0; i < patterns.size(); ++i)
{
string eachPattern = patterns[i];
std::vector<string> eachResult;
glob_rec(directory, eachPattern, eachResult, recursive, true, directory);
for(int j = 0; j < eachResult.size(); ++j)
{
if(IsDirectory(eachResult[j]))
continue;
if(addPath)
{
result.push_back(eachResult[j]);
}
else
{
result.push_back(GetFileName(eachResult[j]));
}
}
}
std::sort(result.begin(), result.end());
}
void GetFileNameList2(const string& directory,
const string& pattern,
std::vector<string>& result,
bool recursive,
bool addPath)
{
// split pattern
vector<string> patterns = SplitString(pattern, ",");
result.clear();
for(int i = 0; i < patterns.size(); ++i)
{
string eachPattern = patterns[i];
std::vector<string> eachResult;
glob_rec(directory, eachPattern, eachResult, recursive, true, directory);
for(int j = 0; j < eachResult.size(); ++j)
{
string filePath = eachResult[j];
if(IsDirectory(filePath))
{
filePath = filePath + "/";
for(int k = 0; k < filePath.size(); ++k)
{ {
result.push_back(eachResult[j]); if(IsPathSeparator(filePath[k]))
{
filePath[k] = '/';
}
} }
else }
if(addPath)
{
result.push_back(filePath);
}
else
{
if(!IsDirectory(filePath))
{ {
result.push_back(GetFileName(eachResult[j])); result.push_back(GetFileName(filePath));
} }
} }
} }
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 RemoveAll(const string& path)
// split pattern {
vector<string> patterns = SplitString(pattern, ",");
if(!Exists(path))
result.clear(); return;
for (int i = 0; i<patterns.size(); ++i) if(IsDirectory(path))
{ {
string eachPattern = patterns[i]; std::vector<string> entries;
std::vector<string> eachResult; GetFileNameList2(path, string(), entries, false, true);
glob_rec(directory, eachPattern, eachResult, recursive, true, directory); for(size_t i = 0; i < entries.size(); i++)
for (int j = 0; j<eachResult.size(); ++j) {
{ const string& e = entries[i];
string filePath = eachResult[j]; RemoveAll(e);
if (IsDirectory(filePath)) }
{
filePath = filePath + "/";
for (int k = 0; k < filePath.size(); ++k)
{
if (IsPathSeparator(filePath[k]))
{
filePath[k] = '/';
}
}
}
if (addPath)
{
result.push_back(filePath);
}
else
{
if (!IsDirectory(filePath))
{
result.push_back(GetFileName(filePath));
}
}
}
}
std::sort(result.begin(), result.end());
}
void RemoveAll(const string& path)
{
if (!Exists(path))
return;
if (IsDirectory(path))
{
std::vector<string> entries;
GetFileNameList2(path, string(), entries, false, true);
for (size_t i = 0; i < entries.size(); i++)
{
const string& e = entries[i];
RemoveAll(e);
}
#ifdef _MSC_VER #ifdef _MSC_VER
bool result = _rmdir(path.c_str()) == 0; bool result = _rmdir(path.c_str()) == 0;
#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());
} }
} }
else else
{ {
#ifdef _MSC_VER #ifdef _MSC_VER
bool result = _unlink(path.c_str()) == 0; bool result = _unlink(path.c_str()) == 0;
#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());
}
}
}
void Remove(const string &directory, const string &extension)
{
DIR *dir;
static int numberOfFiles = 0;
if ((dir = opendir(directory.c_str())) != 0)
{
/* find all the files and directories within directory */
try
{
struct dirent *ent;
while ((ent = readdir(dir)) != 0)
{
const char* name = ent->d_name;
if ((name[0] == 0) || (name[0] == '.' && name[1] == 0) || (name[0] == '.' && name[1] == '.' && name[2] == 0))
continue;
string path = JoinPath(directory, name);
if (isDir(path, dir))
{
Remove(path, extension);
}
// �ж���չ��
if (extension.empty() || wildcmp(name, extension.c_str()))
{
RemoveAll(path);
++numberOfFiles;
printf("%s deleted! number of deleted files:%d\n", path.c_str(), numberOfFiles);
}
}
}
catch (...)
{
closedir(dir);
throw;
}
closedir(dir);
}
else
{
printf("could not open directory: %s", directory.c_str());
}
// ����RemoveAllɾ��Ŀ¼
RemoveAll(directory);
}
string GetFileName(const string &path)
{
string fileName;
int indexOfPathSeparator = -1;
for (int i = path.size() - 1; i >= 0; --i)
{
if (IsPathSeparator(path[i]))
{
fileName = path.substr(i + 1, path.size() - i - 1);
indexOfPathSeparator = i;
break;
}
}
if (indexOfPathSeparator == -1)
{ {
fileName = path; printf("can't remove file: %s\n", path.c_str());
} }
}
}
void Remove(const string& directory, const string& extension)
{
return fileName; DIR* dir;
}
string GetFileName_NoExtension(const string &path) static int numberOfFiles = 0;
if((dir = opendir(directory.c_str())) != 0)
{ {
string fileName=GetFileName(path); /* find all the files and directories within directory */
string fileName_NoExtension; try
for(int i=fileName.size()-1;i>0;--i)
{ {
if(fileName[i]=='.') struct dirent* ent;
while((ent = readdir(dir)) != 0)
{ {
fileName_NoExtension=fileName.substr(0,i); const char* name = ent->d_name;
break; if((name[0] == 0) || (name[0] == '.' && name[1] == 0) ||
} (name[0] == '.' && name[1] == '.' && name[2] == 0))
} continue;
return fileName_NoExtension; string path = JoinPath(directory, name);
}
if(isDir(path, dir))
string GetExtension(const string &path) {
{ Remove(path, extension);
string fileName; }
for (int i = path.size() - 1; i >= 0; --i)
{ // �ж���չ��
if (path[i]=='.') if(extension.empty() || wildcmp(name, extension.c_str()))
{ {
fileName = path.substr(i, path.size() - i); RemoveAll(path);
break; ++numberOfFiles;
} printf("%s deleted! number of deleted files:%d\n", path.c_str(), numberOfFiles);
} }
return fileName;
}
string GetParentPath(const string &path)
{
string fileName;
for (int i = path.size() - 1; i >= 0; --i)
{
if (IsPathSeparator(path[i]))
{
fileName = path.substr(0, i+1);
break;
}
}
return fileName;
}
static bool CreateDirectory(const string &path)
{
#if defined WIN32 || defined _WIN32 || defined WINCE
#ifdef WINRT
wchar_t wpath[MAX_PATH];
size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
int result = CreateDirectoryA(wpath, NULL) ? 0 : -1;
#else
int result = _mkdir(path.c_str());
#endif
#elif defined __linux__ || defined __APPLE__
int result = mkdir(path.c_str(), 0777);
#else
int result = -1;
#endif
if (result == -1)
{
return IsDirectory(path);
} }
return true; }
} catch(...)
bool CreateDirectories(const string &directoryPath)
{
string path = directoryPath;
for (;;)
{
char last_char = path.empty() ? 0 : path[path.length() - 1];
if (IsPathSeparator(last_char))
{
path = path.substr(0, path.length() - 1);
continue;
}
break;
}
if (path.empty() || path == "./" || path == ".\\" || path == ".")
return true;
if (IsDirectory(path))
return true;
size_t pos = path.rfind('/');
if (pos == string::npos)
pos = path.rfind('\\');
if (pos != string::npos)
{
string parent_directory = path.substr(0, pos);
if (!parent_directory.empty())
{
if (!CreateDirectories(parent_directory))
return false;
}
}
return CreateDirectory(path);
}
bool CopyFile(const string srcPath, const string dstPath)
{
std::ifstream srcFile(srcPath,ios::binary);
std::ofstream dstFile(dstPath,ios::binary);
if(!srcFile.is_open())
{ {
printf("can not open %s\n",srcPath.c_str()); closedir(dir);
return false; throw;
} }
if(!dstFile.is_open()) closedir(dir);
}
else
{
printf("could not open directory: %s", directory.c_str());
}
// ����RemoveAllɾ��Ŀ¼
RemoveAll(directory);
}
string GetFileName(const string& path)
{
string fileName;
int indexOfPathSeparator = -1;
for(int i = path.size() - 1; i >= 0; --i)
{
if(IsPathSeparator(path[i]))
{ {
printf("can not open %s\n", dstPath.c_str()); fileName = path.substr(i + 1, path.size() - i - 1);
return false; indexOfPathSeparator = i;
break;
} }
if(srcPath==dstPath) }
if(indexOfPathSeparator == -1)
{
fileName = path;
}
return fileName;
}
string GetFileName_NoExtension(const string& path)
{
string fileName = GetFileName(path);
string fileName_NoExtension;
for(int i = fileName.size() - 1; i > 0; --i)
{
if(fileName[i] == '.')
{ {
printf("src can not be same with dst\n"); fileName_NoExtension = fileName.substr(0, i);
return false; break;
} }
char buffer[2048]; }
unsigned int numberOfBytes=0;
while(srcFile) return fileName_NoExtension;
}
string GetExtension(const string& path)
{
string fileName;
for(int i = path.size() - 1; i >= 0; --i)
{
if(path[i] == '.')
{ {
srcFile.read(buffer,2048); fileName = path.substr(i, path.size() - i);
dstFile.write(buffer,srcFile.gcount()); break;
numberOfBytes+=srcFile.gcount();
} }
srcFile.close();
dstFile.close();
return true;
} }
bool CopyDirectories(string srcPath, const string dstPath) return fileName;
}
string GetParentPath(const string& path)
{
string fileName;
for(int i = path.size() - 1; i >= 0; --i)
{ {
if(srcPath==dstPath) if(IsPathSeparator(path[i]))
{ {
printf("src can not be same with dst\n"); fileName = path.substr(0, i + 1);
return false; break;
} }
}
// ȥ������·���ָ��� return fileName;
srcPath = srcPath.substr(0, srcPath.size() - 1); }
vector<string> fileNameList; static bool CreateDirectory(const string& path)
GetFileNameList2(srcPath, "", fileNameList, true, true); {
#if defined WIN32 || defined _WIN32 || defined WINCE
#ifdef WINRT
wchar_t wpath[MAX_PATH];
size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
int result = CreateDirectoryA(wpath, NULL) ? 0 : -1;
#else
int result = _mkdir(path.c_str());
#endif
#elif defined __linux__ || defined __APPLE__
int result = mkdir(path.c_str(), 0777);
#else
int result = -1;
#endif
string parentPathOfSrc=GetParentPath(srcPath); if(result == -1)
int length=parentPathOfSrc.size(); {
return IsDirectory(path);
}
return true;
}
// create all directories bool CreateDirectories(const string& directoryPath)
for(int i=0;i<fileNameList.size();++i) {
string path = directoryPath;
for(;;)
{
char last_char = path.empty() ? 0 : path[path.length() - 1];
if(IsPathSeparator(last_char))
{ {
// create directory path = path.substr(0, path.length() - 1);
string srcFilePath=fileNameList[i]; continue;
string subStr=srcFilePath.substr(length,srcFilePath.size()-length);
string dstFilePath=dstPath+subStr;
string parentPathOfDst=GetParentPath(dstFilePath);
CreateDirectories(parentPathOfDst);
} }
break;
}
// copy file if(path.empty() || path == "./" || path == ".\\" || path == ".")
for(int i=0;i<fileNameList.size();++i) return true;
if(IsDirectory(path))
return true;
size_t pos = path.rfind('/');
if(pos == string::npos)
pos = path.rfind('\\');
if(pos != string::npos)
{
string parent_directory = path.substr(0, pos);
if(!parent_directory.empty())
{ {
string srcFilePath=fileNameList[i]; if(!CreateDirectories(parent_directory))
if (IsDirectory(srcFilePath)) return false;
{
continue;
}
string subStr=srcFilePath.substr(length,srcFilePath.size()-length);
string dstFilePath=dstPath+subStr;
// copy file
CopyFile(srcFilePath,dstFilePath);
// process
double process = (1.0*(i + 1) / fileNameList.size()) * 100;
printf("%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
} }
printf("all done!(the number of files:%d)\n", fileNameList.size()); }
return true; return CreateDirectory(path);
}
bool CopyFile(const string srcPath, const string dstPath)
{
std::ifstream srcFile(srcPath, ios::binary);
std::ofstream dstFile(dstPath, ios::binary);
if(!srcFile.is_open())
{
printf("can not open %s\n", srcPath.c_str());
return false;
}
if(!dstFile.is_open())
{
printf("can not open %s\n", dstPath.c_str());
return false;
}
if(srcPath == dstPath)
{
printf("src can not be same with dst\n");
return false;
}
char buffer[2048];
unsigned int numberOfBytes = 0;
while(srcFile)
{
srcFile.read(buffer, 2048);
dstFile.write(buffer, srcFile.gcount());
numberOfBytes += srcFile.gcount();
}
srcFile.close();
dstFile.close();
return true;
}
bool CopyDirectories(string srcPath, const string dstPath)
{
if(srcPath == dstPath)
{
printf("src can not be same with dst\n");
return false;
} }
} // ȥ������·���ָ���
srcPath = srcPath.substr(0, srcPath.size() - 1);
vector<string> fileNameList;
GetFileNameList2(srcPath, "", fileNameList, true, true);
string parentPathOfSrc = GetParentPath(srcPath);
int length = parentPathOfSrc.size();
// create all directories
for(int i = 0; i < fileNameList.size(); ++i)
{
// create directory
string srcFilePath = fileNameList[i];
string subStr = srcFilePath.substr(length, srcFilePath.size() - length);
string dstFilePath = dstPath + subStr;
string parentPathOfDst = GetParentPath(dstFilePath);
CreateDirectories(parentPathOfDst);
}
// copy file
for(int i = 0; i < fileNameList.size(); ++i)
{
string srcFilePath = fileNameList[i];
if(IsDirectory(srcFilePath))
{
continue;
}
string subStr = srcFilePath.substr(length, srcFilePath.size() - length);
string dstFilePath = dstPath + subStr;
// copy file
CopyFile(srcFilePath, dstFilePath);
// process
double process = (1.0 * (i + 1) / fileNameList.size()) * 100;
printf("%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
}
printf("all done!(the number of files:%d)\n", fileNameList.size());
return true;
}
} // namespace migraphxSamples
...@@ -5,27 +5,27 @@ ...@@ -5,27 +5,27 @@
#include <string> #include <string>
#include <vector> #include <vector>
namespace migraphxSamples 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);
/** 生成符合指定模式的文件名列表(支持递归遍历) /** 生成符合指定模式的文件名列表(支持递归遍历)
* *
* pattern: 模式,比如"*.jpg","*.png","*.jpg,*.png" * pattern: 模式,比如"*.jpg","*.png","*.jpg,*.png"
* addPath:是否包含父路径 * addPath:是否包含父路径
* 注意: * 注意:
...@@ -36,35 +36,43 @@ bool CreateDirectories(const std::string &directoryPath); ...@@ -36,35 +36,43 @@ 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);
/** 拷贝目录 /** 拷贝目录
* *
* 示例:CopyDirectories("D:/0/1/2/","E:/3/");实现把D:/0/1/2/目录拷贝到E:/3/目录中(即拷贝完成后的目录结构为E:/3/2/) * 示例:CopyDirectories("D:/0/1/2/","E:/3/");实现把D:/0/1/2/目录拷贝到E:/3/目录中(即拷贝完成后的目录结构为E:/3/2/)
* 注意: * 注意:
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 @@
namespace migraphxSamples namespace migraphxSamples
{ {
#define SSD_MAX_PRIORBOX_LAYER_NUM 10 // 能够支持的最大检测层数量 #define SSD_MAX_PRIORBOX_LAYER_NUM 10 // 能够支持的最大检测层数量
// SSD参数 // SSD参数
typedef struct _SSDParameter typedef struct _SSDParameter
...@@ -16,23 +16,23 @@ typedef struct _SSDParameter ...@@ -16,23 +16,23 @@ typedef struct _SSDParameter
int numberOfPriorBoxLayer; // 检测层数量 int numberOfPriorBoxLayer; // 检测层数量
// Model Parameters // Model Parameters
int convHeight[SSD_MAX_PRIORBOX_LAYER_NUM*2]; int convHeight[SSD_MAX_PRIORBOX_LAYER_NUM * 2];
int convWidth[SSD_MAX_PRIORBOX_LAYER_NUM*2]; int convWidth[SSD_MAX_PRIORBOX_LAYER_NUM * 2];
int convChannel[SSD_MAX_PRIORBOX_LAYER_NUM*2]; int convChannel[SSD_MAX_PRIORBOX_LAYER_NUM * 2];
// PriorBoxLayer Parameters // PriorBoxLayer Parameters
int priorBoxWidth[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层priorbox的宽 int priorBoxWidth[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层priorbox的宽
int priorBoxHeight[SSD_MAX_PRIORBOX_LAYER_NUM];// 每个检测层priorbox的高 int priorBoxHeight[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层priorbox的高
std::vector<std::vector<float>> priorBoxMinSize; // 每个检测层priorbox的minsize std::vector<std::vector<float>> priorBoxMinSize; // 每个检测层priorbox的minsize
std::vector<std::vector<float>> priorBoxMaxSize; // 每个检测层priorbox的maxsize std::vector<std::vector<float>> priorBoxMaxSize; // 每个检测层priorbox的maxsize
int minSizeNum[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层priorbox的minsize数量 int minSizeNum[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层priorbox的minsize数量
int maxSizeNum[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层priorbox的maxsize数量 int maxSizeNum[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层priorbox的maxsize数量
int srcImageHeight;// 原图大小 int srcImageHeight; // 原图大小
int srcImageWidth; int srcImageWidth;
int inputAspectRatioNum[SSD_MAX_PRIORBOX_LAYER_NUM];// 每个检测层宽高比的数量 int inputAspectRatioNum[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层宽高比的数量
std::vector<std::vector<float>> priorBoxAspectRatio;// 每个检测层的宽高比 std::vector<std::vector<float>> priorBoxAspectRatio; // 每个检测层的宽高比
float priorBoxStepWidth[SSD_MAX_PRIORBOX_LAYER_NUM];// 每个检测层步长的宽 float priorBoxStepWidth[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层步长的宽
float priorBoxStepHeight[SSD_MAX_PRIORBOX_LAYER_NUM];// 每个检测层步长的高 float priorBoxStepHeight[SSD_MAX_PRIORBOX_LAYER_NUM]; // 每个检测层步长的高
float offset; float offset;
int flip[SSD_MAX_PRIORBOX_LAYER_NUM]; int flip[SSD_MAX_PRIORBOX_LAYER_NUM];
int clip[SSD_MAX_PRIORBOX_LAYER_NUM]; int clip[SSD_MAX_PRIORBOX_LAYER_NUM];
...@@ -47,7 +47,7 @@ typedef struct _SSDParameter ...@@ -47,7 +47,7 @@ typedef struct _SSDParameter
int softMaxOutChn; int softMaxOutChn;
// DetectionOutLayer Parameters // DetectionOutLayer Parameters
int classNum;// 类别数(包含背景类) int classNum; // 类别数(包含背景类)
int topK; int topK;
int keepTopK; int keepTopK;
int NMSThresh; int NMSThresh;
...@@ -56,39 +56,41 @@ typedef struct _SSDParameter ...@@ -56,39 +56,41 @@ typedef struct _SSDParameter
int convStride[SSD_MAX_PRIORBOX_LAYER_NUM]; int convStride[SSD_MAX_PRIORBOX_LAYER_NUM];
// buffer // buffer
int *buffer; int* buffer;
int *classification[SSD_MAX_PRIORBOX_LAYER_NUM];// 分类数据 int* classification[SSD_MAX_PRIORBOX_LAYER_NUM]; // 分类数据
int *regression[SSD_MAX_PRIORBOX_LAYER_NUM];// 回归 int* regression[SSD_MAX_PRIORBOX_LAYER_NUM]; // 回归
int *priorboxOutputData; int* priorboxOutputData;
int *softMaxOutputData; int* softMaxOutputData;
int *getResultBuffer; int* getResultBuffer;
int *dstScore; int* dstScore;
int *dstRoi; int* dstRoi;
int *classRoiNum; int* classRoiNum;
_SSDParameter():srcImageHeight(0), _SSDParameter()
srcImageWidth(0), : srcImageHeight(0),
offset(0.0), srcImageWidth(0),
softMaxInHeight(0), offset(0.0),
concatNum(0), softMaxInHeight(0),
softMaxOutWidth(0), concatNum(0),
softMaxOutHeight(0), softMaxOutWidth(0),
softMaxOutChn(0), softMaxOutHeight(0),
buffer(NULL), softMaxOutChn(0),
priorboxOutputData(NULL), buffer(NULL),
softMaxOutputData(NULL), priorboxOutputData(NULL),
getResultBuffer(NULL), softMaxOutputData(NULL),
dstScore(NULL), getResultBuffer(NULL),
dstRoi(NULL), dstScore(NULL),
classRoiNum(NULL){} dstRoi(NULL),
}SSDParameter; classRoiNum(NULL)
{
}
} SSDParameter;
typedef struct _QuickSortStack typedef struct _QuickSortStack
{ {
int min; int min;
int max; int max;
}QuickSortStack; } QuickSortStack;
} } // 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");
...@@ -34,11 +34,11 @@ using namespace std; ...@@ -34,11 +34,11 @@ using namespace std;
// 关闭日志 // 关闭日志
LogManager::GetInstance()->Close("log1"); LogManager::GetInstance()->Close("log1");
LogManager::GetInstance()->Close("log2"); LogManager::GetInstance()->Close("log2");
* 示例2: * 示例2:
// 将日志输出到控制台 // 将日志输出到控制台
string log = "Hello World"; string log = "Hello World";
LOG_INFO(stdout, "%s\n", log.c_str()); LOG_INFO(stdout, "%s\n", log.c_str());
* 注意: * 注意:
1. 需要C++11 1. 需要C++11
...@@ -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,21 +102,22 @@ public: ...@@ -106,21 +102,22 @@ 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
typedef struct _LogTime typedef struct _LogTime
{ {
string year; string year;
string month; string month;
...@@ -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);
...@@ -187,61 +184,83 @@ inline LogTime GetTime() ...@@ -187,61 +184,83 @@ inline LogTime GetTime()
return currentTime; return currentTime;
} }
#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(), \
LOCK; \ currentTime.second.c_str(), \
LOG_TIME(logFile); \ currentTime.millisecond.c_str()); \
fprintf(((logFile == NULL) ? stdout : logFile), "INFO\t"); \ } while(0)
fprintf(((logFile == NULL) ? stdout : logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ## __VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while (0)
#define LOG_DEBUG(logFile,logInfo, ...) \
do\
{\
LOCK; \
LOG_TIME(logFile);\
fprintf(((logFile==NULL)?stdout:logFile), "DEBUG\t"); \
fprintf(((logFile==NULL)?stdout:logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \
fprintf(((logFile==NULL)?stdout:logFile),logInfo, ## __VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while (0)
#define LOG_ERROR(logFile,logInfo, ...) \
do\
{\
LOCK; \
LOG_TIME(logFile);\
fprintf(((logFile==NULL)?stdout:logFile), "ERROR\t"); \
fprintf(((logFile==NULL)?stdout:logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \
fprintf(((logFile==NULL)?stdout:logFile),logInfo, ## __VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while (0)
#define LOG_WARN(logFile,logInfo, ...) \
do\
{\
LOCK; \
LOG_TIME(logFile);\
fprintf(((logFile==NULL)?stdout:logFile), "WARN\t"); \
fprintf(((logFile==NULL)?stdout:logFile), "[%s:%d (%s) ]: ", __FILE__, __LINE__, __FUNCTION__); \
fprintf(((logFile==NULL)?stdout:logFile),logInfo, ## __VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while (0)
#endif // __SIMPLE_LOG_H__ #define LOG_INFO(logFile, logInfo, ...) \
do \
{ \
LOCK; \
LOG_TIME(logFile); \
fprintf(((logFile == NULL) ? stdout : logFile), "INFO\t"); \
fprintf(((logFile == NULL) ? stdout : logFile), \
"[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while(0)
#define LOG_DEBUG(logFile, logInfo, ...) \
do \
{ \
LOCK; \
LOG_TIME(logFile); \
fprintf(((logFile == NULL) ? stdout : logFile), "DEBUG\t"); \
fprintf(((logFile == NULL) ? stdout : logFile), \
"[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while(0)
#define LOG_ERROR(logFile, logInfo, ...) \
do \
{ \
LOCK; \
LOG_TIME(logFile); \
fprintf(((logFile == NULL) ? stdout : logFile), "ERROR\t"); \
fprintf(((logFile == NULL) ? stdout : logFile), \
"[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while(0)
#define LOG_WARN(logFile, logInfo, ...) \
do \
{ \
LOCK; \
LOG_TIME(logFile); \
fprintf(((logFile == NULL) ? stdout : logFile), "WARN\t"); \
fprintf(((logFile == NULL) ? stdout : logFile), \
"[%s:%d (%s) ]: ", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
fflush(logFile); \
UNLOCK; \
} while(0)
#endif // __SIMPLE_LOG_H__
...@@ -11,8 +11,8 @@ int main() ...@@ -11,8 +11,8 @@ int main()
migraphxSamples::DetectorRetinaFace detector; migraphxSamples::DetectorRetinaFace detector;
migraphxSamples::InitializationParameterOfDetector initParamOfDetectorRetinaFace; migraphxSamples::InitializationParameterOfDetector initParamOfDetectorRetinaFace;
initParamOfDetectorRetinaFace.configFilePath = CONFIG_FILE; initParamOfDetectorRetinaFace.configFilePath = CONFIG_FILE;
migraphxSamples::ErrorCode errorCode=detector.Initialize(initParamOfDetectorRetinaFace); migraphxSamples::ErrorCode errorCode = detector.Initialize(initParamOfDetectorRetinaFace);
if(errorCode!=migraphxSamples::SUCCESS) if(errorCode != migraphxSamples::SUCCESS)
{ {
LOG_ERROR(stdout, "fail to initialize detector!\n"); LOG_ERROR(stdout, "fail to initialize detector!\n");
exit(-1); exit(-1);
...@@ -20,24 +20,30 @@ int main() ...@@ -20,24 +20,30 @@ int main()
LOG_INFO(stdout, "succeed to initialize detector\n"); LOG_INFO(stdout, "succeed to initialize detector\n");
// 读取测试图片 // 读取测试图片
cv::Mat srcImage=cv::imread("../Resource/Images/FaceDetect.jpg",1); cv::Mat srcImage = cv::imread("../Resource/Images/FaceDetect.jpg", 1);
// 推理 // 推理
std::vector<migraphxSamples::ResultOfDetection> predictions; std::vector<migraphxSamples::ResultOfDetection> predictions;
detector.Detect(srcImage,predictions); detector.Detect(srcImage, predictions);
// 获取推理结果 // 获取推理结果
LOG_INFO(stdout,"========== Detection Results ==========\n"); LOG_INFO(stdout, "========== Detection Results ==========\n");
for(int i=0;i<predictions.size();++i) for(int i = 0; i < predictions.size(); ++i)
{ {
migraphxSamples::ResultOfDetection result=predictions[i]; migraphxSamples::ResultOfDetection result = predictions[i];
cv::rectangle(srcImage,result.boundingBox,cv::Scalar(0,255,255),2); cv::rectangle(srcImage, result.boundingBox, cv::Scalar(0, 255, 255), 2);
LOG_INFO(stdout,"box:%d %d %d %d,label:%d,confidence:%f\n",predictions[i].boundingBox.x, LOG_INFO(stdout,
predictions[i].boundingBox.y,predictions[i].boundingBox.width,predictions[i].boundingBox.height,predictions[i].classID,predictions[i].confidence); "box:%d %d %d %d,label:%d,confidence:%f\n",
predictions[i].boundingBox.x,
predictions[i].boundingBox.y,
predictions[i].boundingBox.width,
predictions[i].boundingBox.height,
predictions[i].classID,
predictions[i].confidence);
} }
cv::imwrite("Result.jpg",srcImage); cv::imwrite("Result.jpg", srcImage);
LOG_INFO(stdout,"Detection results have been saved to ./Result.jpg\n"); LOG_INFO(stdout, "Detection results have been saved to ./Result.jpg\n");
return 0; return 0;
} }
\ 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