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) 2017, Intel Corporation, 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 <opencv2/core/ocl.hpp>
44 #include "npy_blob.hpp"
45 #include <opencv2/dnn/shape_utils.hpp>
46 #include <opencv2/dnn/all_layers.hpp>
47 #include <opencv2/dnn/layer.details.hpp> // CV_DNN_REGISTER_LAYER_CLASS
49 #ifdef HAVE_INF_ENGINE
53 namespace opencv_test { namespace {
55 template<typename TString>
56 static String _tf(TString filename)
58 String basetestdir = getOpenCVExtraDir();
59 size_t len = basetestdir.size();
60 if(len > 0 && basetestdir[len-1] != '/' && basetestdir[len-1] != '\\')
61 return (basetestdir + "/dnn/layers") + filename;
62 return (basetestdir + "dnn/layers/") + filename;
65 void runLayer(Ptr<Layer> layer, std::vector<Mat> &inpBlobs, std::vector<Mat> &outBlobs)
67 size_t ninputs = inpBlobs.size();
68 std::vector<Mat> inp(ninputs), outp, intp;
69 std::vector<MatShape> inputs, outputs, internals;
71 for (size_t i = 0; i < ninputs; i++)
73 inp[i] = inpBlobs[i].clone();
74 inputs.push_back(shape(inp[i]));
77 layer->getMemoryShapes(inputs, 0, outputs, internals);
78 for (size_t i = 0; i < outputs.size(); i++)
80 outp.push_back(Mat(outputs[i], CV_32F));
82 for (size_t i = 0; i < internals.size(); i++)
84 intp.push_back(Mat(internals[i], CV_32F));
87 layer->finalize(inp, outp);
88 layer->forward(inp, outp, intp);
90 size_t noutputs = outp.size();
91 outBlobs.resize(noutputs);
92 for (size_t i = 0; i < noutputs; i++)
93 outBlobs[i] = outp[i];
96 class Test_Caffe_layers : public DNNTestLayer
99 void testLayerUsingCaffeModels(const String& basename, bool useCaffeModel = false,
100 bool useCommonInputBlob = true, double l1 = 0.0,
103 String prototxt = _tf(basename + ".prototxt");
104 String caffemodel = _tf(basename + ".caffemodel");
106 String inpfile = (useCommonInputBlob) ? _tf("blob.npy") : _tf(basename + ".input.npy");
107 String outfile = _tf(basename + ".npy");
109 Mat inp = blobFromNPY(inpfile);
110 Mat ref = blobFromNPY(outfile);
111 checkBackend(&inp, &ref);
113 Net net = readNetFromCaffe(prototxt, (useCaffeModel) ? caffemodel : String());
114 ASSERT_FALSE(net.empty());
116 net.setPreferableBackend(backend);
117 net.setPreferableTarget(target);
119 net.setInput(inp, "input");
120 Mat out = net.forward("output");
122 normAssert(ref, out, "", l1 ? l1 : default_l1, lInf ? lInf : default_lInf);
126 TEST_P(Test_Caffe_layers, Softmax)
128 testLayerUsingCaffeModels("layer_softmax");
131 TEST_P(Test_Caffe_layers, LRN)
133 testLayerUsingCaffeModels("layer_lrn_spatial");
134 testLayerUsingCaffeModels("layer_lrn_channels");
137 TEST_P(Test_Caffe_layers, Convolution)
139 testLayerUsingCaffeModels("layer_convolution", true);
142 TEST_P(Test_Caffe_layers, DeConvolution)
144 testLayerUsingCaffeModels("layer_deconvolution", true, false);
147 TEST_P(Test_Caffe_layers, InnerProduct)
149 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
150 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
151 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
152 applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
153 testLayerUsingCaffeModels("layer_inner_product", true);
156 TEST_P(Test_Caffe_layers, Pooling_max)
158 testLayerUsingCaffeModels("layer_pooling_max");
161 TEST_P(Test_Caffe_layers, Pooling_ave)
163 testLayerUsingCaffeModels("layer_pooling_ave");
166 TEST_P(Test_Caffe_layers, MVN)
168 testLayerUsingCaffeModels("layer_mvn");
171 void testReshape(const MatShape& inputShape, const MatShape& targetShape,
172 int axis = 0, int num_axes = -1,
173 MatShape mask = MatShape())
176 params.set("axis", axis);
177 params.set("num_axes", num_axes);
180 params.set("dim", DictValue::arrayInt<int*>(&mask[0], mask.size()));
183 Mat inp(inputShape.size(), &inputShape[0], CV_32F);
184 std::vector<Mat> inpVec(1, inp);
185 std::vector<Mat> outVec, intVec;
187 Ptr<Layer> rl = LayerFactory::createLayerInstance("Reshape", params);
188 runLayer(rl, inpVec, outVec);
190 Mat& out = outVec[0];
191 MatShape shape(out.size.p, out.size.p + out.dims);
192 EXPECT_EQ(shape, targetShape);
195 TEST(Layer_Test_Reshape, Accuracy)
198 int inp[] = {4, 3, 1, 2};
199 int out[] = {4, 3, 2};
200 testReshape(MatShape(inp, inp + 4), MatShape(out, out + 3), 2, 1);
203 int inp[] = {1, 128, 4, 4};
204 int out[] = {1, 2048};
205 int mask[] = {-1, 2048};
206 testReshape(MatShape(inp, inp + 4), MatShape(out, out + 2), 0, -1,
207 MatShape(mask, mask + 2));
210 int inp[] = {1, 2, 3};
211 int out[] = {3, 1, 2};
212 int mask[] = {3, 1, 2};
213 testReshape(MatShape(inp, inp + 3), MatShape(out, out + 3), 0, -1,
214 MatShape(mask, mask + 3));
218 TEST_P(Test_Caffe_layers, BatchNorm)
220 testLayerUsingCaffeModels("layer_batch_norm", true);
221 testLayerUsingCaffeModels("layer_batch_norm_local_stats", true, false);
224 TEST_P(Test_Caffe_layers, ReLU)
226 testLayerUsingCaffeModels("layer_relu");
229 TEST_P(Test_Caffe_layers, Dropout)
231 testLayerUsingCaffeModels("layer_dropout");
234 TEST_P(Test_Caffe_layers, Concat)
236 #if defined(INF_ENGINE_RELEASE)
237 #if INF_ENGINE_VER_MAJOR_GE(2019010000) && INF_ENGINE_VER_MAJOR_LT(2019020000)
238 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
239 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_2019R1, CV_TEST_TAG_DNN_SKIP_IE_2019R1_1);
240 #elif INF_ENGINE_VER_MAJOR_EQ(2019020000)
241 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_OPENCL)
242 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_OPENCL, CV_TEST_TAG_DNN_SKIP_IE_2019R2);
245 testLayerUsingCaffeModels("layer_concat");
246 testLayerUsingCaffeModels("layer_concat_optim", true, false);
247 testLayerUsingCaffeModels("layer_concat_shared_input", true, false);
250 TEST_P(Test_Caffe_layers, Fused_Concat)
252 if (backend == DNN_BACKEND_INFERENCE_ENGINE && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
253 applyTestTag(target == DNN_TARGET_OPENCL ? CV_TEST_TAG_DNN_SKIP_IE_OPENCL : CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16);
270 lp.name = "someLayer";
271 interLayer = net.addLayerToPrev(lp.name, lp.type, lp);
277 lp.name = "testConcat";
278 int id = net.addLayer(lp.name, lp.type, lp);
279 net.connect(interLayer, 0, id, 0);
280 net.connect(interLayer, 0, id, 1);
282 int shape[] = {1, 2, 3, 4};
283 Mat input(4, shape, CV_32F);
284 randu(input, 0.0f, 1.0f); // [0, 1] to make AbsVal an identity transformation.
287 net.setPreferableBackend(backend);
288 net.setPreferableTarget(target);
289 Mat out = net.forward();
291 normAssert(slice(out, Range::all(), Range(0, 2), Range::all(), Range::all()), input, "", default_l1, default_lInf);
292 normAssert(slice(out, Range::all(), Range(2, 4), Range::all(), Range::all()), input, "", default_l1, default_lInf);
295 TEST_P(Test_Caffe_layers, Eltwise)
297 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
298 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
299 testLayerUsingCaffeModels("layer_eltwise");
302 TEST_P(Test_Caffe_layers, PReLU)
304 testLayerUsingCaffeModels("layer_prelu", true);
307 // TODO: fix an unstable test case
308 TEST_P(Test_Caffe_layers, layer_prelu_fc)
310 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
311 applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
312 // Reference output values are in range [-0.0001, 10.3906]
313 double l1 = (target == DNN_TARGET_MYRIAD) ? 0.005 : 0.0;
314 double lInf = (target == DNN_TARGET_MYRIAD) ? 0.021 : 0.0;
315 testLayerUsingCaffeModels("layer_prelu_fc", true, false, l1, lInf);
318 TEST_P(Test_Caffe_layers, Reshape_Split_Slice)
320 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
321 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
323 Net net = readNetFromCaffe(_tf("reshape_and_slice_routines.prototxt"));
324 ASSERT_FALSE(net.empty());
326 net.setPreferableBackend(backend);
327 net.setPreferableTarget(target);
329 Mat input(6, 12, CV_32F);
331 rng.fill(input, RNG::UNIFORM, -1, 1);
333 net.setInput(input, "input");
334 Mat output = net.forward("output");
336 normAssert(input, output, "", default_l1, default_lInf);
339 TEST_P(Test_Caffe_layers, Conv_Elu)
341 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE <= 2018050000
342 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
343 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_2018R5);
346 Net net = readNetFromTensorflow(_tf("layer_elu_model.pb"));
347 ASSERT_FALSE(net.empty());
349 Mat inp = blobFromNPY(_tf("layer_elu_in.npy"));
350 Mat ref = blobFromNPY(_tf("layer_elu_out.npy"));
352 net.setInput(inp, "input");
353 net.setPreferableBackend(backend);
354 net.setPreferableTarget(target);
355 Mat out = net.forward();
357 normAssert(ref, out, "", default_l1, default_lInf);
360 class Layer_LSTM_Test : public ::testing::Test
365 Ptr<LSTMLayer> layer;
366 std::vector<Mat> inputs, outputs;
370 void init(const MatShape &inpShape_, const MatShape &outShape_,
371 bool produceCellOutput, bool useTimestampDim)
373 numInp = total(inpShape_);
374 numOut = total(outShape_);
376 Wh = Mat::ones(4 * numOut, numOut, CV_32F);
377 Wx = Mat::ones(4 * numOut, numInp, CV_32F);
378 b = Mat::ones(4 * numOut, 1, CV_32F);
385 lp.set<bool>("produce_cell_output", produceCellOutput);
386 lp.set<bool>("use_timestamp_dim", useTimestampDim);
388 layer = LSTMLayer::create(lp);
389 layer->setOutShape(outShape_);
393 TEST_F(Layer_LSTM_Test, get_set_test)
396 MatShape inpShape = shape(5, 3, 2);
397 MatShape outShape = shape(3, 1, 2);
398 MatShape inpResShape = concat(shape(TN), inpShape);
399 MatShape outResShape = concat(shape(TN), outShape);
401 init(inpShape, outShape, true, false);
402 layer->setOutShape(outShape);
404 Mat C((int)outResShape.size(), &outResShape[0], CV_32F);
409 Mat inp((int)inpResShape.size(), &inpResShape[0], CV_32F);
412 inputs.push_back(inp);
413 runLayer(layer, inputs, outputs);
415 EXPECT_EQ(2u, outputs.size());
417 print(outResShape, "outResShape");
418 print(shape(outputs[0]), "out0");
419 print(shape(outputs[0]), "out1");
421 EXPECT_EQ(outResShape, shape(outputs[0]));
422 EXPECT_EQ(outResShape, shape(outputs[1]));
424 EXPECT_EQ(0, layer->inputNameToIndex("x"));
425 EXPECT_EQ(0, layer->outputNameToIndex("h"));
426 EXPECT_EQ(1, layer->outputNameToIndex("c"));
429 TEST(Layer_LSTM_Test_Accuracy_with_, CaffeRecurrent)
433 lp.blobs[0] = blobFromNPY(_tf("lstm.prototxt.w_2.npy")); // Wh
434 lp.blobs[1] = blobFromNPY(_tf("lstm.prototxt.w_0.npy")); // Wx
435 lp.blobs[2] = blobFromNPY(_tf("lstm.prototxt.w_1.npy")); // bias
436 Ptr<LSTMLayer> layer = LSTMLayer::create(lp);
438 Mat inp = blobFromNPY(_tf("recurrent.input.npy"));
439 std::vector<Mat> inputs(1, inp), outputs;
440 runLayer(layer, inputs, outputs);
442 Mat h_t_reference = blobFromNPY(_tf("lstm.prototxt.h_1.npy"));
443 normAssert(h_t_reference, outputs[0]);
446 TEST(Layer_RNN_Test_Accuracy_with_, CaffeRecurrent)
448 Ptr<RNNLayer> layer = RNNLayer::create(LayerParams());
451 blobFromNPY(_tf("rnn.prototxt.w_0.npy")),
452 blobFromNPY(_tf("rnn.prototxt.w_1.npy")),
453 blobFromNPY(_tf("rnn.prototxt.w_2.npy")),
454 blobFromNPY(_tf("rnn.prototxt.w_3.npy")),
455 blobFromNPY(_tf("rnn.prototxt.w_4.npy")) );
457 std::vector<Mat> output, input(1, blobFromNPY(_tf("recurrent.input.npy")));
458 runLayer(layer, input, output);
460 Mat h_ref = blobFromNPY(_tf("rnn.prototxt.h_1.npy"));
461 normAssert(h_ref, output[0]);
464 TEST(Layer_LSTM_Test_Accuracy_, Reverse)
466 // This handcrafted setup calculates (approximately) the prefix sum of the
467 // input, assuming the inputs are suitably small.
468 cv::Mat input(2, 1, CV_32FC1);
469 input.at<float>(0, 0) = 1e-5f;
470 input.at<float>(1, 0) = 2e-5f;
472 cv::Mat Wx(4, 1, CV_32FC1);
473 Wx.at<float>(0, 0) = 0.f; // Input gate
474 Wx.at<float>(1, 0) = 0.f; // Forget gate
475 Wx.at<float>(2, 0) = 0.f; // Output gate
476 Wx.at<float>(3, 0) = 1.f; // Update signal
478 cv::Mat Wh(4, 1, CV_32FC1);
479 Wh.at<float>(0, 0) = 0.f; // Input gate
480 Wh.at<float>(1, 0) = 0.f; // Forget gate
481 Wh.at<float>(2, 0) = 0.f; // Output gate
482 Wh.at<float>(3, 0) = 0.f; // Update signal
484 cv::Mat bias(4, 1, CV_32FC1);
485 bias.at<float>(0, 0) = 1e10f; // Input gate - always allows input to c
486 bias.at<float>(1, 0) = 1e10f; // Forget gate - never forget anything on c
487 bias.at<float>(2, 0) = 1e10f; // Output gate - always output everything
488 bias.at<float>(3, 0) = 0.f; // Update signal
491 lp.set("reverse", true);
492 lp.set("use_timestamp_dim", true);
494 lp.blobs.push_back(Wh);
495 lp.blobs.push_back(Wx);
496 lp.blobs.push_back(bias);
498 cv::Ptr<cv::dnn::LSTMLayer> layer = LSTMLayer::create(lp);
499 std::vector<cv::Mat> outputs;
500 std::vector<cv::Mat> inputs;
501 inputs.push_back(input);
502 runLayer(layer, inputs, outputs);
504 ASSERT_EQ(1, outputs.size());
505 cv::Mat out = outputs[0];
506 ASSERT_EQ(3, out.dims);
507 ASSERT_EQ(shape(2, 1, 1), shape(out));
508 float* data = reinterpret_cast<float*>(out.data);
509 EXPECT_NEAR(std::tanh(1e-5f) + std::tanh(2e-5f), data[0], 1e-10);
510 EXPECT_NEAR(std::tanh(2e-5f), data[1], 1e-10);
514 class Layer_RNN_Test : public ::testing::Test
517 int nX, nH, nO, nT, nS;
518 Mat Whh, Wxh, bh, Who, bo;
521 std::vector<Mat> inputs, outputs;
531 Whh = Mat::ones(nH, nH, CV_32F);
532 Wxh = Mat::ones(nH, nX, CV_32F);
533 bh = Mat::ones(nH, 1, CV_32F);
534 Who = Mat::ones(nO, nH, CV_32F);
535 bo = Mat::ones(nO, 1, CV_32F);
537 layer = RNNLayer::create(LayerParams());
538 layer->setProduceHiddenOutput(true);
539 layer->setWeights(Wxh, bh, Whh, Who, bo);
543 TEST_F(Layer_RNN_Test, get_set_test)
545 int sz[] = { nT, nS, 1, nX };
546 Mat inp(4, sz, CV_32F);
548 inputs.push_back(inp);
549 runLayer(layer, inputs, outputs);
551 EXPECT_EQ(outputs.size(), 2u);
552 EXPECT_EQ(shape(outputs[0]), shape(nT, nS, nO));
553 EXPECT_EQ(shape(outputs[1]), shape(nT, nS, nH));
556 TEST(Layer_Test_ROIPooling, Accuracy)
558 Net net = readNetFromCaffe(_tf("net_roi_pooling.prototxt"));
560 Mat inp = blobFromNPY(_tf("net_roi_pooling.input.npy"));
561 Mat rois = blobFromNPY(_tf("net_roi_pooling.rois.npy"));
562 Mat ref = blobFromNPY(_tf("net_roi_pooling.npy"));
564 net.setInput(inp, "input");
565 net.setInput(rois, "rois");
566 net.setPreferableBackend(DNN_BACKEND_OPENCV);
568 Mat out = net.forward();
570 normAssert(out, ref);
573 TEST_P(Test_Caffe_layers, FasterRCNN_Proposal)
575 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
576 applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
577 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
578 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
580 Net net = readNetFromCaffe(_tf("net_faster_rcnn_proposal.prototxt"));
582 Mat scores = blobFromNPY(_tf("net_faster_rcnn_proposal.scores.npy"));
583 Mat deltas = blobFromNPY(_tf("net_faster_rcnn_proposal.deltas.npy"));
584 Mat imInfo = (Mat_<float>(1, 3) << 600, 800, 1.6f);
586 net.setInput(scores, "rpn_cls_prob_reshape");
587 net.setInput(deltas, "rpn_bbox_pred");
588 net.setInput(imInfo, "im_info");
590 std::vector<Mat> outs;
591 net.setPreferableBackend(backend);
592 net.setPreferableTarget(target);
593 net.forward(outs, "output");
595 for (int i = 0; i < 2; ++i)
597 Mat ref = blobFromNPY(_tf(i == 0 ? "net_faster_rcnn_proposal.out_rois.npy" :
598 "net_faster_rcnn_proposal.out_scores.npy"));
599 const int numDets = ref.size[0];
600 EXPECT_LE(numDets, outs[i].size[0]);
601 normAssert(outs[i].rowRange(0, numDets), ref);
603 if (numDets < outs[i].size[0])
605 EXPECT_EQ(countNonZero(outs[i].rowRange(numDets, outs[i].size[0])), 0);
610 typedef testing::TestWithParam<tuple<Vec4i, Vec2i, bool> > Scale_untrainable;
611 TEST_P(Scale_untrainable, Accuracy)
613 Vec4i inpShapeVec = get<0>(GetParam());
614 int axis = get<1>(GetParam())[0];
615 int weightsDims = get<1>(GetParam())[1];
616 bool testFusion = get<2>(GetParam());
617 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
619 // Create a network with two inputs. Scale layer multiplies a first input to
620 // a second one. See http://caffe.berkeleyvision.org/tutorial/layers/scale.html
622 // Check that this version of Scale layer won't be fused with Convolution layer.
626 lp.set("kernel_size", 1);
627 lp.set("num_output", 3);
629 lp.set("bias_term", false);
630 lp.type = "Convolution";
631 lp.name = "testConv";
633 std::vector<int> weightsShape(4);
634 weightsShape[0] = 3; // #outChannels
635 weightsShape[1] = 1; // #inpChannels / group
636 weightsShape[2] = 1; // height
637 weightsShape[3] = 1; // width
638 Mat weights(weightsShape, CV_32F);
640 lp.blobs.push_back(weights);
641 net.addLayerToPrev(lp.name, lp.type, lp);
645 lp.name = "testLayer";
646 lp.set("axis", axis);
647 int id = net.addLayerToPrev(lp.name, lp.type, lp);
648 net.connect(0, 1, id, 1);
650 Mat input(4, inpShape, CV_32F);
651 Mat weights(weightsDims, &inpShape[axis], CV_32F);
653 randu(weights, -1, 1);
655 std::vector<String> inpNames(2);
656 inpNames[0] = "scale_input";
657 inpNames[1] = "scale_weights";
658 net.setInputsNames(inpNames);
659 net.setInput(input, inpNames[0]);
660 net.setInput(weights, inpNames[1]);
661 net.setPreferableBackend(DNN_BACKEND_OPENCV);
662 Mat out = net.forward();
664 Mat ref(input.dims, input.size, CV_32F);
665 float* inpData = (float*)input.data;
666 float* refData = (float*)ref.data;
667 float* weightsData = (float*)weights.data;
669 for (int i = axis + weightsDims; i < 4; ++i)
670 spatialSize *= inpShape[i];
671 for (int i = 0; i < ref.total(); ++i)
673 float w = weightsData[(i / spatialSize) % weights.total()];
674 refData[i] = inpData[i] * w;
676 normAssert(out, ref);
679 INSTANTIATE_TEST_CASE_P(Layer_Test, Scale_untrainable, Combine(
680 /*input size*/ Values(Vec4i(2, 3, 4, 5)),
681 /*axis, #dims*/ Values(Vec2i(0, 1), Vec2i(0, 2), Vec2i(0, 3), Vec2i(0, 4),
682 Vec2i(1, 1), Vec2i(1, 2), Vec2i(1, 3),
683 Vec2i(2, 1), Vec2i(2, 2),
685 /*conv fusion*/ testing::Bool()
688 typedef testing::TestWithParam<tuple<Vec4i, Vec4i, int, int, int> > Crop;
689 TEST_P(Crop, Accuracy)
691 Vec4i inpShapeVec = get<0>(GetParam());
692 Vec4i sizShapeVec = get<1>(GetParam());
693 int axis = get<2>(GetParam());
694 int numOffsets = get<3>(GetParam());
695 int offsetVal = get<4>(GetParam());
696 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
697 const int sizShape[] = {sizShapeVec[0], sizShapeVec[1], sizShapeVec[2], sizShapeVec[3]};
699 // Create a network with two inputs. Crop layer crops a first input to
700 // the size of a second one.
701 // See http://caffe.berkeleyvision.org/tutorial/layers/crop.html
705 lp.name = "testCrop";
707 lp.set("axis", axis);
710 std::vector<int> offsets(numOffsets, offsetVal);
711 lp.set("offset", DictValue::arrayInt<int*>(&offsets[0], offsets.size()));
715 int id = net.addLayerToPrev(lp.name, lp.type, lp);
716 net.connect(0, 1, id, 1);
718 Mat inpImage(4, inpShape, CV_32F);
719 Mat sizImage(4, sizShape, CV_32F);
720 randu(inpImage, -1, 1);
721 randu(sizImage, -1, 1);
723 std::vector<String> inpNames(2);
724 inpNames[0] = "cropImage";
725 inpNames[1] = "sizImage";
726 net.setInputsNames(inpNames);
727 net.setInput(inpImage, inpNames[0]);
728 net.setInput(sizImage, inpNames[1]);
729 net.setPreferableBackend(DNN_BACKEND_OPENCV);
731 // There are a few conditions that represent invalid input to the crop
732 // layer, so in those cases we want to verify an exception is thrown.
734 bool shouldThrowException = false;
735 if (numOffsets > 1 && numOffsets != 4 - axis)
736 shouldThrowException = true;
738 for (int i = axis; i < 4; i++)
739 if (sizShape[i] + offsetVal > inpShape[i])
740 shouldThrowException = true;
743 if (shouldThrowException)
745 ASSERT_ANY_THROW(out = net.forward());
751 // Finally, compare the cropped output blob from the DNN layer (out)
752 // to a reference blob (ref) that we compute here.
754 std::vector<Range> crop_range;
755 crop_range.resize(4, Range::all());
756 for (int i = axis; i < 4; i++)
757 crop_range[i] = Range(offsetVal, sizShape[i] + offsetVal);
759 Mat ref(sizImage.dims, sizImage.size, CV_32F);
760 inpImage(&crop_range[0]).copyTo(ref);
761 normAssert(out, ref);
764 INSTANTIATE_TEST_CASE_P(Layer_Test, Crop, Combine(
765 /*input blob shape*/ Values(Vec4i(1, 3, 20, 30)),
766 /*cropsize blob shape*/ Values(Vec4i(1, 3, 10, 12)),
767 /*start axis*/ Values(0, 1, 2),
768 /*number of offsets*/ Values(0, 1, 2, 4),
769 /*offset value*/ Values(3, 4)
772 // Check that by default average pooling layer should not count zero padded values
773 // into the normalization area.
774 TEST_P(Test_Caffe_layers, Average_pooling_kernel_area)
777 lp.name = "testAvePool";
779 lp.set("kernel_size", 2);
781 lp.set("pool", "AVE");
784 net.addLayerToPrev(lp.name, lp.type, lp);
789 Mat inp = (Mat_<float>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
790 Mat ref = (Mat_<float>(2, 2) << (1 + 2 + 4 + 5) / 4.f, (3 + 6) / 2.f, (7 + 8) / 2.f, 9);
791 Mat tmp = blobFromImage(inp);
792 net.setInput(blobFromImage(inp));
793 net.setPreferableBackend(backend);
794 net.setPreferableTarget(target);
795 Mat out = net.forward();
796 normAssert(out, blobFromImage(ref));
799 TEST_P(Test_Caffe_layers, PriorBox_repeated)
801 Net net = readNet(_tf("prior_box.prototxt"));
802 int inp_size[] = {1, 3, 10, 10};
803 int shape_size[] = {1, 2, 3, 4};
804 Mat inp(4, inp_size, CV_32F);
805 randu(inp, -1.0f, 1.0f);
806 Mat shape(4, shape_size, CV_32F);
807 randu(shape, -1.0f, 1.0f);
808 net.setInput(inp, "data");
809 net.setInput(shape, "shape");
810 Mat out = net.forward();
811 Mat ref = blobFromNPY(_tf("priorbox_output.npy"));
812 normAssert(out, ref, "");
815 // Test PriorBoxLayer in case of no aspect ratios (just squared proposals).
816 TEST_P(Test_Caffe_layers, PriorBox_squares)
818 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
819 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
821 lp.name = "testPriorBox";
822 lp.type = "PriorBox";
823 lp.set("min_size", 2);
824 lp.set("flip", true);
825 lp.set("clip", true);
826 float variance[] = {0.1f, 0.1f, 0.2f, 0.2f};
827 float aspectRatios[] = {1.0f}; // That should be ignored.
828 lp.set("variance", DictValue::arrayReal<float*>(&variance[0], 4));
829 lp.set("aspect_ratio", DictValue::arrayReal<float*>(&aspectRatios[0], 1));
832 int id = net.addLayerToPrev(lp.name, lp.type, lp);
833 net.connect(0, 0, id, 1); // The second input is an input image. Shapes are used for boxes normalization.
834 Mat inp(1, 2, CV_32F);
836 net.setInput(blobFromImage(inp));
837 net.setPreferableBackend(backend);
838 net.setPreferableTarget(target);
839 Mat out = net.forward();
841 Mat ref = (Mat_<float>(4, 4) << 0.0, 0.0, 0.75, 1.0,
843 0.1f, 0.1f, 0.2f, 0.2f,
844 0.1f, 0.1f, 0.2f, 0.2f);
845 double l1 = (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) ? 2e-5 : 1e-5;
846 normAssert(out.reshape(1, 4), ref, "", l1);
849 typedef TestWithParam<tuple<int, int> > Layer_Test_DWconv_Prelu;
850 TEST_P(Layer_Test_DWconv_Prelu, Accuracy)
853 // input img size 3x16x16 value all 1
856 // dw_conv weight[0]=-1 weight[1]=-2 weight[2]=-3 bias={1,2,3}
859 // prelu weight={1,2,3}
862 // output out size 3x14x14 if right: out[0]=-8 out[0]=-32 out[0]=-72
863 // but current opencv output: out[0]=-24 out[0]=-48 out[0]=-72
865 const int num_input = get<0>(GetParam()); //inpChannels
866 const int group = 3; //outChannels=group when group>1
867 const int num_output = get<1>(GetParam());
868 const int kernel_depth = num_input/group;
869 CV_Assert_N(num_output >= group, num_output % group == 0, num_input % group == 0);
875 lp.type = "Convolution";
876 lp.set("kernel_size", 3);
877 lp.set("num_output", num_output);
879 lp.set("group", group);
881 lp.set("engine", "CAFFE");
882 lp.set("bias_term", "true");
884 std::vector<int> weightsShape(4);
885 weightsShape[0] = num_output; // #outChannels
886 weightsShape[1] = kernel_depth; // #inpChannels / group
887 weightsShape[2] = 3; // height
888 weightsShape[3] = 3; // width
889 Mat weights(weightsShape, CV_32F, Scalar(1));
892 for (int i = 0; i < weightsShape[0]; ++i)
894 for (int j = 0; j < weightsShape[1]; ++j)
896 for (int k = 0; k < weightsShape[2]; ++k)
898 for (int l = 0; l < weightsShape[3]; ++l)
900 weights.ptr<float>(i, j, k)[l]=-1*(i+1);
905 lp.blobs.push_back(weights);
908 Mat bias(1, num_output, CV_32F, Scalar(1));
909 for (int i = 0; i < 1; ++i)
911 for (int j = 0; j < num_output; ++j)
913 bias.ptr<float>(i)[j]=j+1;
916 lp.blobs.push_back(bias);
917 net.addLayerToPrev(lp.name, lp.type, lp);
921 lpr.name = "dw_relu";
923 Mat weightsp(1, num_output, CV_32F, Scalar(1));
926 for (int i = 0; i < 1; ++i)
928 for (int j = 0; j < num_output; ++j)
930 weightsp.ptr<float>(i)[j]=j+1;
934 lpr.blobs.push_back(weightsp);
935 net.addLayerToPrev(lpr.name, lpr.type, lpr);
937 int shape[] = {1, num_input, 16, 16};
938 Mat in_blob(4, &shape[0], CV_32FC1, Scalar(1));
940 net.setPreferableBackend(DNN_BACKEND_OPENCV);
941 net.setInput(in_blob);
942 Mat out = net.forward();
945 std::vector<int> outShape(4);
947 outShape[1] = num_output; // outChannels
948 outShape[2] = 14; // height
949 outShape[3] = 14; // width
950 Mat target(outShape, CV_32F, Scalar(1));
951 for (int i = 0; i < outShape[0]; ++i)
953 for (int j = 0; j < outShape[1]; ++j)
955 for (int k = 0; k < outShape[2]; ++k)
957 for (int l = 0; l < outShape[3]; ++l)
959 target.ptr<float>(i, j, k)[l]=(-9*kernel_depth*(j+1)+j+1)*(j+1);
965 normAssert(out, target);
967 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_DWconv_Prelu, Combine(Values(3, 6), Values(3, 6)));
969 #ifdef HAVE_INF_ENGINE
970 // Using Intel's Model Optimizer generate .xml and .bin files:
971 // ./ModelOptimizer -w /path/to/caffemodel -d /path/to/prototxt \
972 // -p FP32 -i -b ${batch_size} -o /path/to/output/folder
973 typedef testing::TestWithParam<Target> Layer_Test_Convolution_DLDT;
974 TEST_P(Layer_Test_Convolution_DLDT, Accuracy)
976 Target targetId = GetParam();
978 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
979 Net netDefault = readNet(_tf("layer_convolution.caffemodel"), _tf("layer_convolution.prototxt"));
980 Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
982 Mat inp = blobFromNPY(_tf("blob.npy"));
984 netDefault.setInput(inp);
985 netDefault.setPreferableBackend(DNN_BACKEND_OPENCV);
986 Mat outDefault = netDefault.forward();
989 net.setPreferableTarget(targetId);
991 Mat out = net.forward();
993 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
994 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
995 normAssert(outDefault, out, "", l1, lInf);
997 std::vector<int> outLayers = net.getUnconnectedOutLayers();
998 ASSERT_EQ(net.getLayer(outLayers[0])->name, "output");
999 ASSERT_EQ(net.getLayer(outLayers[0])->type, "Convolution");
1002 TEST_P(Layer_Test_Convolution_DLDT, setInput_uint8)
1004 Target targetId = GetParam();
1005 Mat inp = blobFromNPY(_tf("blob.npy"));
1007 Mat inputs[] = {Mat(inp.dims, inp.size, CV_8U), Mat()};
1008 randu(inputs[0], 0, 255);
1009 inputs[0].convertTo(inputs[1], CV_32F);
1011 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1014 for (int i = 0; i < 2; ++i)
1016 Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
1017 net.setPreferableTarget(targetId);
1018 net.setInput(inputs[i]);
1019 outs[i] = net.forward();
1020 ASSERT_EQ(outs[i].type(), CV_32F);
1022 if (targetId != DNN_TARGET_MYRIAD)
1023 normAssert(outs[0], outs[1]);
1026 TEST_P(Layer_Test_Convolution_DLDT, multithreading)
1028 Target targetId = GetParam();
1029 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1030 std::string xmlPath = _tf("layer_convolution" + suffix + ".xml");
1031 std::string binPath = _tf("layer_convolution" + suffix + ".bin");
1032 Net firstNet = readNet(xmlPath, binPath);
1033 Net secondNet = readNet(xmlPath, binPath);
1034 Mat inp = blobFromNPY(_tf("blob.npy"));
1036 firstNet.setInput(inp);
1037 secondNet.setInput(inp);
1038 firstNet.setPreferableTarget(targetId);
1039 secondNet.setPreferableTarget(targetId);
1042 std::thread t1([&]{out1 = firstNet.forward();});
1043 std::thread t2([&]{out2 = secondNet.forward();});
1048 Mat ref = blobFromNPY(_tf("layer_convolution.npy"));
1049 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
1050 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
1051 normAssert(out1, ref, "first thread", l1, lInf);
1052 normAssert(out2, ref, "second thread", l1, lInf);
1055 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_Convolution_DLDT,
1056 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)));
1058 // 1. Create a .prototxt file with the following network:
1060 // type: "Input" name: "data" top: "data"
1061 // input_param { shape { dim: 1 dim: 2 dim: 3 } }
1064 // type: "Input" name: "second_input" top: "second_input"
1065 // input_param { shape { dim: 1 dim: 2 dim: 3 } }
1068 // type: "Eltwise" name: "output" top: "output"
1069 // bottom: "data" bottom: "second_input"
1070 // eltwise_param { operation: SUM }
1073 // 2. Create a .caffemodel file using Caffe:
1076 // net = caffe.Net('/path/to/prototxt', caffe.TEST)
1077 // net.save('/path/to/caffemodel')
1079 // 3. Convert using ModelOptimizer.
1080 typedef testing::TestWithParam<tuple<int, int, Target, std::vector<int> > > Test_DLDT_two_inputs_3dim;
1081 TEST_P(Test_DLDT_two_inputs_3dim, as_IR)
1083 int firstInpType = get<0>(GetParam());
1084 int secondInpType = get<1>(GetParam());
1085 Target targetId = get<2>(GetParam());
1087 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1088 Net net = readNet(_tf("net_two_inputs" + suffix + ".xml"), _tf("net_two_inputs.bin"));
1089 std::vector<int> inpSize = get<3>(GetParam());
1090 Mat firstInp(3, inpSize.data(), firstInpType);
1091 Mat secondInp(3, inpSize.data(), secondInpType);
1092 randu(firstInp, 0, 255);
1093 randu(secondInp, 0, 255);
1095 net.setInput(firstInp, "data");
1096 net.setInput(secondInp, "second_input");
1097 net.setPreferableTarget(targetId);
1099 double l1 = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1100 (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.06 : 0.0;
1101 double lInf = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1102 (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.23 : 0.0;
1104 Mat out = net.forward();
1107 cv::add(firstInp, secondInp, ref, Mat(), CV_32F);
1108 normAssert(out, ref, "", l1, lInf);
1111 std::vector< std::vector<int> > list_sizes{ {1, 2, 3}, {3, 2, 1}, {5, 5, 5}, {13, 7, 11} };
1113 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs_3dim, Combine(
1114 Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1115 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)),
1116 testing::ValuesIn(list_sizes)
1119 typedef testing::TestWithParam<tuple<int, int, Target> > Test_DLDT_two_inputs;
1120 TEST_P(Test_DLDT_two_inputs, as_backend)
1122 static const float kScale = 0.5f;
1123 static const float kScaleInv = 1.0f / kScale;
1125 Target targetId = get<2>(GetParam());
1129 lp.type = "Eltwise";
1130 lp.name = "testLayer";
1131 lp.set("operation", "sum");
1132 int eltwiseId = net.addLayerToPrev(lp.name, lp.type, lp); // connect to a first input
1133 net.connect(0, 1, eltwiseId, 1); // connect to a second input
1135 int inpSize[] = {1, 2, 3, 4};
1136 Mat firstInp(4, &inpSize[0], get<0>(GetParam()));
1137 Mat secondInp(4, &inpSize[0], get<1>(GetParam()));
1138 randu(firstInp, 0, 255);
1139 randu(secondInp, 0, 255);
1141 net.setInputsNames({"data", "second_input"});
1142 net.setInput(firstInp, "data", kScale);
1143 net.setInput(secondInp, "second_input", kScaleInv);
1144 net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1145 net.setPreferableTarget(targetId);
1146 Mat out = net.forward();
1149 addWeighted(firstInp, kScale, secondInp, kScaleInv, 0, ref, CV_32F);
1150 // Output values are in range [0, 637.5].
1151 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.06 : 1e-6;
1152 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.3 : 1e-5;
1153 normAssert(out, ref, "", l1, lInf);
1156 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs, Combine(
1157 Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1158 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE))
1161 class UnsupportedLayer : public Layer
1164 UnsupportedLayer(const LayerParams ¶ms) : Layer(params) {}
1166 static Ptr<Layer> create(const LayerParams& params)
1168 return Ptr<Layer>(new UnsupportedLayer(params));
1171 virtual bool supportBackend(int backendId) CV_OVERRIDE
1173 return backendId == DNN_BACKEND_OPENCV;
1176 virtual void forward(cv::InputArrayOfArrays inputs, cv::OutputArrayOfArrays outputs, cv::OutputArrayOfArrays internals) CV_OVERRIDE {}
1179 TEST(Test_DLDT, fused_output)
1181 static const int kNumChannels = 3;
1182 CV_DNN_REGISTER_LAYER_CLASS(Unsupported, UnsupportedLayer);
1186 lp.set("kernel_size", 1);
1187 lp.set("num_output", 3);
1188 lp.set("bias_term", false);
1189 lp.type = "Convolution";
1190 lp.name = "testConv";
1191 lp.blobs.push_back(Mat({kNumChannels, 1, 1, 1}, CV_32F, Scalar(1)));
1192 net.addLayerToPrev(lp.name, lp.type, lp);
1196 lp.set("bias_term", false);
1198 lp.name = "testScale";
1199 lp.blobs.push_back(Mat({kNumChannels}, CV_32F, Scalar(1)));
1200 net.addLayerToPrev(lp.name, lp.type, lp);
1204 net.addLayerToPrev("unsupported_layer", "Unsupported", lp);
1206 net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1207 net.setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1208 ASSERT_NO_THROW(net.forward());
1209 LayerFactory::unregisterLayer("Unsupported");
1212 TEST(Test_DLDT, multiple_networks)
1215 for (int i = 0; i < 2; ++i)
1217 nets[i].setInputsNames(std::vector<String>(1, format("input_%d", i)));
1220 lp.set("kernel_size", 1);
1221 lp.set("num_output", 1);
1222 lp.set("bias_term", false);
1223 lp.type = "Convolution";
1224 lp.name = format("testConv_%d", i);
1225 lp.blobs.push_back(Mat({1, 1, 1, 1}, CV_32F, Scalar(1 + i)));
1226 nets[i].addLayerToPrev(lp.name, lp.type, lp);
1227 nets[i].setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1228 nets[i].setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1230 Mat out_1 = nets[0].forward();
1231 Mat out_2 = nets[1].forward();
1232 // After the second model is initialized we try to receive an output from the first network again.
1233 out_1 = nets[0].forward();
1234 normAssert(2 * out_1, out_2);
1236 #endif // HAVE_INF_ENGINE
1238 // Test a custom layer.
1239 class CustomInterpLayer CV_FINAL : public Layer
1242 CustomInterpLayer(const LayerParams ¶ms) : Layer(params)
1244 zoomFactor = params.get<int>("zoom_factor", 0);
1245 outWidth = params.get<int>("width", 0);
1246 outHeight = params.get<int>("height", 0);
1249 static Ptr<Layer> create(LayerParams& params)
1251 return Ptr<Layer>(new CustomInterpLayer(params));
1254 virtual bool getMemoryShapes(const std::vector<std::vector<int> > &inputs,
1255 const int requiredOutputs,
1256 std::vector<std::vector<int> > &outputs,
1257 std::vector<std::vector<int> > &internals) const CV_OVERRIDE
1259 const int batchSize = inputs[0][0];
1260 const int numChannels = inputs[0][1];
1261 const int inpHeight = inputs[0][2];
1262 const int inpWidth = inputs[0][3];
1264 std::vector<int> outShape(4);
1265 outShape[0] = batchSize;
1266 outShape[1] = numChannels;
1267 outShape[2] = outHeight != 0 ? outHeight : (inpHeight + (inpHeight - 1) * (zoomFactor - 1));
1268 outShape[3] = outWidth != 0 ? outWidth : (inpWidth + (inpWidth - 1) * (zoomFactor - 1));
1269 outputs.assign(1, outShape);
1273 virtual void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
1275 std::vector<Mat> outputs;
1276 outputs_arr.getMatVector(outputs);
1278 if (!outWidth && !outHeight)
1280 outHeight = outputs[0].size[2];
1281 outWidth = outputs[0].size[3];
1285 // Implementation of this custom layer is based on https://github.com/cdmh/deeplab-public/blob/master/src/caffe/layers/interp_layer.cpp
1286 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1288 CV_TRACE_FUNCTION();
1289 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1291 if (inputs_arr.depth() == CV_16S)
1293 forward_fallback(inputs_arr, outputs_arr, internals_arr);
1297 std::vector<Mat> inputs, outputs;
1298 inputs_arr.getMatVector(inputs);
1299 outputs_arr.getMatVector(outputs);
1301 Mat& inp = inputs[0];
1302 Mat& out = outputs[0];
1303 const float* inpData = (float*)inp.data;
1304 float* outData = (float*)out.data;
1306 const int batchSize = inp.size[0];
1307 const int numChannels = inp.size[1];
1308 const int inpHeight = inp.size[2];
1309 const int inpWidth = inp.size[3];
1311 const float rheight = (outHeight > 1) ? static_cast<float>(inpHeight - 1) / (outHeight - 1) : 0.f;
1312 const float rwidth = (outWidth > 1) ? static_cast<float>(inpWidth - 1) / (outWidth - 1) : 0.f;
1313 for (int h2 = 0; h2 < outHeight; ++h2)
1315 const float h1r = rheight * h2;
1317 const int h1p = (h1 < inpHeight - 1) ? 1 : 0;
1318 const float h1lambda = h1r - h1;
1319 const float h0lambda = 1.f - h1lambda;
1320 for (int w2 = 0; w2 < outWidth; ++w2)
1322 const float w1r = rwidth * w2;
1324 const int w1p = (w1 < inpWidth - 1) ? 1 : 0;
1325 const float w1lambda = w1r - w1;
1326 const float w0lambda = 1.f - w1lambda;
1327 const float* pos1 = inpData + h1 * inpWidth + w1;
1328 float* pos2 = outData + h2 * outWidth + w2;
1329 for (int c = 0; c < batchSize * numChannels; ++c)
1332 h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[w1p]) +
1333 h1lambda * (w0lambda * pos1[h1p * inpWidth] + w1lambda * pos1[h1p * inpWidth + w1p]);
1334 pos1 += inpWidth * inpHeight;
1335 pos2 += outWidth * outHeight;
1342 int outWidth, outHeight, zoomFactor;
1345 #ifndef OPENCV_DNN_EXTERNAL_PROTOBUF
1346 TEST_P(Test_Caffe_layers, Interp)
1348 TEST_P(Test_Caffe_layers, DISABLED_Interp) // requires patched protobuf (available in OpenCV source tree only)
1351 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
1352 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
1354 // Test a custom layer.
1355 CV_DNN_REGISTER_LAYER_CLASS(Interp, CustomInterpLayer);
1358 testLayerUsingCaffeModels("layer_interp", false, false);
1362 LayerFactory::unregisterLayer("Interp");
1365 LayerFactory::unregisterLayer("Interp");
1367 // Test an implemented layer.
1368 testLayerUsingCaffeModels("layer_interp", false, false);
1371 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_Caffe_layers, dnnBackendsAndTargets());
1373 TEST(Layer_Test_PoolingIndices, Accuracy)
1378 lp.set("pool", "max");
1379 lp.set("kernel_w", 2);
1380 lp.set("kernel_h", 2);
1381 lp.set("stride_w", 2);
1382 lp.set("stride_h", 2);
1385 lp.name = "testLayer.name"; // This test also checks that OpenCV lets use names with dots.
1386 lp.type = "Pooling";
1387 net.addLayerToPrev(lp.name, lp.type, lp);
1389 Mat inp(10, 10, CV_8U);
1392 Mat maxValues(5, 5, CV_32F, Scalar(-1)), indices(5, 5, CV_32F, Scalar(-1));
1393 for (int y = 0; y < 10; ++y)
1396 for (int x = 0; x < 10; ++x)
1399 uint8_t val = inp.at<uint8_t>(y, x);
1400 if ((float)inp.at<uint8_t>(y, x) > maxValues.at<float>(dstY, dstX))
1402 maxValues.at<float>(dstY, dstX) = val;
1403 indices.at<float>(dstY, dstX) = y * 10 + x;
1407 net.setPreferableBackend(DNN_BACKEND_OPENCV);
1408 net.setInput(blobFromImage(inp));
1410 std::vector<Mat> outputs;
1411 net.forward(outputs, lp.name);
1412 normAssert(maxValues, outputs[0].reshape(1, 5));
1413 normAssert(indices, outputs[1].reshape(1, 5));
1416 typedef testing::TestWithParam<tuple<Vec4i, int, tuple<Backend, Target> > > Layer_Test_ShuffleChannel;
1417 TEST_P(Layer_Test_ShuffleChannel, Accuracy)
1419 Vec4i inpShapeVec = get<0>(GetParam());
1420 int group = get<1>(GetParam());
1421 ASSERT_EQ(inpShapeVec[1] % group, 0);
1422 const int groupSize = inpShapeVec[1] / group;
1423 int backendId = get<0>(get<2>(GetParam()));
1424 int targetId = get<1>(get<2>(GetParam()));
1428 lp.set("group", group);
1429 lp.type = "ShuffleChannel";
1430 lp.name = "testLayer";
1431 net.addLayerToPrev(lp.name, lp.type, lp);
1433 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
1434 Mat inp(4, inpShape, CV_32F);
1438 net.setPreferableBackend(backendId);
1439 net.setPreferableTarget(targetId);
1440 Mat out = net.forward();
1442 double l1 = (targetId == DNN_TARGET_OPENCL_FP16) ? 5e-2 : 1e-5;
1443 double lInf = (targetId == DNN_TARGET_OPENCL_FP16) ? 7e-2 : 1e-4;
1444 for (int n = 0; n < inpShapeVec[0]; ++n)
1446 for (int c = 0; c < inpShapeVec[1]; ++c)
1448 Mat outChannel = getPlane(out, n, c);
1449 Mat inpChannel = getPlane(inp, n, groupSize * (c % group) + c / group);
1450 normAssert(outChannel, inpChannel, "", l1, lInf);
1454 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_ShuffleChannel, Combine(
1455 /*input shape*/ Values(Vec4i(1, 6, 5, 7), Vec4i(3, 12, 1, 4)),
1456 /*group*/ Values(1, 2, 3, 6), dnnBackendsAndTargets(/*with IE*/ false)
1459 // Check if relu is not fused to convolution if we requested it's output
1460 TEST(Layer_Test_Convolution, relu_fusion)
1465 lp.set("kernel_size", 1);
1466 lp.set("num_output", 1);
1467 lp.set("bias_term", false);
1468 lp.type = "Convolution";
1469 lp.name = "testConv";
1471 int weightsShape[] = {1, 1, 1, 1};
1472 Mat weights(4, &weightsShape[0], CV_32F, Scalar(1));
1473 lp.blobs.push_back(weights);
1474 net.addLayerToPrev(lp.name, lp.type, lp);
1479 lp.name = "testReLU";
1480 net.addLayerToPrev(lp.name, lp.type, lp);
1482 int sz[] = {1, 1, 2, 3};
1483 Mat input(4, &sz[0], CV_32F);
1484 randu(input, -1.0, -0.1);
1485 net.setInput(input);
1486 net.setPreferableBackend(DNN_BACKEND_OPENCV);
1487 Mat output = net.forward("testConv");
1488 normAssert(input, output);