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 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE); // TODO IE_CPU
146 testLayerUsingCaffeModels("layer_deconvolution", true, false);
149 TEST_P(Test_Caffe_layers, InnerProduct)
151 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
152 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
153 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
154 applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
155 testLayerUsingCaffeModels("layer_inner_product", true);
158 TEST_P(Test_Caffe_layers, Pooling_max)
160 testLayerUsingCaffeModels("layer_pooling_max");
163 TEST_P(Test_Caffe_layers, Pooling_ave)
165 testLayerUsingCaffeModels("layer_pooling_ave");
168 TEST_P(Test_Caffe_layers, MVN)
170 testLayerUsingCaffeModels("layer_mvn");
173 void testReshape(const MatShape& inputShape, const MatShape& targetShape,
174 int axis = 0, int num_axes = -1,
175 MatShape mask = MatShape())
178 params.set("axis", axis);
179 params.set("num_axes", num_axes);
182 params.set("dim", DictValue::arrayInt<int*>(&mask[0], mask.size()));
185 Mat inp(inputShape.size(), &inputShape[0], CV_32F);
186 std::vector<Mat> inpVec(1, inp);
187 std::vector<Mat> outVec, intVec;
189 Ptr<Layer> rl = LayerFactory::createLayerInstance("Reshape", params);
190 runLayer(rl, inpVec, outVec);
192 Mat& out = outVec[0];
193 MatShape shape(out.size.p, out.size.p + out.dims);
194 EXPECT_EQ(shape, targetShape);
197 TEST(Layer_Test_Reshape, Accuracy)
200 int inp[] = {4, 3, 1, 2};
201 int out[] = {4, 3, 2};
202 testReshape(MatShape(inp, inp + 4), MatShape(out, out + 3), 2, 1);
205 int inp[] = {1, 128, 4, 4};
206 int out[] = {1, 2048};
207 int mask[] = {-1, 2048};
208 testReshape(MatShape(inp, inp + 4), MatShape(out, out + 2), 0, -1,
209 MatShape(mask, mask + 2));
212 int inp[] = {1, 2, 3};
213 int out[] = {3, 1, 2};
214 int mask[] = {3, 1, 2};
215 testReshape(MatShape(inp, inp + 3), MatShape(out, out + 3), 0, -1,
216 MatShape(mask, mask + 3));
220 TEST_P(Test_Caffe_layers, BatchNorm)
222 testLayerUsingCaffeModels("layer_batch_norm", true);
223 testLayerUsingCaffeModels("layer_batch_norm_local_stats", true, false);
226 TEST_P(Test_Caffe_layers, ReLU)
228 testLayerUsingCaffeModels("layer_relu");
231 TEST_P(Test_Caffe_layers, Dropout)
233 testLayerUsingCaffeModels("layer_dropout");
236 TEST_P(Test_Caffe_layers, Concat)
238 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_GE(2019010000)
239 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
240 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_2019R1, CV_TEST_TAG_DNN_SKIP_IE_2019R1_1);
242 testLayerUsingCaffeModels("layer_concat");
243 testLayerUsingCaffeModels("layer_concat_optim", true, false);
244 testLayerUsingCaffeModels("layer_concat_shared_input", true, false);
247 TEST_P(Test_Caffe_layers, Fused_Concat)
249 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_GE(2019010000)
250 if (backend == DNN_BACKEND_INFERENCE_ENGINE) // Test is disabled for DLIE due negative_slope parameter
251 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE, CV_TEST_TAG_DNN_SKIP_IE_2019R1, CV_TEST_TAG_DNN_SKIP_IE_2019R1_1);
254 #if defined(INF_ENGINE_RELEASE)
255 if (backend == DNN_BACKEND_INFERENCE_ENGINE && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
256 applyTestTag(target == DNN_TARGET_OPENCL ? CV_TEST_TAG_DNN_SKIP_IE_OPENCL : CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16);
274 lp.name = "someLayer";
275 interLayer = net.addLayerToPrev(lp.name, lp.type, lp);
281 lp.name = "testConcat";
282 int id = net.addLayer(lp.name, lp.type, lp);
283 net.connect(interLayer, 0, id, 0);
284 net.connect(interLayer, 0, id, 1);
286 int shape[] = {1, 2, 3, 4};
287 Mat input(4, shape, CV_32F);
288 randu(input, 0.0f, 1.0f); // [0, 1] to make AbsVal an identity transformation.
291 net.setPreferableBackend(backend);
292 net.setPreferableTarget(target);
293 Mat out = net.forward();
295 normAssert(slice(out, Range::all(), Range(0, 2), Range::all(), Range::all()), input, "", default_l1, default_lInf);
296 normAssert(slice(out, Range::all(), Range(2, 4), Range::all(), Range::all()), input, "", default_l1, default_lInf);
299 TEST_P(Test_Caffe_layers, Eltwise)
301 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
302 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
303 testLayerUsingCaffeModels("layer_eltwise");
306 TEST_P(Test_Caffe_layers, PReLU)
308 testLayerUsingCaffeModels("layer_prelu", true);
311 // TODO: fix an unstable test case
312 TEST_P(Test_Caffe_layers, layer_prelu_fc)
314 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
315 applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
316 // Reference output values are in range [-0.0001, 10.3906]
317 double l1 = (target == DNN_TARGET_MYRIAD) ? 0.005 : 0.0;
318 double lInf = (target == DNN_TARGET_MYRIAD) ? 0.021 : 0.0;
319 testLayerUsingCaffeModels("layer_prelu_fc", true, false, l1, lInf);
322 //template<typename XMat>
323 //static void test_Layer_Concat()
325 // Matx21f a(1.f, 1.f), b(2.f, 2.f), c(3.f, 3.f);
326 // std::vector<Blob> res(1), src = { Blob(XMat(a)), Blob(XMat(b)), Blob(XMat(c)) };
327 // Blob ref(XMat(Matx23f(1.f, 2.f, 3.f, 1.f, 2.f, 3.f)));
329 // runLayer(ConcatLayer::create(1), src, res);
330 // normAssert(ref, res[0]);
332 //TEST(Layer_Concat, Accuracy)
334 // test_Layer_Concat<Mat>());
336 //OCL_TEST(Layer_Concat, Accuracy)
338 // OCL_ON(test_Layer_Concat<Mat>());
342 TEST_P(Test_Caffe_layers, Reshape_Split_Slice)
344 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
345 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
347 Net net = readNetFromCaffe(_tf("reshape_and_slice_routines.prototxt"));
348 ASSERT_FALSE(net.empty());
350 net.setPreferableBackend(backend);
351 net.setPreferableTarget(target);
353 Mat input(6, 12, CV_32F);
355 rng.fill(input, RNG::UNIFORM, -1, 1);
357 net.setInput(input, "input");
358 Mat output = net.forward("output");
360 normAssert(input, output, "", default_l1, default_lInf);
363 TEST_P(Test_Caffe_layers, Conv_Elu)
365 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE <= 2018050000
366 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
367 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_2018R5);
370 Net net = readNetFromTensorflow(_tf("layer_elu_model.pb"));
371 ASSERT_FALSE(net.empty());
373 Mat inp = blobFromNPY(_tf("layer_elu_in.npy"));
374 Mat ref = blobFromNPY(_tf("layer_elu_out.npy"));
376 net.setInput(inp, "input");
377 net.setPreferableBackend(backend);
378 net.setPreferableTarget(target);
379 Mat out = net.forward();
381 normAssert(ref, out, "", default_l1, default_lInf);
384 class Layer_LSTM_Test : public ::testing::Test
389 Ptr<LSTMLayer> layer;
390 std::vector<Mat> inputs, outputs;
394 void init(const MatShape &inpShape_, const MatShape &outShape_,
395 bool produceCellOutput, bool useTimestampDim)
397 numInp = total(inpShape_);
398 numOut = total(outShape_);
400 Wh = Mat::ones(4 * numOut, numOut, CV_32F);
401 Wx = Mat::ones(4 * numOut, numInp, CV_32F);
402 b = Mat::ones(4 * numOut, 1, CV_32F);
409 lp.set<bool>("produce_cell_output", produceCellOutput);
410 lp.set<bool>("use_timestamp_dim", useTimestampDim);
412 layer = LSTMLayer::create(lp);
413 layer->setOutShape(outShape_);
417 TEST_F(Layer_LSTM_Test, get_set_test)
420 MatShape inpShape = shape(5, 3, 2);
421 MatShape outShape = shape(3, 1, 2);
422 MatShape inpResShape = concat(shape(TN), inpShape);
423 MatShape outResShape = concat(shape(TN), outShape);
425 init(inpShape, outShape, true, false);
426 layer->setOutShape(outShape);
428 Mat C((int)outResShape.size(), &outResShape[0], CV_32F);
433 Mat inp((int)inpResShape.size(), &inpResShape[0], CV_32F);
436 inputs.push_back(inp);
437 runLayer(layer, inputs, outputs);
439 EXPECT_EQ(2u, outputs.size());
441 print(outResShape, "outResShape");
442 print(shape(outputs[0]), "out0");
443 print(shape(outputs[0]), "out1");
445 EXPECT_EQ(outResShape, shape(outputs[0]));
446 EXPECT_EQ(outResShape, shape(outputs[1]));
448 EXPECT_EQ(0, layer->inputNameToIndex("x"));
449 EXPECT_EQ(0, layer->outputNameToIndex("h"));
450 EXPECT_EQ(1, layer->outputNameToIndex("c"));
453 TEST(Layer_LSTM_Test_Accuracy_with_, CaffeRecurrent)
457 lp.blobs[0] = blobFromNPY(_tf("lstm.prototxt.w_2.npy")); // Wh
458 lp.blobs[1] = blobFromNPY(_tf("lstm.prototxt.w_0.npy")); // Wx
459 lp.blobs[2] = blobFromNPY(_tf("lstm.prototxt.w_1.npy")); // bias
460 Ptr<LSTMLayer> layer = LSTMLayer::create(lp);
462 Mat inp = blobFromNPY(_tf("recurrent.input.npy"));
463 std::vector<Mat> inputs(1, inp), outputs;
464 runLayer(layer, inputs, outputs);
466 Mat h_t_reference = blobFromNPY(_tf("lstm.prototxt.h_1.npy"));
467 normAssert(h_t_reference, outputs[0]);
470 TEST(Layer_RNN_Test_Accuracy_with_, CaffeRecurrent)
472 Ptr<RNNLayer> layer = RNNLayer::create(LayerParams());
475 blobFromNPY(_tf("rnn.prototxt.w_0.npy")),
476 blobFromNPY(_tf("rnn.prototxt.w_1.npy")),
477 blobFromNPY(_tf("rnn.prototxt.w_2.npy")),
478 blobFromNPY(_tf("rnn.prototxt.w_3.npy")),
479 blobFromNPY(_tf("rnn.prototxt.w_4.npy")) );
481 std::vector<Mat> output, input(1, blobFromNPY(_tf("recurrent.input.npy")));
482 runLayer(layer, input, output);
484 Mat h_ref = blobFromNPY(_tf("rnn.prototxt.h_1.npy"));
485 normAssert(h_ref, output[0]);
489 class Layer_RNN_Test : public ::testing::Test
492 int nX, nH, nO, nT, nS;
493 Mat Whh, Wxh, bh, Who, bo;
496 std::vector<Mat> inputs, outputs;
506 Whh = Mat::ones(nH, nH, CV_32F);
507 Wxh = Mat::ones(nH, nX, CV_32F);
508 bh = Mat::ones(nH, 1, CV_32F);
509 Who = Mat::ones(nO, nH, CV_32F);
510 bo = Mat::ones(nO, 1, CV_32F);
512 layer = RNNLayer::create(LayerParams());
513 layer->setProduceHiddenOutput(true);
514 layer->setWeights(Wxh, bh, Whh, Who, bo);
518 TEST_F(Layer_RNN_Test, get_set_test)
520 int sz[] = { nT, nS, 1, nX };
521 Mat inp(4, sz, CV_32F);
523 inputs.push_back(inp);
524 runLayer(layer, inputs, outputs);
526 EXPECT_EQ(outputs.size(), 2u);
527 EXPECT_EQ(shape(outputs[0]), shape(nT, nS, nO));
528 EXPECT_EQ(shape(outputs[1]), shape(nT, nS, nH));
531 TEST(Layer_Test_ROIPooling, Accuracy)
533 Net net = readNetFromCaffe(_tf("net_roi_pooling.prototxt"));
535 Mat inp = blobFromNPY(_tf("net_roi_pooling.input.npy"));
536 Mat rois = blobFromNPY(_tf("net_roi_pooling.rois.npy"));
537 Mat ref = blobFromNPY(_tf("net_roi_pooling.npy"));
539 net.setInput(inp, "input");
540 net.setInput(rois, "rois");
541 net.setPreferableBackend(DNN_BACKEND_OPENCV);
543 Mat out = net.forward();
545 normAssert(out, ref);
548 TEST_P(Test_Caffe_layers, FasterRCNN_Proposal)
550 if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
551 applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
552 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
553 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
555 Net net = readNetFromCaffe(_tf("net_faster_rcnn_proposal.prototxt"));
557 Mat scores = blobFromNPY(_tf("net_faster_rcnn_proposal.scores.npy"));
558 Mat deltas = blobFromNPY(_tf("net_faster_rcnn_proposal.deltas.npy"));
559 Mat imInfo = (Mat_<float>(1, 3) << 600, 800, 1.6f);
561 net.setInput(scores, "rpn_cls_prob_reshape");
562 net.setInput(deltas, "rpn_bbox_pred");
563 net.setInput(imInfo, "im_info");
565 std::vector<Mat> outs;
566 net.setPreferableBackend(backend);
567 net.setPreferableTarget(target);
568 net.forward(outs, "output");
570 for (int i = 0; i < 2; ++i)
572 Mat ref = blobFromNPY(_tf(i == 0 ? "net_faster_rcnn_proposal.out_rois.npy" :
573 "net_faster_rcnn_proposal.out_scores.npy"));
574 const int numDets = ref.size[0];
575 EXPECT_LE(numDets, outs[i].size[0]);
576 normAssert(outs[i].rowRange(0, numDets), ref);
578 if (numDets < outs[i].size[0])
580 EXPECT_EQ(countNonZero(outs[i].rowRange(numDets, outs[i].size[0])), 0);
585 typedef testing::TestWithParam<tuple<Vec4i, Vec2i, bool> > Scale_untrainable;
586 TEST_P(Scale_untrainable, Accuracy)
588 Vec4i inpShapeVec = get<0>(GetParam());
589 int axis = get<1>(GetParam())[0];
590 int weightsDims = get<1>(GetParam())[1];
591 bool testFusion = get<2>(GetParam());
592 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
594 // Create a network with two inputs. Scale layer multiplies a first input to
595 // a second one. See http://caffe.berkeleyvision.org/tutorial/layers/scale.html
597 // Check that this version of Scale layer won't be fused with Convolution layer.
601 lp.set("kernel_size", 1);
602 lp.set("num_output", 3);
604 lp.set("bias_term", false);
605 lp.type = "Convolution";
606 lp.name = "testConv";
608 std::vector<int> weightsShape(4);
609 weightsShape[0] = 3; // #outChannels
610 weightsShape[1] = 1; // #inpChannels / group
611 weightsShape[2] = 1; // height
612 weightsShape[3] = 1; // width
613 Mat weights(weightsShape, CV_32F);
615 lp.blobs.push_back(weights);
616 net.addLayerToPrev(lp.name, lp.type, lp);
620 lp.name = "testLayer";
621 lp.set("axis", axis);
622 int id = net.addLayerToPrev(lp.name, lp.type, lp);
623 net.connect(0, 1, id, 1);
625 Mat input(4, inpShape, CV_32F);
626 Mat weights(weightsDims, &inpShape[axis], CV_32F);
628 randu(weights, -1, 1);
630 std::vector<String> inpNames(2);
631 inpNames[0] = "scale_input";
632 inpNames[1] = "scale_weights";
633 net.setInputsNames(inpNames);
634 net.setInput(input, inpNames[0]);
635 net.setInput(weights, inpNames[1]);
636 net.setPreferableBackend(DNN_BACKEND_OPENCV);
637 Mat out = net.forward();
639 Mat ref(input.dims, input.size, CV_32F);
640 float* inpData = (float*)input.data;
641 float* refData = (float*)ref.data;
642 float* weightsData = (float*)weights.data;
644 for (int i = axis + weightsDims; i < 4; ++i)
645 spatialSize *= inpShape[i];
646 for (int i = 0; i < ref.total(); ++i)
648 float w = weightsData[(i / spatialSize) % weights.total()];
649 refData[i] = inpData[i] * w;
651 normAssert(out, ref);
654 INSTANTIATE_TEST_CASE_P(Layer_Test, Scale_untrainable, Combine(
655 /*input size*/ Values(Vec4i(2, 3, 4, 5)),
656 /*axis, #dims*/ Values(Vec2i(0, 1), Vec2i(0, 2), Vec2i(0, 3), Vec2i(0, 4),
657 Vec2i(1, 1), Vec2i(1, 2), Vec2i(1, 3),
658 Vec2i(2, 1), Vec2i(2, 2),
660 /*conv fusion*/ testing::Bool()
663 typedef testing::TestWithParam<tuple<Vec4i, Vec4i, int, int, int> > Crop;
664 TEST_P(Crop, Accuracy)
666 Vec4i inpShapeVec = get<0>(GetParam());
667 Vec4i sizShapeVec = get<1>(GetParam());
668 int axis = get<2>(GetParam());
669 int numOffsets = get<3>(GetParam());
670 int offsetVal = get<4>(GetParam());
671 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
672 const int sizShape[] = {sizShapeVec[0], sizShapeVec[1], sizShapeVec[2], sizShapeVec[3]};
674 // Create a network with two inputs. Crop layer crops a first input to
675 // the size of a second one.
676 // See http://caffe.berkeleyvision.org/tutorial/layers/crop.html
680 lp.name = "testCrop";
682 lp.set("axis", axis);
685 std::vector<int> offsets(numOffsets, offsetVal);
686 lp.set("offset", DictValue::arrayInt<int*>(&offsets[0], offsets.size()));
690 int id = net.addLayerToPrev(lp.name, lp.type, lp);
691 net.connect(0, 1, id, 1);
693 Mat inpImage(4, inpShape, CV_32F);
694 Mat sizImage(4, sizShape, CV_32F);
695 randu(inpImage, -1, 1);
696 randu(sizImage, -1, 1);
698 std::vector<String> inpNames(2);
699 inpNames[0] = "cropImage";
700 inpNames[1] = "sizImage";
701 net.setInputsNames(inpNames);
702 net.setInput(inpImage, inpNames[0]);
703 net.setInput(sizImage, inpNames[1]);
704 net.setPreferableBackend(DNN_BACKEND_OPENCV);
706 // There are a few conditions that represent invalid input to the crop
707 // layer, so in those cases we want to verify an exception is thrown.
709 bool shouldThrowException = false;
710 if (numOffsets > 1 && numOffsets != 4 - axis)
711 shouldThrowException = true;
713 for (int i = axis; i < 4; i++)
714 if (sizShape[i] + offsetVal > inpShape[i])
715 shouldThrowException = true;
718 if (shouldThrowException)
720 ASSERT_ANY_THROW(out = net.forward());
726 // Finally, compare the cropped output blob from the DNN layer (out)
727 // to a reference blob (ref) that we compute here.
729 std::vector<Range> crop_range;
730 crop_range.resize(4, Range::all());
731 for (int i = axis; i < 4; i++)
732 crop_range[i] = Range(offsetVal, sizShape[i] + offsetVal);
734 Mat ref(sizImage.dims, sizImage.size, CV_32F);
735 inpImage(&crop_range[0]).copyTo(ref);
736 normAssert(out, ref);
739 INSTANTIATE_TEST_CASE_P(Layer_Test, Crop, Combine(
740 /*input blob shape*/ Values(Vec4i(1, 3, 20, 30)),
741 /*cropsize blob shape*/ Values(Vec4i(1, 3, 10, 12)),
742 /*start axis*/ Values(0, 1, 2),
743 /*number of offsets*/ Values(0, 1, 2, 4),
744 /*offset value*/ Values(3, 4)
747 // Check that by default average pooling layer should not count zero padded values
748 // into the normalization area.
749 TEST_P(Test_Caffe_layers, Average_pooling_kernel_area)
752 lp.name = "testAvePool";
754 lp.set("kernel_size", 2);
756 lp.set("pool", "AVE");
759 net.addLayerToPrev(lp.name, lp.type, lp);
764 Mat inp = (Mat_<float>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
765 Mat ref = (Mat_<float>(2, 2) << (1 + 2 + 4 + 5) / 4.f, (3 + 6) / 2.f, (7 + 8) / 2.f, 9);
766 Mat tmp = blobFromImage(inp);
767 net.setInput(blobFromImage(inp));
768 net.setPreferableBackend(backend);
769 net.setPreferableTarget(target);
770 Mat out = net.forward();
771 normAssert(out, blobFromImage(ref));
774 // Test PriorBoxLayer in case of no aspect ratios (just squared proposals).
775 TEST_P(Test_Caffe_layers, PriorBox_squares)
777 if (backend == DNN_BACKEND_INFERENCE_ENGINE)
778 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
781 lp.name = "testPriorBox";
782 lp.type = "PriorBox";
783 lp.set("min_size", 2);
784 lp.set("flip", true);
785 lp.set("clip", true);
786 float variance[] = {0.1f, 0.1f, 0.2f, 0.2f};
787 float aspectRatios[] = {1.0f}; // That should be ignored.
788 lp.set("variance", DictValue::arrayReal<float*>(&variance[0], 4));
789 lp.set("aspect_ratio", DictValue::arrayReal<float*>(&aspectRatios[0], 1));
792 int id = net.addLayerToPrev(lp.name, lp.type, lp);
793 net.connect(0, 0, id, 1); // The second input is an input image. Shapes are used for boxes normalization.
794 Mat inp(1, 2, CV_32F);
796 net.setInput(blobFromImage(inp));
797 net.setPreferableBackend(backend);
798 net.setPreferableTarget(target);
799 Mat out = net.forward();
801 Mat ref = (Mat_<float>(4, 4) << 0.0, 0.0, 0.75, 1.0,
803 0.1f, 0.1f, 0.2f, 0.2f,
804 0.1f, 0.1f, 0.2f, 0.2f);
805 double l1 = (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) ? 2e-5 : 1e-5;
806 normAssert(out.reshape(1, 4), ref, "", l1);
809 typedef TestWithParam<tuple<int, int> > Layer_Test_DWconv_Prelu;
810 TEST_P(Layer_Test_DWconv_Prelu, Accuracy)
813 // input img size 3x16x16 value all 1
816 // dw_conv weight[0]=-1 weight[1]=-2 weight[2]=-3 bias={1,2,3}
819 // prelu weight={1,2,3}
822 // output out size 3x14x14 if right: out[0]=-8 out[0]=-32 out[0]=-72
823 // but current opencv output: out[0]=-24 out[0]=-48 out[0]=-72
825 const int num_input = get<0>(GetParam()); //inpChannels
826 const int group = 3; //outChannels=group when group>1
827 const int num_output = get<1>(GetParam());
828 const int kernel_depth = num_input/group;
829 CV_Assert_N(num_output >= group, num_output % group == 0, num_input % group == 0);
835 lp.type = "Convolution";
836 lp.set("kernel_size", 3);
837 lp.set("num_output", num_output);
839 lp.set("group", group);
841 lp.set("engine", "CAFFE");
842 lp.set("bias_term", "true");
844 std::vector<int> weightsShape(4);
845 weightsShape[0] = num_output; // #outChannels
846 weightsShape[1] = kernel_depth; // #inpChannels / group
847 weightsShape[2] = 3; // height
848 weightsShape[3] = 3; // width
849 Mat weights(weightsShape, CV_32F, Scalar(1));
852 for (int i = 0; i < weightsShape[0]; ++i)
854 for (int j = 0; j < weightsShape[1]; ++j)
856 for (int k = 0; k < weightsShape[2]; ++k)
858 for (int l = 0; l < weightsShape[3]; ++l)
860 weights.ptr<float>(i, j, k)[l]=-1*(i+1);
865 lp.blobs.push_back(weights);
868 Mat bias(1, num_output, CV_32F, Scalar(1));
869 for (int i = 0; i < 1; ++i)
871 for (int j = 0; j < num_output; ++j)
873 bias.ptr<float>(i)[j]=j+1;
876 lp.blobs.push_back(bias);
877 net.addLayerToPrev(lp.name, lp.type, lp);
881 lpr.name = "dw_relu";
883 Mat weightsp(1, num_output, CV_32F, Scalar(1));
886 for (int i = 0; i < 1; ++i)
888 for (int j = 0; j < num_output; ++j)
890 weightsp.ptr<float>(i)[j]=j+1;
894 lpr.blobs.push_back(weightsp);
895 net.addLayerToPrev(lpr.name, lpr.type, lpr);
897 int shape[] = {1, num_input, 16, 16};
898 Mat in_blob(4, &shape[0], CV_32FC1, Scalar(1));
900 net.setPreferableBackend(DNN_BACKEND_OPENCV);
901 net.setInput(in_blob);
902 Mat out = net.forward();
905 std::vector<int> outShape(4);
907 outShape[1] = num_output; // outChannels
908 outShape[2] = 14; // height
909 outShape[3] = 14; // width
910 Mat target(outShape, CV_32F, Scalar(1));
911 for (int i = 0; i < outShape[0]; ++i)
913 for (int j = 0; j < outShape[1]; ++j)
915 for (int k = 0; k < outShape[2]; ++k)
917 for (int l = 0; l < outShape[3]; ++l)
919 target.ptr<float>(i, j, k)[l]=(-9*kernel_depth*(j+1)+j+1)*(j+1);
925 normAssert(out, target);
927 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_DWconv_Prelu, Combine(Values(3, 6), Values(3, 6)));
929 #ifdef HAVE_INF_ENGINE
930 // Using Intel's Model Optimizer generate .xml and .bin files:
931 // ./ModelOptimizer -w /path/to/caffemodel -d /path/to/prototxt \
932 // -p FP32 -i -b ${batch_size} -o /path/to/output/folder
933 typedef testing::TestWithParam<Target> Layer_Test_Convolution_DLDT;
934 TEST_P(Layer_Test_Convolution_DLDT, Accuracy)
936 Target targetId = GetParam();
938 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
939 Net netDefault = readNet(_tf("layer_convolution.caffemodel"), _tf("layer_convolution.prototxt"));
940 Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
942 Mat inp = blobFromNPY(_tf("blob.npy"));
944 netDefault.setInput(inp);
945 netDefault.setPreferableBackend(DNN_BACKEND_OPENCV);
946 Mat outDefault = netDefault.forward();
949 net.setPreferableTarget(targetId);
951 Mat out = net.forward();
953 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
954 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
955 normAssert(outDefault, out, "", l1, lInf);
957 std::vector<int> outLayers = net.getUnconnectedOutLayers();
958 ASSERT_EQ(net.getLayer(outLayers[0])->name, "output");
959 ASSERT_EQ(net.getLayer(outLayers[0])->type, "Convolution");
962 TEST_P(Layer_Test_Convolution_DLDT, setInput_uint8)
964 Target targetId = GetParam();
965 Mat inp = blobFromNPY(_tf("blob.npy"));
967 Mat inputs[] = {Mat(inp.dims, inp.size, CV_8U), Mat()};
968 randu(inputs[0], 0, 255);
969 inputs[0].convertTo(inputs[1], CV_32F);
971 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
974 for (int i = 0; i < 2; ++i)
976 Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
977 net.setPreferableTarget(targetId);
978 net.setInput(inputs[i]);
979 outs[i] = net.forward();
980 ASSERT_EQ(outs[i].type(), CV_32F);
982 if (targetId != DNN_TARGET_MYRIAD)
983 normAssert(outs[0], outs[1]);
986 TEST_P(Layer_Test_Convolution_DLDT, multithreading)
988 Target targetId = GetParam();
989 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
990 std::string xmlPath = _tf("layer_convolution" + suffix + ".xml");
991 std::string binPath = _tf("layer_convolution" + suffix + ".bin");
992 Net firstNet = readNet(xmlPath, binPath);
993 Net secondNet = readNet(xmlPath, binPath);
994 Mat inp = blobFromNPY(_tf("blob.npy"));
996 firstNet.setInput(inp);
997 secondNet.setInput(inp);
998 firstNet.setPreferableTarget(targetId);
999 secondNet.setPreferableTarget(targetId);
1002 std::thread t1([&]{out1 = firstNet.forward();});
1003 std::thread t2([&]{out2 = secondNet.forward();});
1008 Mat ref = blobFromNPY(_tf("layer_convolution.npy"));
1009 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
1010 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
1011 normAssert(out1, ref, "first thread", l1, lInf);
1012 normAssert(out2, ref, "second thread", l1, lInf);
1015 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_Convolution_DLDT,
1016 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)));
1018 // 1. Create a .prototxt file with the following network:
1020 // type: "Input" name: "data" top: "data"
1021 // input_param { shape { dim: 1 dim: 2 dim: 3 } }
1024 // type: "Input" name: "second_input" top: "second_input"
1025 // input_param { shape { dim: 1 dim: 2 dim: 3 } }
1028 // type: "Eltwise" name: "output" top: "output"
1029 // bottom: "data" bottom: "second_input"
1030 // eltwise_param { operation: SUM }
1033 // 2. Create a .caffemodel file using Caffe:
1036 // net = caffe.Net('/path/to/prototxt', caffe.TEST)
1037 // net.save('/path/to/caffemodel')
1039 // 3. Convert using ModelOptimizer.
1040 typedef testing::TestWithParam<tuple<int, int, Target, std::vector<int> > > Test_DLDT_two_inputs_3dim;
1041 TEST_P(Test_DLDT_two_inputs_3dim, as_IR)
1043 int firstInpType = get<0>(GetParam());
1044 int secondInpType = get<1>(GetParam());
1045 Target targetId = get<2>(GetParam());
1047 std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1048 Net net = readNet(_tf("net_two_inputs" + suffix + ".xml"), _tf("net_two_inputs.bin"));
1049 std::vector<int> inpSize = get<3>(GetParam());
1050 Mat firstInp(3, inpSize.data(), firstInpType);
1051 Mat secondInp(3, inpSize.data(), secondInpType);
1052 randu(firstInp, 0, 255);
1053 randu(secondInp, 0, 255);
1055 net.setInput(firstInp, "data");
1056 net.setInput(secondInp, "second_input");
1057 net.setPreferableTarget(targetId);
1059 double l1 = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1060 (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.06 : 0.0;
1061 double lInf = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1062 (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.23 : 0.0;
1064 Mat out = net.forward();
1067 cv::add(firstInp, secondInp, ref, Mat(), CV_32F);
1068 normAssert(out, ref, "", l1, lInf);
1071 std::vector< std::vector<int> > list_sizes{ {1, 2, 3}, {3, 2, 1}, {5, 5, 5}, {13, 7, 11} };
1073 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs_3dim, Combine(
1074 Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1075 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)),
1076 testing::ValuesIn(list_sizes)
1079 typedef testing::TestWithParam<tuple<int, int, Target> > Test_DLDT_two_inputs;
1080 TEST_P(Test_DLDT_two_inputs, as_backend)
1082 static const float kScale = 0.5f;
1083 static const float kScaleInv = 1.0f / kScale;
1085 Target targetId = get<2>(GetParam());
1089 lp.type = "Eltwise";
1090 lp.name = "testLayer";
1091 lp.set("operation", "sum");
1092 int eltwiseId = net.addLayerToPrev(lp.name, lp.type, lp); // connect to a first input
1093 net.connect(0, 1, eltwiseId, 1); // connect to a second input
1095 int inpSize[] = {1, 2, 3, 4};
1096 Mat firstInp(4, &inpSize[0], get<0>(GetParam()));
1097 Mat secondInp(4, &inpSize[0], get<1>(GetParam()));
1098 randu(firstInp, 0, 255);
1099 randu(secondInp, 0, 255);
1101 net.setInputsNames({"data", "second_input"});
1102 net.setInput(firstInp, "data", kScale);
1103 net.setInput(secondInp, "second_input", kScaleInv);
1104 net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1105 net.setPreferableTarget(targetId);
1106 Mat out = net.forward();
1109 addWeighted(firstInp, kScale, secondInp, kScaleInv, 0, ref, CV_32F);
1110 // Output values are in range [0, 637.5].
1111 double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.06 : 1e-6;
1112 double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.3 : 1e-5;
1113 normAssert(out, ref, "", l1, lInf);
1116 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs, Combine(
1117 Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1118 testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE))
1121 class UnsupportedLayer : public Layer
1124 UnsupportedLayer(const LayerParams ¶ms) {}
1126 static Ptr<Layer> create(const LayerParams& params)
1128 return Ptr<Layer>(new UnsupportedLayer(params));
1131 virtual bool supportBackend(int backendId) CV_OVERRIDE
1133 return backendId == DNN_BACKEND_OPENCV;
1136 virtual void forward(cv::InputArrayOfArrays inputs, cv::OutputArrayOfArrays outputs, cv::OutputArrayOfArrays internals) CV_OVERRIDE {}
1139 TEST(Test_DLDT, fused_output)
1141 static const int kNumChannels = 3;
1142 CV_DNN_REGISTER_LAYER_CLASS(Unsupported, UnsupportedLayer);
1146 lp.set("kernel_size", 1);
1147 lp.set("num_output", 3);
1148 lp.set("bias_term", false);
1149 lp.type = "Convolution";
1150 lp.name = "testConv";
1151 lp.blobs.push_back(Mat({kNumChannels, 1, 1, 1}, CV_32F, Scalar(1)));
1152 net.addLayerToPrev(lp.name, lp.type, lp);
1156 lp.set("bias_term", false);
1158 lp.name = "testScale";
1159 lp.blobs.push_back(Mat({kNumChannels}, CV_32F, Scalar(1)));
1160 net.addLayerToPrev(lp.name, lp.type, lp);
1164 net.addLayerToPrev("unsupported_layer", "Unsupported", lp);
1166 net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1167 net.setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1168 ASSERT_NO_THROW(net.forward());
1169 LayerFactory::unregisterLayer("Unsupported");
1172 TEST(Test_DLDT, multiple_networks)
1175 for (int i = 0; i < 2; ++i)
1177 nets[i].setInputsNames(std::vector<String>(1, format("input_%d", i)));
1180 lp.set("kernel_size", 1);
1181 lp.set("num_output", 1);
1182 lp.set("bias_term", false);
1183 lp.type = "Convolution";
1184 lp.name = format("testConv_%d", i);
1185 lp.blobs.push_back(Mat({1, 1, 1, 1}, CV_32F, Scalar(1 + i)));
1186 nets[i].addLayerToPrev(lp.name, lp.type, lp);
1187 nets[i].setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1188 nets[i].setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1190 Mat out_1 = nets[0].forward();
1191 Mat out_2 = nets[1].forward();
1192 // After the second model is initialized we try to receive an output from the first network again.
1193 out_1 = nets[0].forward();
1194 normAssert(2 * out_1, out_2);
1196 #endif // HAVE_INF_ENGINE
1198 // Test a custom layer.
1199 class CustomInterpLayer CV_FINAL : public Layer
1202 CustomInterpLayer(const LayerParams ¶ms) : Layer(params)
1204 zoomFactor = params.get<int>("zoom_factor", 0);
1205 outWidth = params.get<int>("width", 0);
1206 outHeight = params.get<int>("height", 0);
1209 static Ptr<Layer> create(LayerParams& params)
1211 return Ptr<Layer>(new CustomInterpLayer(params));
1214 virtual bool getMemoryShapes(const std::vector<std::vector<int> > &inputs,
1215 const int requiredOutputs,
1216 std::vector<std::vector<int> > &outputs,
1217 std::vector<std::vector<int> > &internals) const CV_OVERRIDE
1219 const int batchSize = inputs[0][0];
1220 const int numChannels = inputs[0][1];
1221 const int inpHeight = inputs[0][2];
1222 const int inpWidth = inputs[0][3];
1224 std::vector<int> outShape(4);
1225 outShape[0] = batchSize;
1226 outShape[1] = numChannels;
1227 outShape[2] = outHeight != 0 ? outHeight : (inpHeight + (inpHeight - 1) * (zoomFactor - 1));
1228 outShape[3] = outWidth != 0 ? outWidth : (inpWidth + (inpWidth - 1) * (zoomFactor - 1));
1229 outputs.assign(1, outShape);
1233 virtual void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
1235 std::vector<Mat> outputs;
1236 outputs_arr.getMatVector(outputs);
1238 if (!outWidth && !outHeight)
1240 outHeight = outputs[0].size[2];
1241 outWidth = outputs[0].size[3];
1245 // Implementation of this custom layer is based on https://github.com/cdmh/deeplab-public/blob/master/src/caffe/layers/interp_layer.cpp
1246 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1248 CV_TRACE_FUNCTION();
1249 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1251 if (inputs_arr.depth() == CV_16S)
1253 forward_fallback(inputs_arr, outputs_arr, internals_arr);
1257 std::vector<Mat> inputs, outputs;
1258 inputs_arr.getMatVector(inputs);
1259 outputs_arr.getMatVector(outputs);
1261 Mat& inp = inputs[0];
1262 Mat& out = outputs[0];
1263 const float* inpData = (float*)inp.data;
1264 float* outData = (float*)out.data;
1266 const int batchSize = inp.size[0];
1267 const int numChannels = inp.size[1];
1268 const int inpHeight = inp.size[2];
1269 const int inpWidth = inp.size[3];
1271 const float rheight = (outHeight > 1) ? static_cast<float>(inpHeight - 1) / (outHeight - 1) : 0.f;
1272 const float rwidth = (outWidth > 1) ? static_cast<float>(inpWidth - 1) / (outWidth - 1) : 0.f;
1273 for (int h2 = 0; h2 < outHeight; ++h2)
1275 const float h1r = rheight * h2;
1277 const int h1p = (h1 < inpHeight - 1) ? 1 : 0;
1278 const float h1lambda = h1r - h1;
1279 const float h0lambda = 1.f - h1lambda;
1280 for (int w2 = 0; w2 < outWidth; ++w2)
1282 const float w1r = rwidth * w2;
1284 const int w1p = (w1 < inpWidth - 1) ? 1 : 0;
1285 const float w1lambda = w1r - w1;
1286 const float w0lambda = 1.f - w1lambda;
1287 const float* pos1 = inpData + h1 * inpWidth + w1;
1288 float* pos2 = outData + h2 * outWidth + w2;
1289 for (int c = 0; c < batchSize * numChannels; ++c)
1292 h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[w1p]) +
1293 h1lambda * (w0lambda * pos1[h1p * inpWidth] + w1lambda * pos1[h1p * inpWidth + w1p]);
1294 pos1 += inpWidth * inpHeight;
1295 pos2 += outWidth * outHeight;
1302 int outWidth, outHeight, zoomFactor;
1305 #ifndef OPENCV_DNN_EXTERNAL_PROTOBUF
1306 TEST_P(Test_Caffe_layers, Interp)
1308 TEST_P(Test_Caffe_layers, DISABLED_Interp) // requires patched protobuf (available in OpenCV source tree only)
1311 if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
1312 applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
1314 // Test a custom layer.
1315 CV_DNN_REGISTER_LAYER_CLASS(Interp, CustomInterpLayer);
1318 testLayerUsingCaffeModels("layer_interp", false, false);
1322 LayerFactory::unregisterLayer("Interp");
1325 LayerFactory::unregisterLayer("Interp");
1327 // Test an implemented layer.
1328 testLayerUsingCaffeModels("layer_interp", false, false);
1331 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_Caffe_layers, dnnBackendsAndTargets());
1333 TEST(Layer_Test_PoolingIndices, Accuracy)
1338 lp.set("pool", "max");
1339 lp.set("kernel_w", 2);
1340 lp.set("kernel_h", 2);
1341 lp.set("stride_w", 2);
1342 lp.set("stride_h", 2);
1345 lp.name = "testLayer.name"; // This test also checks that OpenCV lets use names with dots.
1346 lp.type = "Pooling";
1347 net.addLayerToPrev(lp.name, lp.type, lp);
1349 Mat inp(10, 10, CV_8U);
1352 Mat maxValues(5, 5, CV_32F, Scalar(-1)), indices(5, 5, CV_32F, Scalar(-1));
1353 for (int y = 0; y < 10; ++y)
1356 for (int x = 0; x < 10; ++x)
1359 uint8_t val = inp.at<uint8_t>(y, x);
1360 if ((float)inp.at<uint8_t>(y, x) > maxValues.at<float>(dstY, dstX))
1362 maxValues.at<float>(dstY, dstX) = val;
1363 indices.at<float>(dstY, dstX) = y * 10 + x;
1367 net.setPreferableBackend(DNN_BACKEND_OPENCV);
1368 net.setInput(blobFromImage(inp));
1370 std::vector<Mat> outputs;
1371 net.forward(outputs, lp.name);
1372 normAssert(maxValues, outputs[0].reshape(1, 5));
1373 normAssert(indices, outputs[1].reshape(1, 5));
1376 typedef testing::TestWithParam<tuple<Vec4i, int, tuple<Backend, Target> > > Layer_Test_ShuffleChannel;
1377 TEST_P(Layer_Test_ShuffleChannel, Accuracy)
1379 Vec4i inpShapeVec = get<0>(GetParam());
1380 int group = get<1>(GetParam());
1381 ASSERT_EQ(inpShapeVec[1] % group, 0);
1382 const int groupSize = inpShapeVec[1] / group;
1383 int backendId = get<0>(get<2>(GetParam()));
1384 int targetId = get<1>(get<2>(GetParam()));
1388 lp.set("group", group);
1389 lp.type = "ShuffleChannel";
1390 lp.name = "testLayer";
1391 net.addLayerToPrev(lp.name, lp.type, lp);
1393 const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
1394 Mat inp(4, inpShape, CV_32F);
1398 net.setPreferableBackend(backendId);
1399 net.setPreferableTarget(targetId);
1400 Mat out = net.forward();
1402 double l1 = (targetId == DNN_TARGET_OPENCL_FP16) ? 5e-2 : 1e-5;
1403 double lInf = (targetId == DNN_TARGET_OPENCL_FP16) ? 7e-2 : 1e-4;
1404 for (int n = 0; n < inpShapeVec[0]; ++n)
1406 for (int c = 0; c < inpShapeVec[1]; ++c)
1408 Mat outChannel = getPlane(out, n, c);
1409 Mat inpChannel = getPlane(inp, n, groupSize * (c % group) + c / group);
1410 normAssert(outChannel, inpChannel, "", l1, lInf);
1414 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_ShuffleChannel, Combine(
1415 /*input shape*/ Values(Vec4i(1, 6, 5, 7), Vec4i(3, 12, 1, 4)),
1416 /*group*/ Values(1, 2, 3, 6), dnnBackendsAndTargets(/*with IE*/ false)
1419 // Check if relu is not fused to convolution if we requested it's output
1420 TEST(Layer_Test_Convolution, relu_fusion)
1425 lp.set("kernel_size", 1);
1426 lp.set("num_output", 1);
1427 lp.set("bias_term", false);
1428 lp.type = "Convolution";
1429 lp.name = "testConv";
1431 int weightsShape[] = {1, 1, 1, 1};
1432 Mat weights(4, &weightsShape[0], CV_32F, Scalar(1));
1433 lp.blobs.push_back(weights);
1434 net.addLayerToPrev(lp.name, lp.type, lp);
1439 lp.name = "testReLU";
1440 net.addLayerToPrev(lp.name, lp.type, lp);
1442 int sz[] = {1, 1, 2, 3};
1443 Mat input(4, &sz[0], CV_32F);
1444 randu(input, -1.0, -0.1);
1445 net.setInput(input);
1446 net.setPreferableBackend(DNN_BACKEND_OPENCV);
1447 Mat output = net.forward("testConv");
1448 normAssert(input, output);