Merge remote-tracking branch 'upstream/3.4' into merge-3.4
[platform/upstream/opencv.git] / modules / dnn / test / test_common.hpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of the copyright holders may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #ifndef __OPENCV_TEST_COMMON_HPP__
43 #define __OPENCV_TEST_COMMON_HPP__
44
45 #ifdef HAVE_OPENCL
46 #include "opencv2/core/ocl.hpp"
47 #endif
48
49 namespace cv { namespace dnn {
50 CV__DNN_INLINE_NS_BEGIN
51 static inline void PrintTo(const cv::dnn::Backend& v, std::ostream* os)
52 {
53     switch (v) {
54     case DNN_BACKEND_DEFAULT: *os << "DEFAULT"; return;
55     case DNN_BACKEND_HALIDE: *os << "HALIDE"; return;
56     case DNN_BACKEND_INFERENCE_ENGINE: *os << "DLIE"; return;
57     case DNN_BACKEND_OPENCV: *os << "OCV"; return;
58     case DNN_BACKEND_VKCOM: *os << "VKCOM"; return;
59     } // don't use "default:" to emit compiler warnings
60     *os << "DNN_BACKEND_UNKNOWN(" << (int)v << ")";
61 }
62
63 static inline void PrintTo(const cv::dnn::Target& v, std::ostream* os)
64 {
65     switch (v) {
66     case DNN_TARGET_CPU: *os << "CPU"; return;
67     case DNN_TARGET_OPENCL: *os << "OCL"; return;
68     case DNN_TARGET_OPENCL_FP16: *os << "OCL_FP16"; return;
69     case DNN_TARGET_MYRIAD: *os << "MYRIAD"; return;
70     case DNN_TARGET_VULKAN: *os << "VULKAN"; return;
71     case DNN_TARGET_FPGA: *os << "FPGA"; return;
72     } // don't use "default:" to emit compiler warnings
73     *os << "DNN_TARGET_UNKNOWN(" << (int)v << ")";
74 }
75
76 using opencv_test::tuple;
77 using opencv_test::get;
78 static inline void PrintTo(const tuple<cv::dnn::Backend, cv::dnn::Target> v, std::ostream* os)
79 {
80     PrintTo(get<0>(v), os);
81     *os << "/";
82     PrintTo(get<1>(v), os);
83 }
84
85 CV__DNN_INLINE_NS_END
86 }} // namespace
87
88
89 static inline const std::string &getOpenCVExtraDir()
90 {
91     return cvtest::TS::ptr()->get_data_path();
92 }
93
94 static inline void normAssert(cv::InputArray ref, cv::InputArray test, const char *comment = "",
95                        double l1 = 0.00001, double lInf = 0.0001)
96 {
97     double normL1 = cvtest::norm(ref, test, cv::NORM_L1) / ref.getMat().total();
98     EXPECT_LE(normL1, l1) << comment;
99
100     double normInf = cvtest::norm(ref, test, cv::NORM_INF);
101     EXPECT_LE(normInf, lInf) << comment;
102 }
103
104 static std::vector<cv::Rect2d> matToBoxes(const cv::Mat& m)
105 {
106     EXPECT_EQ(m.type(), CV_32FC1);
107     EXPECT_EQ(m.dims, 2);
108     EXPECT_EQ(m.cols, 4);
109
110     std::vector<cv::Rect2d> boxes(m.rows);
111     for (int i = 0; i < m.rows; ++i)
112     {
113         CV_Assert(m.row(i).isContinuous());
114         const float* data = m.ptr<float>(i);
115         double l = data[0], t = data[1], r = data[2], b = data[3];
116         boxes[i] = cv::Rect2d(l, t, r - l, b - t);
117     }
118     return boxes;
119 }
120
121 static inline void normAssertDetections(const std::vector<int>& refClassIds,
122                                  const std::vector<float>& refScores,
123                                  const std::vector<cv::Rect2d>& refBoxes,
124                                  const std::vector<int>& testClassIds,
125                                  const std::vector<float>& testScores,
126                                  const std::vector<cv::Rect2d>& testBoxes,
127                                  const char *comment = "", double confThreshold = 0.0,
128                                  double scores_diff = 1e-5, double boxes_iou_diff = 1e-4)
129 {
130     std::vector<bool> matchedRefBoxes(refBoxes.size(), false);
131     for (int i = 0; i < testBoxes.size(); ++i)
132     {
133         double testScore = testScores[i];
134         if (testScore < confThreshold)
135             continue;
136
137         int testClassId = testClassIds[i];
138         const cv::Rect2d& testBox = testBoxes[i];
139         bool matched = false;
140         for (int j = 0; j < refBoxes.size() && !matched; ++j)
141         {
142             if (!matchedRefBoxes[j] && testClassId == refClassIds[j] &&
143                 std::abs(testScore - refScores[j]) < scores_diff)
144             {
145                 double interArea = (testBox & refBoxes[j]).area();
146                 double iou = interArea / (testBox.area() + refBoxes[j].area() - interArea);
147                 if (std::abs(iou - 1.0) < boxes_iou_diff)
148                 {
149                     matched = true;
150                     matchedRefBoxes[j] = true;
151                 }
152             }
153         }
154         if (!matched)
155             std::cout << cv::format("Unmatched prediction: class %d score %f box ",
156                                     testClassId, testScore) << testBox << std::endl;
157         EXPECT_TRUE(matched) << comment;
158     }
159
160     // Check unmatched reference detections.
161     for (int i = 0; i < refBoxes.size(); ++i)
162     {
163         if (!matchedRefBoxes[i] && refScores[i] > confThreshold)
164         {
165             std::cout << cv::format("Unmatched reference: class %d score %f box ",
166                                     refClassIds[i], refScores[i]) << refBoxes[i] << std::endl;
167             EXPECT_LE(refScores[i], confThreshold) << comment;
168         }
169     }
170 }
171
172 // For SSD-based object detection networks which produce output of shape 1x1xNx7
173 // where N is a number of detections and an every detection is represented by
174 // a vector [batchId, classId, confidence, left, top, right, bottom].
175 static inline void normAssertDetections(cv::Mat ref, cv::Mat out, const char *comment = "",
176                                  double confThreshold = 0.0, double scores_diff = 1e-5,
177                                  double boxes_iou_diff = 1e-4)
178 {
179     CV_Assert(ref.total() % 7 == 0);
180     CV_Assert(out.total() % 7 == 0);
181     ref = ref.reshape(1, ref.total() / 7);
182     out = out.reshape(1, out.total() / 7);
183
184     cv::Mat refClassIds, testClassIds;
185     ref.col(1).convertTo(refClassIds, CV_32SC1);
186     out.col(1).convertTo(testClassIds, CV_32SC1);
187     std::vector<float> refScores(ref.col(2)), testScores(out.col(2));
188     std::vector<cv::Rect2d> refBoxes = matToBoxes(ref.colRange(3, 7));
189     std::vector<cv::Rect2d> testBoxes = matToBoxes(out.colRange(3, 7));
190     normAssertDetections(refClassIds, refScores, refBoxes, testClassIds, testScores,
191                          testBoxes, comment, confThreshold, scores_diff, boxes_iou_diff);
192 }
193
194 static inline bool readFileInMemory(const std::string& filename, std::string& content)
195 {
196     std::ios::openmode mode = std::ios::in | std::ios::binary;
197     std::ifstream ifs(filename.c_str(), mode);
198     if (!ifs.is_open())
199         return false;
200
201     content.clear();
202
203     ifs.seekg(0, std::ios::end);
204     content.reserve(ifs.tellg());
205     ifs.seekg(0, std::ios::beg);
206
207     content.assign((std::istreambuf_iterator<char>(ifs)),
208                    std::istreambuf_iterator<char>());
209
210     return true;
211 }
212
213 namespace opencv_test {
214
215 using namespace cv::dnn;
216
217 static inline
218 testing::internal::ParamGenerator< tuple<Backend, Target> > dnnBackendsAndTargets(
219         bool withInferenceEngine = true,
220         bool withHalide = false,
221         bool withCpuOCV = true,
222         bool withVkCom = true
223 )
224 {
225     std::vector< tuple<Backend, Target> > targets;
226     std::vector< Target > available;
227     if (withHalide)
228     {
229         available = getAvailableTargets(DNN_BACKEND_HALIDE);
230         for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
231             targets.push_back(make_tuple(DNN_BACKEND_HALIDE, *i));
232     }
233     if (withInferenceEngine)
234     {
235         available = getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE);
236         for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
237             targets.push_back(make_tuple(DNN_BACKEND_INFERENCE_ENGINE, *i));
238     }
239     if (withVkCom)
240     {
241         available = getAvailableTargets(DNN_BACKEND_VKCOM);
242         for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
243             targets.push_back(make_tuple(DNN_BACKEND_VKCOM, *i));
244     }
245     {
246         available = getAvailableTargets(DNN_BACKEND_OPENCV);
247         for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
248         {
249             if (!withCpuOCV && *i == DNN_TARGET_CPU)
250                 continue;
251             targets.push_back(make_tuple(DNN_BACKEND_OPENCV, *i));
252         }
253     }
254     if (targets.empty())  // validate at least CPU mode
255         targets.push_back(make_tuple(DNN_BACKEND_OPENCV, DNN_TARGET_CPU));
256     return testing::ValuesIn(targets);
257 }
258
259 } // namespace
260
261
262 namespace opencv_test {
263 using namespace cv::dnn;
264
265 class DNNTestLayer : public TestWithParam<tuple<Backend, Target> >
266 {
267 public:
268     dnn::Backend backend;
269     dnn::Target target;
270     double default_l1, default_lInf;
271
272     DNNTestLayer()
273     {
274         backend = (dnn::Backend)(int)get<0>(GetParam());
275         target = (dnn::Target)(int)get<1>(GetParam());
276         getDefaultThresholds(backend, target, &default_l1, &default_lInf);
277     }
278
279    static void getDefaultThresholds(int backend, int target, double* l1, double* lInf)
280    {
281        if (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD)
282        {
283            *l1 = 4e-3;
284            *lInf = 2e-2;
285        }
286        else
287        {
288            *l1 = 1e-5;
289            *lInf = 1e-4;
290        }
291    }
292
293     static void checkBackend(int backend, int target, Mat* inp = 0, Mat* ref = 0)
294     {
295        if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
296        {
297            if (inp && ref && inp->dims == 4 && ref->dims == 4 &&
298                inp->size[0] != 1 && inp->size[0] != ref->size[0])
299                throw SkipTestException("Inconsistent batch size of input and output blobs for Myriad plugin");
300        }
301    }
302
303 protected:
304     void checkBackend(Mat* inp = 0, Mat* ref = 0)
305     {
306         checkBackend(backend, target, inp, ref);
307     }
308 };
309
310 } // namespace
311
312 #endif