YOLOV5.cpp 7.14 KB
Newer Older
liucong's avatar
liucong committed
1
#include <YOLOV5.h>
Your Name's avatar
Your Name committed
2
3
4
5
6
7
8
9
10
11
#include <migraphx/onnx.hpp>
#include <migraphx/gpu/target.hpp>
#include <migraphx/quantization.hpp>
#include <Filesystem.h>
#include <SimpleLog.h>


namespace migraphxSamples
{

liucong's avatar
liucong committed
12
DetectorYOLOV5::DetectorYOLOV5()
Your Name's avatar
Your Name committed
13
14
15
16
17
18
19
20
21
22
23
24
25
{

}

DetectorYOLOV5::~DetectorYOLOV5()
{

    configurationFile.release();
    
}

ErrorCode DetectorYOLOV5::Initialize(InitializationParameterOfDetector initializationParameterOfDetector)
{
liucong's avatar
liucong committed
26
27
28
    // 读取配置文件
    std::string configFilePath=initializationParameterOfDetector.configFilePath;
    if(Exists(configFilePath)==false)
Your Name's avatar
Your Name committed
29
    {
liucong's avatar
liucong committed
30
31
        LOG_ERROR(stdout, "no configuration file!\n");
        return CONFIG_FILE_NOT_EXIST;
Your Name's avatar
Your Name committed
32
    }
liucong's avatar
liucong committed
33
34
35
36
37
38
    if(!configurationFile.open(configFilePath, cv::FileStorage::READ))
    {
       LOG_ERROR(stdout, "fail to open configuration file\n");
       return FAIL_TO_OPEN_CONFIG_FILE;
    }
    LOG_INFO(stdout, "succeed to open configuration file\n");
Your Name's avatar
Your Name committed
39
40
    
    // 获取配置文件参数
liucong's avatar
liucong committed
41
42
43
    cv::FileNode netNode = configurationFile["DetectorYOLOV5"];
    std::string modelPath=(std::string)netNode["ModelPath"];
    std::string pathOfClassNameFile=(std::string)netNode["ClassNameFile"];
Your Name's avatar
Your Name committed
44
45
46
47
48
49
50
51
52
    yolov5Parameter.confidenceThreshold = (float)netNode["ConfidenceThreshold"];
    yolov5Parameter.nmsThreshold = (float)netNode["NMSThreshold"];
    yolov5Parameter.objectThreshold = (float)netNode["ObjectThreshold"];
    yolov5Parameter.numberOfClasses=(int)netNode["NumberOfClasses"];
    useFP16=(bool)(int)netNode["UseFP16"];

    // 加载模型
    if(Exists(modelPath)==false)
    {
liucong's avatar
liucong committed
53
        LOG_ERROR(stdout,"%s not exist!\n",modelPath.c_str());
Your Name's avatar
Your Name committed
54
55
        return MODEL_NOT_EXIST;
    }
56
57
    
    migraphx::onnx_options onnx_options;
shizhm's avatar
shizhm committed
58
    onnx_options.map_input_dims["images"]={1,3,800,800}; 
59
    net = migraphx::parse_onnx(modelPath, onnx_options);
liucong's avatar
liucong committed
60
    LOG_INFO(stdout,"succeed to load model: %s\n",GetFileName(modelPath).c_str());
Your Name's avatar
Your Name committed
61
62

    // 获取模型输入属性
liucong's avatar
liucong committed
63
64
65
66
67
68
69
70
    std::unordered_map<std::string, migraphx::shape> inputMap=net.get_parameter_shapes();
    inputName=inputMap.begin()->first;
    inputShape=inputMap.begin()->second;
    int N=inputShape.lens()[0];
    int C=inputShape.lens()[1];
    int H=inputShape.lens()[2];
    int W=inputShape.lens()[3];
    inputSize=cv::Size(W,H);
Your Name's avatar
Your Name committed
71
72
73
74
75
76
77
78
79
80
81
82

    // 设置模型为GPU模式
    migraphx::target gpuTarget = migraphx::gpu::target{};

    // 量化    
    if(useFP16)
    {
        migraphx::quantize_fp16(net);
    }

    // 编译模型
    migraphx::compile_options options;
83
    options.device_id=0; 
liucong's avatar
liucong committed
84
    options.offload_copy=true;
Your Name's avatar
Your Name committed
85
    net.compile(gpuTarget,options);
liucong's avatar
liucong committed
86
    LOG_INFO(stdout,"succeed to compile model: %s\n",GetFileName(modelPath).c_str());
Your Name's avatar
Your Name committed
87

liucong's avatar
liucong committed
88
89
90
    // warm up
    std::unordered_map<std::string, migraphx::argument> inputData;
    inputData[inputName]=migraphx::argument{inputShape};
Your Name's avatar
Your Name committed
91
92
93
94
95
    net.eval(inputData);

    // 读取类别名
    if(!pathOfClassNameFile.empty())
    {
liucong's avatar
liucong committed
96
97
        std::ifstream classNameFile(pathOfClassNameFile);
        std::string line;
Your Name's avatar
Your Name committed
98
99
100
101
102
103
104
105
106
107
108
        while (getline(classNameFile, line))
        {
            classNames.push_back(line);
        }
    }
    else
    {
        classNames.resize(yolov5Parameter.numberOfClasses);
    }

    // log
109
    LOG_INFO(stdout,"InputMaxSize:%dx%d\n",inputSize.width,inputSize.height);
liucong's avatar
liucong committed
110
111
112
113
114
    LOG_INFO(stdout,"InputName:%s\n",inputName.c_str());
    LOG_INFO(stdout,"ConfidenceThreshold:%f\n",yolov5Parameter.confidenceThreshold);
    LOG_INFO(stdout,"NMSThreshold:%f\n",yolov5Parameter.nmsThreshold);
    LOG_INFO(stdout,"objectThreshold:%f\n",yolov5Parameter.objectThreshold);
    LOG_INFO(stdout,"NumberOfClasses:%d\n",yolov5Parameter.numberOfClasses);
Your Name's avatar
Your Name committed
115
116
117
118
119

    return SUCCESS;

}

120
ErrorCode DetectorYOLOV5::Detect(const cv::Mat &srcImage, std::vector<std::size_t> &relInputShape, std::vector<ResultOfDetection> &resultsOfDetection)
Your Name's avatar
Your Name committed
121
122
123
{
    if(srcImage.empty()||srcImage.type()!=CV_8UC3)
    {
liucong's avatar
liucong committed
124
        LOG_ERROR(stdout, "image error!\n");
Your Name's avatar
Your Name committed
125
126
127
        return IMAGE_ERROR;
    }

128
129
    
    inputSize = cv::Size(relInputShape[3], relInputShape[2]);
liucong's avatar
liucong committed
130
    // 数据预处理并转换为NCHW格式
Your Name's avatar
Your Name committed
131
    cv::Mat inputBlob;
liucong's avatar
liucong committed
132
    cv::dnn::blobFromImage(srcImage,
Your Name's avatar
Your Name committed
133
134
135
                    inputBlob,
                    1 / 255.0,
                    inputSize,
liucong's avatar
liucong committed
136
                    cv::Scalar(0, 0, 0),
Your Name's avatar
Your Name committed
137
138
                    true,
                    false);
liucong's avatar
liucong committed
139
140

    // 创建输入数据
141
142
    migraphx::parameter_map inputData;
    inputData[inputName]= migraphx::argument{migraphx::shape(inputShape.type(), relInputShape), (float*)inputBlob.data};
Your Name's avatar
Your Name committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

    // 推理
    std::vector<migraphx::argument> inferenceResults = net.eval(inputData);

    // 获取推理结果
    std::vector<cv::Mat> outs;
    migraphx::argument result = inferenceResults[0]; 

    // 转换为cv::Mat
    migraphx::shape outputShape = result.get_shape();
    int shape[]={outputShape.lens()[0],outputShape.lens()[1],outputShape.lens()[2]};
    cv::Mat out(3,shape,CV_32F);
    memcpy(out.data,result.data(),sizeof(float)*outputShape.elements());
    outs.push_back(out);

    //获取先验框的个数
    int numProposal = outs[0].size[1];
    int numOut = outs[0].size[2];
    //变换输出的维度
    outs[0] = outs[0].reshape(0, numProposal);

    //生成先验框
    std::vector<float> confidences;
    std::vector<cv::Rect> boxes;
    std::vector<int> classIds;
    float ratioh = (float)srcImage.rows / inputSize.height, ratiow = (float)srcImage.cols / inputSize.width;

    //计算cx,cy,w,h,box_sore,class_sore
    int n = 0, rowInd = 0;
    float* pdata = (float*)outs[0].data;
    for (n = 0; n < numProposal; n++)
    {
        float boxScores = pdata[4];
        if (boxScores > yolov5Parameter.objectThreshold)
        {
            cv::Mat scores = outs[0].row(rowInd).colRange(5, numOut);
            cv::Point classIdPoint;
            double maxClassScore;
            cv::minMaxLoc(scores, 0, &maxClassScore, 0, &classIdPoint);
            maxClassScore *= boxScores;
            if (maxClassScore > yolov5Parameter.confidenceThreshold)
            {
                const int classIdx = classIdPoint.x;
                float cx = pdata[0] * ratiow;
                float cy = pdata[1] * ratioh;
                float w = pdata[2] * ratiow;
                float h = pdata[3] * ratioh;

                int left = int(cx - 0.5 * w);
                int top = int(cy - 0.5 * h);

                confidences.push_back((float)maxClassScore);
                boxes.push_back(cv::Rect(left, top, (int)(w), (int)(h)));
                classIds.push_back(classIdx);
            }
        }
        rowInd++;
        pdata += numOut;
    }

    //执行non maximum suppression消除冗余重叠boxes
    std::vector<int> indices;
liucong's avatar
liucong committed
205
    cv::dnn::NMSBoxes(boxes, confidences, yolov5Parameter.confidenceThreshold, yolov5Parameter.nmsThreshold, indices);
Your Name's avatar
Your Name committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    for (size_t i = 0; i < indices.size(); ++i)
    {
        int idx = indices[i];
        int classID=classIds[idx];
        string className=classNames[classID];
        float confidence=confidences[idx];
        cv::Rect box = boxes[idx];

        ResultOfDetection result;
        result.boundingBox=box;
        result.confidence=confidence;// confidence
        result.classID=classID; // label
        result.className=className;
        resultsOfDetection.push_back(result);
    }

    return SUCCESS;
}

}