1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
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.
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.
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.
42 #include "test_precomp.hpp"
43 #include "npy_blob.hpp"
44 #include <opencv2/dnn/shape_utils.hpp>
45 #include <opencv2/dnn/layer.details.hpp> // CV_DNN_REGISTER_LAYER_CLASS
51 using namespace testing;
53 using namespace cv::dnn;
55 template<typename TStr>
56 static std::string _tf(TStr filename, bool inTorchDir = true)
62 return findDataFile(path, false);
65 TEST(Torch_Importer, simple_read)
68 ASSERT_NO_THROW(net = readNetFromTorch(_tf("net_simple_net.txt"), false));
69 ASSERT_FALSE(net.empty());
72 class Test_Torch_layers : public DNNTestLayer
75 void runTorchNet(const String& prefix, String outLayerName = "",
76 bool check2ndBlob = false, bool isBinary = false, bool evaluate = true,
77 double l1 = 0.0, double lInf = 0.0)
79 String suffix = (isBinary) ? ".dat" : ".txt";
82 ASSERT_NO_THROW( inp = readTorchBlob(_tf(prefix + "_input" + suffix), isBinary) );
83 ASSERT_NO_THROW( outRef = readTorchBlob(_tf(prefix + "_output" + suffix), isBinary) );
85 checkBackend(backend, target, &inp, &outRef);
87 Net net = readNetFromTorch(_tf(prefix + "_net" + suffix), isBinary, evaluate);
88 ASSERT_FALSE(net.empty());
90 net.setPreferableBackend(backend);
91 net.setPreferableTarget(target);
93 if (outLayerName.empty())
94 outLayerName = net.getLayerNames().back();
97 std::vector<Mat> outBlobs;
98 net.forward(outBlobs, outLayerName);
99 l1 = l1 ? l1 : default_l1;
100 lInf = lInf ? lInf : default_lInf;
101 normAssert(outRef, outBlobs[0], "", l1, lInf);
103 if (check2ndBlob && backend != DNN_BACKEND_INFERENCE_ENGINE)
105 Mat out2 = outBlobs[1];
106 Mat ref2 = readTorchBlob(_tf(prefix + "_output_2" + suffix), isBinary);
107 normAssert(out2, ref2, "", l1, lInf);
112 TEST_P(Test_Torch_layers, run_convolution)
114 // Output reference values are in range [23.4018, 72.0181]
115 double l1 = (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) ? 0.08 : default_l1;
116 double lInf = (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) ? 0.42 : default_lInf;
117 runTorchNet("net_conv", "", false, true, true, l1, lInf);
120 TEST_P(Test_Torch_layers, run_pool_max)
122 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
123 throw SkipTestException("");
124 runTorchNet("net_pool_max", "", true);
127 TEST_P(Test_Torch_layers, run_pool_ave)
129 runTorchNet("net_pool_ave");
132 TEST_P(Test_Torch_layers, run_reshape_change_batch_size)
134 runTorchNet("net_reshape");
137 TEST_P(Test_Torch_layers, run_reshape)
139 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE >= 2018040000
140 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
141 throw SkipTestException("Test is disabled for OpenVINO 2018R4");
143 runTorchNet("net_reshape_batch");
144 runTorchNet("net_reshape_channels", "", false, true);
147 TEST_P(Test_Torch_layers, run_reshape_single_sample)
149 // Reference output values in range [14.4586, 18.4492].
150 runTorchNet("net_reshape_single_sample", "", false, false, true,
151 (target == DNN_TARGET_MYRIAD || target == DNN_TARGET_OPENCL_FP16) ? 0.033 : default_l1,
152 (target == DNN_TARGET_MYRIAD || target == DNN_TARGET_OPENCL_FP16) ? 0.05 : default_lInf);
155 TEST_P(Test_Torch_layers, run_linear)
157 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
158 throw SkipTestException("");
159 runTorchNet("net_linear_2d");
162 TEST_P(Test_Torch_layers, run_concat)
164 runTorchNet("net_concat", "l5_torchMerge");
167 TEST_P(Test_Torch_layers, run_depth_concat)
169 runTorchNet("net_depth_concat", "", false, true, true, 0.0,
170 target == DNN_TARGET_OPENCL_FP16 ? 0.021 : 0.0);
173 TEST_P(Test_Torch_layers, run_deconv)
175 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE >= 2018040000
176 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
177 throw SkipTestException("Test is disabled for OpenVINO 2018R4");
179 runTorchNet("net_deconv");
182 TEST_P(Test_Torch_layers, run_batch_norm)
184 runTorchNet("net_batch_norm", "", false, true);
185 runTorchNet("net_batch_norm_train", "", false, true, false);
188 TEST_P(Test_Torch_layers, net_prelu)
190 runTorchNet("net_prelu");
193 TEST_P(Test_Torch_layers, net_cadd_table)
195 runTorchNet("net_cadd_table");
198 TEST_P(Test_Torch_layers, net_softmax)
200 runTorchNet("net_softmax");
201 runTorchNet("net_softmax_spatial");
204 TEST_P(Test_Torch_layers, net_logsoftmax)
206 runTorchNet("net_logsoftmax");
207 runTorchNet("net_logsoftmax_spatial");
210 TEST_P(Test_Torch_layers, net_lp_pooling)
212 runTorchNet("net_lp_pooling_square", "", false, true);
213 runTorchNet("net_lp_pooling_power", "", false, true);
216 TEST_P(Test_Torch_layers, net_conv_gemm_lrn)
218 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
219 throw SkipTestException("");
220 runTorchNet("net_conv_gemm_lrn", "", false, true, true,
221 target == DNN_TARGET_OPENCL_FP16 ? 0.046 : 0.0,
222 target == DNN_TARGET_OPENCL_FP16 ? 0.023 : 0.0);
225 TEST_P(Test_Torch_layers, net_inception_block)
227 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE == 2018030000
228 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
229 throw SkipTestException("");
231 runTorchNet("net_inception_block", "", false, true);
234 TEST_P(Test_Torch_layers, net_normalize)
236 runTorchNet("net_normalize", "", false, true);
239 TEST_P(Test_Torch_layers, net_padding)
241 runTorchNet("net_padding", "", false, true);
242 runTorchNet("net_spatial_zero_padding", "", false, true);
243 runTorchNet("net_spatial_reflection_padding", "", false, true);
246 TEST_P(Test_Torch_layers, net_non_spatial)
248 if (backend == DNN_BACKEND_INFERENCE_ENGINE &&
249 (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
250 throw SkipTestException("");
251 runTorchNet("net_non_spatial", "", false, true);
254 TEST_P(Test_Torch_layers, run_paralel)
256 if (backend != DNN_BACKEND_OPENCV || target != DNN_TARGET_CPU)
257 throw SkipTestException("");
258 runTorchNet("net_parallel", "l5_torchMerge");
261 TEST_P(Test_Torch_layers, net_residual)
263 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE == 2018050000
264 if (backend == DNN_BACKEND_INFERENCE_ENGINE && (target == DNN_TARGET_OPENCL ||
265 target == DNN_TARGET_OPENCL_FP16))
266 throw SkipTestException("Test is disabled for OpenVINO 2018R5");
268 runTorchNet("net_residual", "", false, true);
271 class Test_Torch_nets : public DNNTestLayer {};
273 TEST_P(Test_Torch_nets, OpenFace_accuracy)
275 #if defined(INF_ENGINE_RELEASE)
276 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
277 throw SkipTestException("Test is disabled for Myriad targets");
281 const string model = findDataFile("dnn/openface_nn4.small2.v1.t7", false);
282 Net net = readNetFromTorch(model);
284 net.setPreferableBackend(backend);
285 net.setPreferableTarget(target);
287 Mat sample = imread(findDataFile("cv/shared/lena.png", false));
288 Mat sampleF32(sample.size(), CV_32FC3);
289 sample.convertTo(sampleF32, sampleF32.type());
291 resize(sampleF32, sampleF32, Size(96, 96), 0, 0, INTER_NEAREST);
293 Mat inputBlob = blobFromImage(sampleF32, 1.0, Size(), Scalar(), /*swapRB*/true);
295 net.setInput(inputBlob);
296 Mat out = net.forward();
298 // Reference output values are in range [-0.17212, 0.263492]
299 // on Myriad problem layer: l4_Pooling - does not use pads_begin
300 float l1 = (target == DNN_TARGET_OPENCL_FP16) ? 4e-4 : 1e-5;
301 float lInf = (target == DNN_TARGET_OPENCL_FP16) ? 1.5e-3 : 1e-3;
302 Mat outRef = readTorchBlob(_tf("net_openface_output.dat"), true);
303 normAssert(out, outRef, "", l1, lInf);
306 static Mat getSegmMask(const Mat& scores)
308 const int rows = scores.size[2];
309 const int cols = scores.size[3];
310 const int numClasses = scores.size[1];
312 Mat maxCl = Mat::zeros(rows, cols, CV_8UC1);
313 Mat maxVal(rows, cols, CV_32FC1, Scalar(0));
314 for (int ch = 0; ch < numClasses; ch++)
316 for (int row = 0; row < rows; row++)
318 const float *ptrScore = scores.ptr<float>(0, ch, row);
319 uint8_t *ptrMaxCl = maxCl.ptr<uint8_t>(row);
320 float *ptrMaxVal = maxVal.ptr<float>(row);
321 for (int col = 0; col < cols; col++)
323 if (ptrScore[col] > ptrMaxVal[col])
325 ptrMaxVal[col] = ptrScore[col];
326 ptrMaxCl[col] = (uchar)ch;
334 // Computer per-class intersection over union metric.
335 static void normAssertSegmentation(const Mat& ref, const Mat& test)
337 CV_Assert_N(ref.dims == 4, test.dims == 4);
338 const int numClasses = ref.size[1];
339 CV_Assert(numClasses == test.size[1]);
341 Mat refMask = getSegmMask(ref);
342 Mat testMask = getSegmMask(test);
343 EXPECT_EQ(countNonZero(refMask != testMask), 0);
346 TEST_P(Test_Torch_nets, ENet_accuracy)
349 if (backend == DNN_BACKEND_INFERENCE_ENGINE ||
350 (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16))
351 throw SkipTestException("");
355 const string model = findDataFile("dnn/Enet-model-best.net", false);
356 net = readNetFromTorch(model, true);
357 ASSERT_TRUE(!net.empty());
360 net.setPreferableBackend(backend);
361 net.setPreferableTarget(target);
363 Mat sample = imread(_tf("street.png", false));
364 Mat inputBlob = blobFromImage(sample, 1./255, Size(), Scalar(), /*swapRB*/true);
366 net.setInput(inputBlob, "");
367 Mat out = net.forward();
368 Mat ref = blobFromNPY(_tf("torch_enet_prob.npy", false));
369 // Due to numerical instability in Pooling-Unpooling layers (indexes jittering)
370 // thresholds for ENet must be changed. Accuracy of results was checked on
371 // Cityscapes dataset and difference in mIOU with Torch is 10E-4%
372 normAssert(ref, out, "", 0.00044, /*target == DNN_TARGET_CPU ? 0.453 : */0.552);
373 normAssertSegmentation(ref, out);
376 for (int i = 0; i < N; i++)
378 net.setInput(inputBlob, "");
379 Mat out = net.forward();
380 normAssert(ref, out, "", 0.00044, /*target == DNN_TARGET_CPU ? 0.453 : */0.552);
381 normAssertSegmentation(ref, out);
385 // Check accuracy of style transfer models from https://github.com/jcjohnson/fast-neural-style
386 // th fast_neural_style.lua \
387 // -input_image ~/opencv_extra/testdata/dnn/googlenet_1.png \
388 // -output_image lena.png \
389 // -median_filter 0 \
391 // -model models/eccv16/starry_night.t7
392 // th fast_neural_style.lua \
393 // -input_image ~/opencv_extra/testdata/dnn/googlenet_1.png \
394 // -output_image lena.png \
395 // -median_filter 0 \
397 // -model models/instance_norm/feathers.t7
398 TEST_P(Test_Torch_nets, FastNeuralStyle_accuracy)
400 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LE(2018050000)
401 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD
402 && getInferenceEngineVPUType() == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X)
403 throw SkipTestException("Test is disabled for OpenVINO <= 2018R5 + MyriadX target");
408 #if defined(INF_ENGINE_RELEASE)
409 #if INF_ENGINE_RELEASE <= 2018050000
410 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_OPENCL)
411 throw SkipTestException("");
415 std::string models[] = {"dnn/fast_neural_style_eccv16_starry_night.t7",
416 "dnn/fast_neural_style_instance_norm_feathers.t7"};
417 std::string targets[] = {"dnn/lena_starry_night.png", "dnn/lena_feathers.png"};
419 for (int i = 0; i < 2; ++i)
421 const string model = findDataFile(models[i], false);
422 Net net = readNetFromTorch(model);
424 net.setPreferableBackend(backend);
425 net.setPreferableTarget(target);
427 Mat img = imread(findDataFile("dnn/googlenet_1.png", false));
428 Mat inputBlob = blobFromImage(img, 1.0, Size(), Scalar(103.939, 116.779, 123.68), false);
430 net.setInput(inputBlob);
431 Mat out = net.forward();
434 getPlane(out, 0, 0) += 103.939;
435 getPlane(out, 0, 1) += 116.779;
436 getPlane(out, 0, 2) += 123.68;
437 out = cv::min(cv::max(0, out), 255);
439 Mat ref = imread(findDataFile(targets[i]));
440 Mat refBlob = blobFromImage(ref, 1.0, Size(), Scalar(), false);
442 if (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD)
444 double normL1 = cvtest::norm(refBlob, out, cv::NORM_L1) / refBlob.total();
445 if (target == DNN_TARGET_MYRIAD)
446 EXPECT_LE(normL1, 4.0f);
448 EXPECT_LE(normL1, 0.6f);
451 normAssert(out, refBlob, "", 0.5, 1.1);
455 INSTANTIATE_TEST_CASE_P(/**/, Test_Torch_nets, dnnBackendsAndTargets());
457 // Test a custom layer
458 // https://github.com/torch/nn/blob/master/doc/convolution.md#nn.SpatialUpSamplingNearest
459 class SpatialUpSamplingNearestLayer CV_FINAL : public Layer
462 SpatialUpSamplingNearestLayer(const LayerParams ¶ms) : Layer(params)
464 scale = params.get<int>("scale_factor");
467 static Ptr<Layer> create(LayerParams& params)
469 return Ptr<Layer>(new SpatialUpSamplingNearestLayer(params));
472 virtual bool getMemoryShapes(const std::vector<std::vector<int> > &inputs,
473 const int requiredOutputs,
474 std::vector<std::vector<int> > &outputs,
475 std::vector<std::vector<int> > &internals) const CV_OVERRIDE
477 std::vector<int> outShape(4);
478 outShape[0] = inputs[0][0]; // batch size
479 outShape[1] = inputs[0][1]; // number of channels
480 outShape[2] = scale * inputs[0][2];
481 outShape[3] = scale * inputs[0][3];
482 outputs.assign(1, outShape);
486 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays) CV_OVERRIDE
489 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
491 std::vector<Mat> inputs, outputs;
492 inputs_arr.getMatVector(inputs);
493 outputs_arr.getMatVector(outputs);
495 Mat& inp = inputs[0];
496 Mat& out = outputs[0];
497 const int outHeight = out.size[2];
498 const int outWidth = out.size[3];
499 for (size_t n = 0; n < inp.size[0]; ++n)
501 for (size_t ch = 0; ch < inp.size[1]; ++ch)
503 resize(getPlane(inp, n, ch), getPlane(out, n, ch),
504 Size(outWidth, outHeight), 0, 0, INTER_NEAREST);
513 TEST_P(Test_Torch_layers, upsampling_nearest)
515 // Test a custom layer.
516 CV_DNN_REGISTER_LAYER_CLASS(SpatialUpSamplingNearest, SpatialUpSamplingNearestLayer);
519 runTorchNet("net_spatial_upsampling_nearest", "", false, true);
523 LayerFactory::unregisterLayer("SpatialUpSamplingNearest");
526 LayerFactory::unregisterLayer("SpatialUpSamplingNearest");
528 // Test an implemented layer.
529 runTorchNet("net_spatial_upsampling_nearest", "", false, true);
532 INSTANTIATE_TEST_CASE_P(/**/, Test_Torch_layers, dnnBackendsAndTargets());