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 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_CPU)
145 throw SkipTestException("Test is disabled for DLIE/CPU");
146 testLayerUsingCaffeModels("layer_deconvolution", true, false);
149 TEST_P(Test_Caffe_layers, InnerProduct)
151 if (backend == DNN_BACKEND_INFERENCE_ENGINE ||
152 (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16))
153 throw SkipTestException("");
154 testLayerUsingCaffeModels("layer_inner_product", true);
157 TEST_P(Test_Caffe_layers, Pooling_max)
159 testLayerUsingCaffeModels("layer_pooling_max");
162 TEST_P(Test_Caffe_layers, Pooling_ave)
164 testLayerUsingCaffeModels("layer_pooling_ave");
167 TEST_P(Test_Caffe_layers, MVN)
169 testLayerUsingCaffeModels("layer_mvn");
172 void testReshape(const MatShape& inputShape, const MatShape& targetShape,
173 int axis = 0, int num_axes = -1,
174 MatShape mask = MatShape())
177 params.set("axis", axis);
178 params.set("num_axes", num_axes);
181 params.set("dim", DictValue::arrayInt<int*>(&mask[0], mask.size()));
184 Mat inp(inputShape.size(), &inputShape[0], CV_32F);
185 std::vector<Mat> inpVec(1, inp);
186 std::vector<Mat> outVec, intVec;
188 Ptr<Layer> rl = LayerFactory::createLayerInstance("Reshape", params);
189 runLayer(rl, inpVec, outVec);
191 Mat& out = outVec[0];
192 MatShape shape(out.size.p, out.size.p + out.dims);
193 EXPECT_EQ(shape, targetShape);
196 TEST(Layer_Test_Reshape, Accuracy)
199 int inp[] = {4, 3, 1, 2};
200 int out[] = {4, 3, 2};
201 testReshape(MatShape(inp, inp + 4), MatShape(out, out + 3), 2, 1);
204 int inp[] = {1, 128, 4, 4};
205 int out[] = {1, 2048};
206 int mask[] = {-1, 2048};
207 testReshape(MatShape(inp, inp + 4), MatShape(out, out + 2), 0, -1,
208 MatShape(mask, mask + 2));
211 int inp[] = {1, 2, 3};
212 int out[] = {3, 1, 2};
213 int mask[] = {3, 1, 2};
214 testReshape(MatShape(inp, inp + 3), MatShape(out, out + 3), 0, -1,
215 MatShape(mask, mask + 3));
219 TEST_P(Test_Caffe_layers, BatchNorm)
221 testLayerUsingCaffeModels("layer_batch_norm", true);
222 testLayerUsingCaffeModels("layer_batch_norm_local_stats", true, false);
225 TEST_P(Test_Caffe_layers, ReLU)
227 testLayerUsingCaffeModels("layer_relu");
230 TEST_P(Test_Caffe_layers, Dropout)
232 testLayerUsingCaffeModels("layer_dropout");
235 TEST_P(Test_Caffe_layers, Concat)
237 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_GE(2019010000)
238 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
239 throw SkipTestException("Test is disabled for Myriad targets");
241 testLayerUsingCaffeModels("layer_concat");
242 testLayerUsingCaffeModels("layer_concat_optim", true, false);
243 testLayerUsingCaffeModels("layer_concat_shared_input", true, false);
246 TEST_P(Test_Caffe_layers, Fused_Concat)
248 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_GE(2019010000)
249 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
250 throw SkipTestException("Test is disabled for DLIE due negative_slope parameter");
253 #if defined(INF_ENGINE_RELEASE)
254 if (backend == DNN_BACKEND_INFERENCE_ENGINE
255 && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16)
257 throw SkipTestException("Test is disabled for DLIE");
275 lp.name = "someLayer";
276 interLayer = net.addLayerToPrev(lp.name, lp.type, lp);
282 lp.name = "testConcat";
283 int id = net.addLayer(lp.name, lp.type, lp);
284 net.connect(interLayer, 0, id, 0);
285 net.connect(interLayer, 0, id, 1);
287 int shape[] = {1, 2, 3, 4};
288 Mat input(4, shape, CV_32F);
289 randu(input, 0.0f, 1.0f); // [0, 1] to make AbsVal an identity transformation.
292 net.setPreferableBackend(backend);
293 net.setPreferableTarget(target);
294 Mat out = net.forward();
296 normAssert(slice(out, Range::all(), Range(0, 2), Range::all(), Range::all()), input, "", default_l1, default_lInf);
297 normAssert(slice(out, Range::all(), Range(2, 4), Range::all(), Range::all()), input, "", default_l1, default_lInf);
300 TEST_P(Test_Caffe_layers, Eltwise)
302 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
303 throw SkipTestException("");
304 testLayerUsingCaffeModels("layer_eltwise");
307 TEST_P(Test_Caffe_layers, PReLU)
309 testLayerUsingCaffeModels("layer_prelu", true);
312 // TODO: fix an unstable test case
313 TEST_P(Test_Caffe_layers, layer_prelu_fc)
315 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
316 throw SkipTestException("");
317 // Reference output values are in range [-0.0001, 10.3906]
318 double l1 = (target == DNN_TARGET_MYRIAD) ? 0.005 : 0.0;
319 double lInf = (target == DNN_TARGET_MYRIAD) ? 0.021 : 0.0;
320 testLayerUsingCaffeModels("layer_prelu_fc", true, false, l1, lInf);
323 //template<typename XMat>
324 //static void test_Layer_Concat()
326 // Matx21f a(1.f, 1.f), b(2.f, 2.f), c(3.f, 3.f);
327 // std::vector<Blob> res(1), src = { Blob(XMat(a)), Blob(XMat(b)), Blob(XMat(c)) };
328 // Blob ref(XMat(Matx23f(1.f, 2.f, 3.f, 1.f, 2.f, 3.f)));
330 // runLayer(ConcatLayer::create(1), src, res);
331 // normAssert(ref, res[0]);
333 //TEST(Layer_Concat, Accuracy)
335 // test_Layer_Concat<Mat>());
337 //OCL_TEST(Layer_Concat, Accuracy)
339 // OCL_ON(test_Layer_Concat<Mat>());
343 TEST_P(Test_Caffe_layers, Reshape_Split_Slice)
345 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
346 throw SkipTestException("");
348 Net net = readNetFromCaffe(_tf("reshape_and_slice_routines.prototxt"));
349 ASSERT_FALSE(net.empty());
351 net.setPreferableBackend(backend);
352 net.setPreferableTarget(target);
354 Mat input(6, 12, CV_32F);
356 rng.fill(input, RNG::UNIFORM, -1, 1);
358 net.setInput(input, "input");
359 Mat output = net.forward("output");
361 normAssert(input, output, "", default_l1, default_lInf);
364 TEST_P(Test_Caffe_layers, Conv_Elu)
366 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE <= 2018050000
367 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
368 throw SkipTestException("");
371 Net net = readNetFromTensorflow(_tf("layer_elu_model.pb"));
372 ASSERT_FALSE(net.empty());
374 Mat inp = blobFromNPY(_tf("layer_elu_in.npy"));
375 Mat ref = blobFromNPY(_tf("layer_elu_out.npy"));
377 net.setInput(inp, "input");
378 net.setPreferableBackend(backend);
379 net.setPreferableTarget(target);
380 Mat out = net.forward();
382 normAssert(ref, out, "", default_l1, default_lInf);
385 class Layer_LSTM_Test : public ::testing::Test
390 Ptr<LSTMLayer> layer;
391 std::vector<Mat> inputs, outputs;
395 void init(const MatShape &inpShape_, const MatShape &outShape_,
396 bool produceCellOutput, bool useTimestampDim)
398 numInp = total(inpShape_);
399 numOut = total(outShape_);
401 Wh = Mat::ones(4 * numOut, numOut, CV_32F);
402 Wx = Mat::ones(4 * numOut, numInp, CV_32F);
403 b = Mat::ones(4 * numOut, 1, CV_32F);
410 lp.set<bool>("produce_cell_output", produceCellOutput);
411 lp.set<bool>("use_timestamp_dim", useTimestampDim);
413 layer = LSTMLayer::create(lp);
414 layer->setOutShape(outShape_);
418 TEST_F(Layer_LSTM_Test, get_set_test)
421 MatShape inpShape = shape(5, 3, 2);
422 MatShape outShape = shape(3, 1, 2);
423 MatShape inpResShape = concat(shape(TN), inpShape);
424 MatShape outResShape = concat(shape(TN), outShape);
426 init(inpShape, outShape, true, false);
427 layer->setOutShape(outShape);
429 Mat C((int)outResShape.size(), &outResShape[0], CV_32F);
434 Mat inp((int)inpResShape.size(), &inpResShape[0], CV_32F);
437 inputs.push_back(inp);
438 runLayer(layer, inputs, outputs);
440 EXPECT_EQ(2u, outputs.size());
442 print(outResShape, "outResShape");
443 print(shape(outputs[0]), "out0");
444 print(shape(outputs[0]), "out1");
446 EXPECT_EQ(outResShape, shape(outputs[0]));
447 EXPECT_EQ(outResShape, shape(outputs[1]));
449 EXPECT_EQ(0, layer->inputNameToIndex("x"));
450 EXPECT_EQ(0, layer->outputNameToIndex("h"));
451 EXPECT_EQ(1, layer->outputNameToIndex("c"));
454 TEST(Layer_LSTM_Test_Accuracy_with_, CaffeRecurrent)
458 lp.blobs[0] = blobFromNPY(_tf("lstm.prototxt.w_2.npy")); // Wh
459 lp.blobs[1] = blobFromNPY(_tf("lstm.prototxt.w_0.npy")); // Wx
460 lp.blobs[2] = blobFromNPY(_tf("lstm.prototxt.w_1.npy")); // bias
461 Ptr<LSTMLayer> layer = LSTMLayer::create(lp);
463 Mat inp = blobFromNPY(_tf("recurrent.input.npy"));
464 std::vector<Mat> inputs(1, inp), outputs;
465 runLayer(layer, inputs, outputs);
467 Mat h_t_reference = blobFromNPY(_tf("lstm.prototxt.h_1.npy"));
468 normAssert(h_t_reference, outputs[0]);
471 TEST(Layer_RNN_Test_Accuracy_with_, CaffeRecurrent)
473 Ptr<RNNLayer> layer = RNNLayer::create(LayerParams());
476 blobFromNPY(_tf("rnn.prototxt.w_0.npy")),
477 blobFromNPY(_tf("rnn.prototxt.w_1.npy")),
478 blobFromNPY(_tf("rnn.prototxt.w_2.npy")),
479 blobFromNPY(_tf("rnn.prototxt.w_3.npy")),
480 blobFromNPY(_tf("rnn.prototxt.w_4.npy")) );
482 std::vector<Mat> output, input(1, blobFromNPY(_tf("recurrent.input.npy")));
483 runLayer(layer, input, output);
485 Mat h_ref = blobFromNPY(_tf("rnn.prototxt.h_1.npy"));
486 normAssert(h_ref, output[0]);
490 class Layer_RNN_Test : public ::testing::Test
493 int nX, nH, nO, nT, nS;
494 Mat Whh, Wxh, bh, Who, bo;
497 std::vector<Mat> inputs, outputs;
507 Whh = Mat::ones(nH, nH, CV_32F);
508 Wxh = Mat::ones(nH, nX, CV_32F);
509 bh = Mat::ones(nH, 1, CV_32F);
510 Who = Mat::ones(nO, nH, CV_32F);
511 bo = Mat::ones(nO, 1, CV_32F);
513 layer = RNNLayer::create(LayerParams());
514 layer->setProduceHiddenOutput(true);
515 layer->setWeights(Wxh, bh, Whh, Who, bo);
519 TEST_F(Layer_RNN_Test, get_set_test)
521 int sz[] = { nT, nS, 1, nX };
522 Mat inp(4, sz, CV_32F);
524 inputs.push_back(inp);
525 runLayer(layer, inputs, outputs);
527 EXPECT_EQ(outputs.size(), 2u);
528 EXPECT_EQ(shape(outputs[0]), shape(nT, nS, nO));
529 EXPECT_EQ(shape(outputs[1]), shape(nT, nS, nH));
532 TEST(Layer_Test_ROIPooling, Accuracy)
534 Net net = readNetFromCaffe(_tf("net_roi_pooling.prototxt"));
536 Mat inp = blobFromNPY(_tf("net_roi_pooling.input.npy"));
537 Mat rois = blobFromNPY(_tf("net_roi_pooling.rois.npy"));
538 Mat ref = blobFromNPY(_tf("net_roi_pooling.npy"));
540 net.setInput(inp, "input");
541 net.setInput(rois, "rois");
542 net.setPreferableBackend(DNN_BACKEND_OPENCV);
544 Mat out = net.forward();
546 normAssert(out, ref);
549 TEST_P(Test_Caffe_layers, FasterRCNN_Proposal)
551 if ((backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16) ||
552 backend == DNN_BACKEND_INFERENCE_ENGINE)
553 throw SkipTestException("");
554 Net net = readNetFromCaffe(_tf("net_faster_rcnn_proposal.prototxt"));
556 Mat scores = blobFromNPY(_tf("net_faster_rcnn_proposal.scores.npy"));
557 Mat deltas = blobFromNPY(_tf("net_faster_rcnn_proposal.deltas.npy"));
558 Mat imInfo = (Mat_<float>(1, 3) << 600, 800, 1.6f);
560 net.setInput(scores, "rpn_cls_prob_reshape");
561 net.setInput(deltas, "rpn_bbox_pred");
562 net.setInput(imInfo, "im_info");
564 std::vector<Mat> outs;
565 net.setPreferableBackend(backend);
566 net.setPreferableTarget(target);
567 net.forward(outs, "output");
569 for (int i = 0; i < 2; ++i)
571 Mat ref = blobFromNPY(_tf(i == 0 ? "net_faster_rcnn_proposal.out_rois.npy" :
572 "net_faster_rcnn_proposal.out_scores.npy"));
573 const int numDets = ref.size[0];
574 EXPECT_LE(numDets, outs[i].size[0]);
575 normAssert(outs[i].rowRange(0, numDets), ref);
577 if (numDets < outs[i].size[0])
579 EXPECT_EQ(countNonZero(outs[i].rowRange(numDets, outs[i].size[0])), 0);
584 typedef testing::TestWithParam<tuple<Vec4i, Vec2i, bool> > Scale_untrainable;
585 TEST_P(Scale_untrainable, Accuracy)
587 Vec4i inpShapeVec = get<0>(GetParam());
588 int axis = get<1>(GetParam())[0];
589 int weightsDims = get<1>(GetParam())[1];
590 bool testFusion = get<2>(GetParam());
591 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
593 // Create a network with two inputs. Scale layer multiplies a first input to
594 // a second one. See http://caffe.berkeleyvision.org/tutorial/layers/scale.html
596 // Check that this version of Scale layer won't be fused with Convolution layer.
600 lp.set("kernel_size", 1);
601 lp.set("num_output", 3);
603 lp.set("bias_term", false);
604 lp.type = "Convolution";
605 lp.name = "testConv";
607 std::vector<int> weightsShape(4);
608 weightsShape[0] = 3; // #outChannels
609 weightsShape[1] = 1; // #inpChannels / group
610 weightsShape[2] = 1; // height
611 weightsShape[3] = 1; // width
612 Mat weights(weightsShape, CV_32F);
614 lp.blobs.push_back(weights);
615 net.addLayerToPrev(lp.name, lp.type, lp);
619 lp.name = "testLayer";
620 lp.set("axis", axis);
621 int id = net.addLayerToPrev(lp.name, lp.type, lp);
622 net.connect(0, 1, id, 1);
624 Mat input(4, inpShape, CV_32F);
625 Mat weights(weightsDims, &inpShape[axis], CV_32F);
627 randu(weights, -1, 1);
629 std::vector<String> inpNames(2);
630 inpNames[0] = "scale_input";
631 inpNames[1] = "scale_weights";
632 net.setInputsNames(inpNames);
633 net.setInput(input, inpNames[0]);
634 net.setInput(weights, inpNames[1]);
635 net.setPreferableBackend(DNN_BACKEND_OPENCV);
636 Mat out = net.forward();
638 Mat ref(input.dims, input.size, CV_32F);
639 float* inpData = (float*)input.data;
640 float* refData = (float*)ref.data;
641 float* weightsData = (float*)weights.data;
643 for (int i = axis + weightsDims; i < 4; ++i)
644 spatialSize *= inpShape[i];
645 for (int i = 0; i < ref.total(); ++i)
647 float w = weightsData[(i / spatialSize) % weights.total()];
648 refData[i] = inpData[i] * w;
650 normAssert(out, ref);
653 INSTANTIATE_TEST_CASE_P(Layer_Test, Scale_untrainable, Combine(
654 /*input size*/ Values(Vec4i(2, 3, 4, 5)),
655 /*axis, #dims*/ Values(Vec2i(0, 1), Vec2i(0, 2), Vec2i(0, 3), Vec2i(0, 4),
656 Vec2i(1, 1), Vec2i(1, 2), Vec2i(1, 3),
657 Vec2i(2, 1), Vec2i(2, 2),
659 /*conv fusion*/ testing::Bool()
662 typedef testing::TestWithParam<tuple<Vec4i, Vec4i, int, int, int> > Crop;
663 TEST_P(Crop, Accuracy)
665 Vec4i inpShapeVec = get<0>(GetParam());
666 Vec4i sizShapeVec = get<1>(GetParam());
667 int axis = get<2>(GetParam());
668 int numOffsets = get<3>(GetParam());
669 int offsetVal = get<4>(GetParam());
670 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
671 const int sizShape[] = {sizShapeVec[0], sizShapeVec[1], sizShapeVec[2], sizShapeVec[3]};
673 // Create a network with two inputs. Crop layer crops a first input to
674 // the size of a second one.
675 // See http://caffe.berkeleyvision.org/tutorial/layers/crop.html
679 lp.name = "testCrop";
681 lp.set("axis", axis);
684 std::vector<int> offsets(numOffsets, offsetVal);
685 lp.set("offset", DictValue::arrayInt<int*>(&offsets[0], offsets.size()));
689 int id = net.addLayerToPrev(lp.name, lp.type, lp);
690 net.connect(0, 1, id, 1);
692 Mat inpImage(4, inpShape, CV_32F);
693 Mat sizImage(4, sizShape, CV_32F);
694 randu(inpImage, -1, 1);
695 randu(sizImage, -1, 1);
697 std::vector<String> inpNames(2);
698 inpNames[0] = "cropImage";
699 inpNames[1] = "sizImage";
700 net.setInputsNames(inpNames);
701 net.setInput(inpImage, inpNames[0]);
702 net.setInput(sizImage, inpNames[1]);
703 net.setPreferableBackend(DNN_BACKEND_OPENCV);
705 // There are a few conditions that represent invalid input to the crop
706 // layer, so in those cases we want to verify an exception is thrown.
708 bool shouldThrowException = false;
709 if (numOffsets > 1 && numOffsets != 4 - axis)
710 shouldThrowException = true;
712 for (int i = axis; i < 4; i++)
713 if (sizShape[i] + offsetVal > inpShape[i])
714 shouldThrowException = true;
717 if (shouldThrowException)
719 ASSERT_ANY_THROW(out = net.forward());
725 // Finally, compare the cropped output blob from the DNN layer (out)
726 // to a reference blob (ref) that we compute here.
728 std::vector<Range> crop_range;
729 crop_range.resize(4, Range::all());
730 for (int i = axis; i < 4; i++)
731 crop_range[i] = Range(offsetVal, sizShape[i] + offsetVal);
733 Mat ref(sizImage.dims, sizImage.size, CV_32F);
734 inpImage(&crop_range[0]).copyTo(ref);
735 normAssert(out, ref);
738 INSTANTIATE_TEST_CASE_P(Layer_Test, Crop, Combine(
739 /*input blob shape*/ Values(Vec4i(1, 3, 20, 30)),
740 /*cropsize blob shape*/ Values(Vec4i(1, 3, 10, 12)),
741 /*start axis*/ Values(0, 1, 2),
742 /*number of offsets*/ Values(0, 1, 2, 4),
743 /*offset value*/ Values(3, 4)
746 // Check that by default average pooling layer should not count zero padded values
747 // into the normalization area.
748 TEST_P(Test_Caffe_layers, Average_pooling_kernel_area)
751 lp.name = "testAvePool";
753 lp.set("kernel_size", 2);
755 lp.set("pool", "AVE");
758 net.addLayerToPrev(lp.name, lp.type, lp);
763 Mat inp = (Mat_<float>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
764 Mat ref = (Mat_<float>(2, 2) << (1 + 2 + 4 + 5) / 4.f, (3 + 6) / 2.f, (7 + 8) / 2.f, 9);
765 Mat tmp = blobFromImage(inp);
766 net.setInput(blobFromImage(inp));
767 net.setPreferableBackend(backend);
768 net.setPreferableTarget(target);
769 Mat out = net.forward();
770 normAssert(out, blobFromImage(ref));
773 // Test PriorBoxLayer in case of no aspect ratios (just squared proposals).
774 TEST_P(Test_Caffe_layers, PriorBox_squares)
776 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
777 throw SkipTestException("");
779 lp.name = "testPriorBox";
780 lp.type = "PriorBox";
781 lp.set("min_size", 2);
782 lp.set("flip", true);
783 lp.set("clip", true);
784 float variance[] = {0.1f, 0.1f, 0.2f, 0.2f};
785 float aspectRatios[] = {1.0f}; // That should be ignored.
786 lp.set("variance", DictValue::arrayReal<float*>(&variance[0], 4));
787 lp.set("aspect_ratio", DictValue::arrayReal<float*>(&aspectRatios[0], 1));
790 int id = net.addLayerToPrev(lp.name, lp.type, lp);
791 net.connect(0, 0, id, 1); // The second input is an input image. Shapes are used for boxes normalization.
792 Mat inp(1, 2, CV_32F);
794 net.setInput(blobFromImage(inp));
795 net.setPreferableBackend(backend);
796 net.setPreferableTarget(target);
797 Mat out = net.forward();
799 Mat ref = (Mat_<float>(4, 4) << 0.0, 0.0, 0.75, 1.0,
801 0.1f, 0.1f, 0.2f, 0.2f,
802 0.1f, 0.1f, 0.2f, 0.2f);
803 double l1 = (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) ? 2e-5 : 1e-5;
804 normAssert(out.reshape(1, 4), ref, "", l1);
807 typedef TestWithParam<tuple<int, int> > Layer_Test_DWconv_Prelu;
808 TEST_P(Layer_Test_DWconv_Prelu, Accuracy)
811 // input img size 3x16x16 value all 1
814 // dw_conv weight[0]=-1 weight[1]=-2 weight[2]=-3 bias={1,2,3}
817 // prelu weight={1,2,3}
820 // output out size 3x14x14 if right: out[0]=-8 out[0]=-32 out[0]=-72
821 // but current opencv output: out[0]=-24 out[0]=-48 out[0]=-72
823 const int num_input = get<0>(GetParam()); //inpChannels
824 const int group = 3; //outChannels=group when group>1
825 const int num_output = get<1>(GetParam());
826 const int kernel_depth = num_input/group;
827 CV_Assert_N(num_output >= group, num_output % group == 0, num_input % group == 0);
833 lp.type = "Convolution";
834 lp.set("kernel_size", 3);
835 lp.set("num_output", num_output);
837 lp.set("group", group);
839 lp.set("engine", "CAFFE");
840 lp.set("bias_term", "true");
842 std::vector<int> weightsShape(4);
843 weightsShape[0] = num_output; // #outChannels
844 weightsShape[1] = kernel_depth; // #inpChannels / group
845 weightsShape[2] = 3; // height
846 weightsShape[3] = 3; // width
847 Mat weights(weightsShape, CV_32F, Scalar(1));
850 for (int i = 0; i < weightsShape[0]; ++i)
852 for (int j = 0; j < weightsShape[1]; ++j)
854 for (int k = 0; k < weightsShape[2]; ++k)
856 for (int l = 0; l < weightsShape[3]; ++l)
858 weights.ptr<float>(i, j, k)[l]=-1*(i+1);
863 lp.blobs.push_back(weights);
866 Mat bias(1, num_output, CV_32F, Scalar(1));
867 for (int i = 0; i < 1; ++i)
869 for (int j = 0; j < num_output; ++j)
871 bias.ptr<float>(i)[j]=j+1;
874 lp.blobs.push_back(bias);
875 net.addLayerToPrev(lp.name, lp.type, lp);
879 lpr.name = "dw_relu";
881 Mat weightsp(1, num_output, CV_32F, Scalar(1));
884 for (int i = 0; i < 1; ++i)
886 for (int j = 0; j < num_output; ++j)
888 weightsp.ptr<float>(i)[j]=j+1;
892 lpr.blobs.push_back(weightsp);
893 net.addLayerToPrev(lpr.name, lpr.type, lpr);
895 int shape[] = {1, num_input, 16, 16};
896 Mat in_blob(4, &shape[0], CV_32FC1, Scalar(1));
898 net.setPreferableBackend(DNN_BACKEND_OPENCV);
899 net.setInput(in_blob);
900 Mat out = net.forward();
903 std::vector<int> outShape(4);
905 outShape[1] = num_output; // outChannels
906 outShape[2] = 14; // height
907 outShape[3] = 14; // width
908 Mat target(outShape, CV_32F, Scalar(1));
909 for (int i = 0; i < outShape[0]; ++i)
911 for (int j = 0; j < outShape[1]; ++j)
913 for (int k = 0; k < outShape[2]; ++k)
915 for (int l = 0; l < outShape[3]; ++l)
917 target.ptr<float>(i, j, k)[l]=(-9*kernel_depth*(j+1)+j+1)*(j+1);
923 normAssert(out, target);
925 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_DWconv_Prelu, Combine(Values(3, 6), Values(3, 6)));
927 #ifdef HAVE_INF_ENGINE
928 // Using Intel's Model Optimizer generate .xml and .bin files:
929 // ./ModelOptimizer -w /path/to/caffemodel -d /path/to/prototxt \
930 // -p FP32 -i -b ${batch_size} -o /path/to/output/folder
931 typedef testing::TestWithParam<Target> Layer_Test_Convolution_DLDT;
932 TEST_P(Layer_Test_Convolution_DLDT, Accuracy)
934 Target targetId = GetParam();
936 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
937 Net netDefault = readNet(_tf("layer_convolution.caffemodel"), _tf("layer_convolution.prototxt"));
938 Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
940 Mat inp = blobFromNPY(_tf("blob.npy"));
942 netDefault.setInput(inp);
943 netDefault.setPreferableBackend(DNN_BACKEND_OPENCV);
944 Mat outDefault = netDefault.forward();
947 net.setPreferableTarget(targetId);
949 Mat out = net.forward();
951 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
952 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
953 normAssert(outDefault, out, "", l1, lInf);
955 std::vector<int> outLayers = net.getUnconnectedOutLayers();
956 ASSERT_EQ(net.getLayer(outLayers[0])->name, "output");
957 ASSERT_EQ(net.getLayer(outLayers[0])->type, "Convolution");
960 TEST_P(Layer_Test_Convolution_DLDT, setInput_uint8)
962 Target targetId = GetParam();
963 Mat inp = blobFromNPY(_tf("blob.npy"));
965 Mat inputs[] = {Mat(inp.dims, inp.size, CV_8U), Mat()};
966 randu(inputs[0], 0, 255);
967 inputs[0].convertTo(inputs[1], CV_32F);
969 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
972 for (int i = 0; i < 2; ++i)
974 Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
975 net.setPreferableTarget(targetId);
976 net.setInput(inputs[i]);
977 outs[i] = net.forward();
978 ASSERT_EQ(outs[i].type(), CV_32F);
980 if (targetId != DNN_TARGET_MYRIAD)
981 normAssert(outs[0], outs[1]);
984 TEST_P(Layer_Test_Convolution_DLDT, multithreading)
986 Target targetId = GetParam();
987 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
988 std::string xmlPath = _tf("layer_convolution" + suffix + ".xml");
989 std::string binPath = _tf("layer_convolution" + suffix + ".bin");
990 Net firstNet = readNet(xmlPath, binPath);
991 Net secondNet = readNet(xmlPath, binPath);
992 Mat inp = blobFromNPY(_tf("blob.npy"));
994 firstNet.setInput(inp);
995 secondNet.setInput(inp);
996 firstNet.setPreferableTarget(targetId);
997 secondNet.setPreferableTarget(targetId);
1000 std::thread t1([&]{out1 = firstNet.forward();});
1001 std::thread t2([&]{out2 = secondNet.forward();});
1006 Mat ref = blobFromNPY(_tf("layer_convolution.npy"));
1007 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
1008 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
1009 normAssert(out1, ref, "first thread", l1, lInf);
1010 normAssert(out2, ref, "second thread", l1, lInf);
1013 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_Convolution_DLDT,
1014 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)));
1016 // 1. Create a .prototxt file with the following network:
1018 // type: "Input" name: "data" top: "data"
1019 // input_param { shape { dim: 1 dim: 2 dim: 3 } }
1022 // type: "Input" name: "second_input" top: "second_input"
1023 // input_param { shape { dim: 1 dim: 2 dim: 3 } }
1026 // type: "Eltwise" name: "output" top: "output"
1027 // bottom: "data" bottom: "second_input"
1028 // eltwise_param { operation: SUM }
1031 // 2. Create a .caffemodel file using Caffe:
1034 // net = caffe.Net('/path/to/prototxt', caffe.TEST)
1035 // net.save('/path/to/caffemodel')
1037 // 3. Convert using ModelOptimizer.
1038 typedef testing::TestWithParam<tuple<int, int, Target, std::vector<int> > > Test_DLDT_two_inputs_3dim;
1039 TEST_P(Test_DLDT_two_inputs_3dim, as_IR)
1041 int firstInpType = get<0>(GetParam());
1042 int secondInpType = get<1>(GetParam());
1043 Target targetId = get<2>(GetParam());
1045 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1046 Net net = readNet(_tf("net_two_inputs" + suffix + ".xml"), _tf("net_two_inputs.bin"));
1047 std::vector<int> inpSize = get<3>(GetParam());
1048 Mat firstInp(3, inpSize.data(), firstInpType);
1049 Mat secondInp(3, inpSize.data(), secondInpType);
1050 randu(firstInp, 0, 255);
1051 randu(secondInp, 0, 255);
1053 net.setInput(firstInp, "data");
1054 net.setInput(secondInp, "second_input");
1055 net.setPreferableTarget(targetId);
1057 double l1 = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1058 (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.06 : 0.0;
1059 double lInf = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1060 (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.23 : 0.0;
1062 Mat out = net.forward();
1065 cv::add(firstInp, secondInp, ref, Mat(), CV_32F);
1066 normAssert(out, ref, "", l1, lInf);
1069 std::vector< std::vector<int> > list_sizes{ {1, 2, 3}, {3, 2, 1}, {5, 5, 5}, {13, 7, 11} };
1071 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs_3dim, Combine(
1072 Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1073 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)),
1074 testing::ValuesIn(list_sizes)
1077 typedef testing::TestWithParam<tuple<int, int, Target> > Test_DLDT_two_inputs;
1078 TEST_P(Test_DLDT_two_inputs, as_backend)
1080 static const float kScale = 0.5f;
1081 static const float kScaleInv = 1.0f / kScale;
1083 Target targetId = get<2>(GetParam());
1087 lp.type = "Eltwise";
1088 lp.name = "testLayer";
1089 lp.set("operation", "sum");
1090 int eltwiseId = net.addLayerToPrev(lp.name, lp.type, lp); // connect to a first input
1091 net.connect(0, 1, eltwiseId, 1); // connect to a second input
1093 int inpSize[] = {1, 2, 3, 4};
1094 Mat firstInp(4, &inpSize[0], get<0>(GetParam()));
1095 Mat secondInp(4, &inpSize[0], get<1>(GetParam()));
1096 randu(firstInp, 0, 255);
1097 randu(secondInp, 0, 255);
1099 net.setInputsNames({"data", "second_input"});
1100 net.setInput(firstInp, "data", kScale);
1101 net.setInput(secondInp, "second_input", kScaleInv);
1102 net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1103 net.setPreferableTarget(targetId);
1104 Mat out = net.forward();
1107 addWeighted(firstInp, kScale, secondInp, kScaleInv, 0, ref, CV_32F);
1108 // Output values are in range [0, 637.5].
1109 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.06 : 1e-6;
1110 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.3 : 1e-5;
1111 normAssert(out, ref, "", l1, lInf);
1114 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs, Combine(
1115 Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1116 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE))
1119 class UnsupportedLayer : public Layer
1122 UnsupportedLayer(const LayerParams ¶ms) {}
1124 static Ptr<Layer> create(const LayerParams& params)
1126 return Ptr<Layer>(new UnsupportedLayer(params));
1129 virtual bool supportBackend(int backendId) CV_OVERRIDE
1131 return backendId == DNN_BACKEND_OPENCV;
1134 virtual void forward(cv::InputArrayOfArrays inputs, cv::OutputArrayOfArrays outputs, cv::OutputArrayOfArrays internals) CV_OVERRIDE {}
1137 TEST(Test_DLDT, fused_output)
1139 static const int kNumChannels = 3;
1140 CV_DNN_REGISTER_LAYER_CLASS(Unsupported, UnsupportedLayer);
1144 lp.set("kernel_size", 1);
1145 lp.set("num_output", 3);
1146 lp.set("bias_term", false);
1147 lp.type = "Convolution";
1148 lp.name = "testConv";
1149 lp.blobs.push_back(Mat({kNumChannels, 1, 1, 1}, CV_32F, Scalar(1)));
1150 net.addLayerToPrev(lp.name, lp.type, lp);
1154 lp.set("bias_term", false);
1156 lp.name = "testScale";
1157 lp.blobs.push_back(Mat({kNumChannels}, CV_32F, Scalar(1)));
1158 net.addLayerToPrev(lp.name, lp.type, lp);
1162 net.addLayerToPrev("unsupported_layer", "Unsupported", lp);
1164 net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1165 net.setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1166 ASSERT_NO_THROW(net.forward());
1167 LayerFactory::unregisterLayer("Unsupported");
1170 TEST(Test_DLDT, multiple_networks)
1173 for (int i = 0; i < 2; ++i)
1175 nets[i].setInputsNames(std::vector<String>(1, format("input_%d", i)));
1178 lp.set("kernel_size", 1);
1179 lp.set("num_output", 1);
1180 lp.set("bias_term", false);
1181 lp.type = "Convolution";
1182 lp.name = format("testConv_%d", i);
1183 lp.blobs.push_back(Mat({1, 1, 1, 1}, CV_32F, Scalar(1 + i)));
1184 nets[i].addLayerToPrev(lp.name, lp.type, lp);
1185 nets[i].setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1186 nets[i].setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1188 Mat out_1 = nets[0].forward();
1189 Mat out_2 = nets[1].forward();
1190 // After the second model is initialized we try to receive an output from the first network again.
1191 out_1 = nets[0].forward();
1192 normAssert(2 * out_1, out_2);
1194 #endif // HAVE_INF_ENGINE
1196 // Test a custom layer.
1197 class CustomInterpLayer CV_FINAL : public Layer
1200 CustomInterpLayer(const LayerParams ¶ms) : Layer(params)
1202 zoomFactor = params.get<int>("zoom_factor", 0);
1203 outWidth = params.get<int>("width", 0);
1204 outHeight = params.get<int>("height", 0);
1207 static Ptr<Layer> create(LayerParams& params)
1209 return Ptr<Layer>(new CustomInterpLayer(params));
1212 virtual bool getMemoryShapes(const std::vector<std::vector<int> > &inputs,
1213 const int requiredOutputs,
1214 std::vector<std::vector<int> > &outputs,
1215 std::vector<std::vector<int> > &internals) const CV_OVERRIDE
1217 const int batchSize = inputs[0][0];
1218 const int numChannels = inputs[0][1];
1219 const int inpHeight = inputs[0][2];
1220 const int inpWidth = inputs[0][3];
1222 std::vector<int> outShape(4);
1223 outShape[0] = batchSize;
1224 outShape[1] = numChannels;
1225 outShape[2] = outHeight != 0 ? outHeight : (inpHeight + (inpHeight - 1) * (zoomFactor - 1));
1226 outShape[3] = outWidth != 0 ? outWidth : (inpWidth + (inpWidth - 1) * (zoomFactor - 1));
1227 outputs.assign(1, outShape);
1231 virtual void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
1233 std::vector<Mat> outputs;
1234 outputs_arr.getMatVector(outputs);
1236 if (!outWidth && !outHeight)
1238 outHeight = outputs[0].size[2];
1239 outWidth = outputs[0].size[3];
1243 // Implementation of this custom layer is based on https://github.com/cdmh/deeplab-public/blob/master/src/caffe/layers/interp_layer.cpp
1244 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1246 CV_TRACE_FUNCTION();
1247 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1249 if (inputs_arr.depth() == CV_16S)
1251 forward_fallback(inputs_arr, outputs_arr, internals_arr);
1255 std::vector<Mat> inputs, outputs;
1256 inputs_arr.getMatVector(inputs);
1257 outputs_arr.getMatVector(outputs);
1259 Mat& inp = inputs[0];
1260 Mat& out = outputs[0];
1261 const float* inpData = (float*)inp.data;
1262 float* outData = (float*)out.data;
1264 const int batchSize = inp.size[0];
1265 const int numChannels = inp.size[1];
1266 const int inpHeight = inp.size[2];
1267 const int inpWidth = inp.size[3];
1269 const float rheight = (outHeight > 1) ? static_cast<float>(inpHeight - 1) / (outHeight - 1) : 0.f;
1270 const float rwidth = (outWidth > 1) ? static_cast<float>(inpWidth - 1) / (outWidth - 1) : 0.f;
1271 for (int h2 = 0; h2 < outHeight; ++h2)
1273 const float h1r = rheight * h2;
1275 const int h1p = (h1 < inpHeight - 1) ? 1 : 0;
1276 const float h1lambda = h1r - h1;
1277 const float h0lambda = 1.f - h1lambda;
1278 for (int w2 = 0; w2 < outWidth; ++w2)
1280 const float w1r = rwidth * w2;
1282 const int w1p = (w1 < inpWidth - 1) ? 1 : 0;
1283 const float w1lambda = w1r - w1;
1284 const float w0lambda = 1.f - w1lambda;
1285 const float* pos1 = inpData + h1 * inpWidth + w1;
1286 float* pos2 = outData + h2 * outWidth + w2;
1287 for (int c = 0; c < batchSize * numChannels; ++c)
1290 h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[w1p]) +
1291 h1lambda * (w0lambda * pos1[h1p * inpWidth] + w1lambda * pos1[h1p * inpWidth + w1p]);
1292 pos1 += inpWidth * inpHeight;
1293 pos2 += outWidth * outHeight;
1300 int outWidth, outHeight, zoomFactor;
1303 #ifndef OPENCV_DNN_EXTERNAL_PROTOBUF
1304 TEST_P(Test_Caffe_layers, Interp)
1306 TEST_P(Test_Caffe_layers, DISABLED_Interp) // requires patched protobuf (available in OpenCV source tree only)
1309 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
1310 throw SkipTestException("");
1311 // Test a custom layer.
1312 CV_DNN_REGISTER_LAYER_CLASS(Interp, CustomInterpLayer);
1315 testLayerUsingCaffeModels("layer_interp", false, false);
1319 LayerFactory::unregisterLayer("Interp");
1322 LayerFactory::unregisterLayer("Interp");
1324 // Test an implemented layer.
1325 testLayerUsingCaffeModels("layer_interp", false, false);
1328 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_Caffe_layers, dnnBackendsAndTargets());
1330 TEST(Layer_Test_PoolingIndices, Accuracy)
1335 lp.set("pool", "max");
1336 lp.set("kernel_w", 2);
1337 lp.set("kernel_h", 2);
1338 lp.set("stride_w", 2);
1339 lp.set("stride_h", 2);
1342 lp.name = "testLayer.name"; // This test also checks that OpenCV lets use names with dots.
1343 lp.type = "Pooling";
1344 net.addLayerToPrev(lp.name, lp.type, lp);
1346 Mat inp(10, 10, CV_8U);
1349 Mat maxValues(5, 5, CV_32F, Scalar(-1)), indices(5, 5, CV_32F, Scalar(-1));
1350 for (int y = 0; y < 10; ++y)
1353 for (int x = 0; x < 10; ++x)
1356 uint8_t val = inp.at<uint8_t>(y, x);
1357 if ((float)inp.at<uint8_t>(y, x) > maxValues.at<float>(dstY, dstX))
1359 maxValues.at<float>(dstY, dstX) = val;
1360 indices.at<float>(dstY, dstX) = y * 10 + x;
1364 net.setPreferableBackend(DNN_BACKEND_OPENCV);
1365 net.setInput(blobFromImage(inp));
1367 std::vector<Mat> outputs;
1368 net.forward(outputs, lp.name);
1369 normAssert(maxValues, outputs[0].reshape(1, 5));
1370 normAssert(indices, outputs[1].reshape(1, 5));
1373 typedef testing::TestWithParam<tuple<Vec4i, int, tuple<Backend, Target> > > Layer_Test_ShuffleChannel;
1374 TEST_P(Layer_Test_ShuffleChannel, Accuracy)
1376 Vec4i inpShapeVec = get<0>(GetParam());
1377 int group = get<1>(GetParam());
1378 ASSERT_EQ(inpShapeVec[1] % group, 0);
1379 const int groupSize = inpShapeVec[1] / group;
1380 int backendId = get<0>(get<2>(GetParam()));
1381 int targetId = get<1>(get<2>(GetParam()));
1385 lp.set("group", group);
1386 lp.type = "ShuffleChannel";
1387 lp.name = "testLayer";
1388 net.addLayerToPrev(lp.name, lp.type, lp);
1390 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
1391 Mat inp(4, inpShape, CV_32F);
1395 net.setPreferableBackend(backendId);
1396 net.setPreferableTarget(targetId);
1397 Mat out = net.forward();
1399 double l1 = (targetId == DNN_TARGET_OPENCL_FP16) ? 5e-2 : 1e-5;
1400 double lInf = (targetId == DNN_TARGET_OPENCL_FP16) ? 7e-2 : 1e-4;
1401 for (int n = 0; n < inpShapeVec[0]; ++n)
1403 for (int c = 0; c < inpShapeVec[1]; ++c)
1405 Mat outChannel = getPlane(out, n, c);
1406 Mat inpChannel = getPlane(inp, n, groupSize * (c % group) + c / group);
1407 normAssert(outChannel, inpChannel, "", l1, lInf);
1411 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_ShuffleChannel, Combine(
1412 /*input shape*/ Values(Vec4i(1, 6, 5, 7), Vec4i(3, 12, 1, 4)),
1413 /*group*/ Values(1, 2, 3, 6), dnnBackendsAndTargets(/*with IE*/ false)
1416 // Check if relu is not fused to convolution if we requested it's output
1417 TEST(Layer_Test_Convolution, relu_fusion)
1422 lp.set("kernel_size", 1);
1423 lp.set("num_output", 1);
1424 lp.set("bias_term", false);
1425 lp.type = "Convolution";
1426 lp.name = "testConv";
1428 int weightsShape[] = {1, 1, 1, 1};
1429 Mat weights(4, &weightsShape[0], CV_32F, Scalar(1));
1430 lp.blobs.push_back(weights);
1431 net.addLayerToPrev(lp.name, lp.type, lp);
1436 lp.name = "testReLU";
1437 net.addLayerToPrev(lp.name, lp.type, lp);
1439 int sz[] = {1, 1, 2, 3};
1440 Mat input(4, &sz[0], CV_32F);
1441 randu(input, -1.0, -0.1);
1442 net.setInput(input);
1443 net.setPreferableBackend(DNN_BACKEND_OPENCV);
1444 Mat output = net.forward("testConv");
1445 normAssert(input, output);