test_caffe_importer.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  14. // Third party copyrights are property of their respective owners.
  15. //
  16. // Redistribution and use in source and binary forms, with or without modification,
  17. // are permitted provided that the following conditions are met:
  18. //
  19. // * Redistribution's of source code must retain the above copyright notice,
  20. // this list of conditions and the following disclaimer.
  21. //
  22. // * Redistribution's in binary form must reproduce the above copyright notice,
  23. // this list of conditions and the following disclaimer in the documentation
  24. // and/or other materials provided with the distribution.
  25. //
  26. // * The name of the copyright holders may not be used to endorse or promote products
  27. // derived from this software without specific prior written permission.
  28. //
  29. // This software is provided by the copyright holders and contributors "as is" and
  30. // any express or implied warranties, including, but not limited to, the implied
  31. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  32. // In no event shall the Intel Corporation or contributors be liable for any direct,
  33. // indirect, incidental, special, exemplary, or consequential damages
  34. // (including, but not limited to, procurement of substitute goods or services;
  35. // loss of use, data, or profits; or business interruption) however caused
  36. // and on any theory of liability, whether in contract, strict liability,
  37. // or tort (including negligence or otherwise) arising in any way out of
  38. // the use of this software, even if advised of the possibility of such damage.
  39. //
  40. //M*/
  41. #include "test_precomp.hpp"
  42. #include "npy_blob.hpp"
  43. #include <opencv2/dnn/shape_utils.hpp>
  44. namespace opencv_test { namespace {
  45. template<typename TString>
  46. static std::string _tf(TString filename)
  47. {
  48. return findDataFile(std::string("dnn/") + filename);
  49. }
  50. class Test_Caffe_nets : public DNNTestLayer
  51. {
  52. public:
  53. void testFaster(const std::string& proto, const std::string& model, const Mat& ref,
  54. double scoreDiff = 0.0, double iouDiff = 0.0)
  55. {
  56. checkBackend();
  57. Net net = readNetFromCaffe(findDataFile("dnn/" + proto),
  58. findDataFile("dnn/" + model, false));
  59. net.setPreferableBackend(backend);
  60. net.setPreferableTarget(target);
  61. Mat img = imread(findDataFile("dnn/dog416.png"));
  62. resize(img, img, Size(800, 600));
  63. Mat blob = blobFromImage(img, 1.0, Size(), Scalar(102.9801, 115.9465, 122.7717), false, false);
  64. Mat imInfo = (Mat_<float>(1, 3) << img.rows, img.cols, 1.6f);
  65. net.setInput(blob, "data");
  66. net.setInput(imInfo, "im_info");
  67. // Output has shape 1x1xNx7 where N - number of detections.
  68. // An every detection is a vector of values [id, classId, confidence, left, top, right, bottom]
  69. Mat out = net.forward();
  70. scoreDiff = scoreDiff ? scoreDiff : default_l1;
  71. iouDiff = iouDiff ? iouDiff : default_lInf;
  72. normAssertDetections(ref, out, ("model name: " + model).c_str(), 0.8, scoreDiff, iouDiff);
  73. }
  74. };
  75. TEST(Test_Caffe, memory_read)
  76. {
  77. const string proto = findDataFile("dnn/bvlc_googlenet.prototxt");
  78. const string model = findDataFile("dnn/bvlc_googlenet.caffemodel", false);
  79. std::vector<char> dataProto;
  80. readFileContent(proto, dataProto);
  81. std::vector<char> dataModel;
  82. readFileContent(model, dataModel);
  83. Net net = readNetFromCaffe(dataProto.data(), dataProto.size());
  84. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  85. ASSERT_FALSE(net.empty());
  86. Net net2 = readNetFromCaffe(dataProto.data(), dataProto.size(),
  87. dataModel.data(), dataModel.size());
  88. ASSERT_FALSE(net2.empty());
  89. }
  90. TEST(Test_Caffe, read_gtsrb)
  91. {
  92. Net net = readNetFromCaffe(_tf("gtsrb.prototxt"));
  93. ASSERT_FALSE(net.empty());
  94. }
  95. TEST(Test_Caffe, read_googlenet)
  96. {
  97. Net net = readNetFromCaffe(_tf("bvlc_googlenet.prototxt"));
  98. ASSERT_FALSE(net.empty());
  99. }
  100. TEST_P(Test_Caffe_nets, Axpy)
  101. {
  102. #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LT(2021040000)
  103. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
  104. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NN_BUILDER);
  105. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
  106. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NGRAPH);
  107. #endif
  108. String proto = _tf("axpy.prototxt");
  109. Net net = readNetFromCaffe(proto);
  110. checkBackend();
  111. net.setPreferableBackend(backend);
  112. net.setPreferableTarget(target);
  113. int size[] = {1, 2, 3, 4};
  114. int scale_size[] = {1, 2, 1, 1};
  115. Mat scale(4, &scale_size[0], CV_32F);
  116. Mat shift(4, &size[0], CV_32F);
  117. Mat inp(4, &size[0], CV_32F);
  118. randu(scale, -1.0f, 1.0f);
  119. randu(shift, -1.0f, 1.0f);
  120. randu(inp, -1.0f, 1.0f);
  121. net.setInput(scale, "scale");
  122. net.setInput(shift, "shift");
  123. net.setInput(inp, "data");
  124. Mat out = net.forward();
  125. Mat ref(4, &size[0], inp.type());
  126. for (int i = 0; i < inp.size[1]; i++) {
  127. for (int h = 0; h < inp.size[2]; h++) {
  128. for (int w = 0; w < inp.size[3]; w++) {
  129. int idx[] = {0, i, h, w};
  130. int scale_idx[] = {0, i, 0, 0};
  131. ref.at<float>(idx) = inp.at<float>(idx) * scale.at<float>(scale_idx) +
  132. shift.at<float>(idx);
  133. }
  134. }
  135. }
  136. float l1 = 1e-5, lInf = 1e-4;
  137. if (target == DNN_TARGET_OPENCL_FP16)
  138. {
  139. l1 = 2e-4;
  140. lInf = 1e-3;
  141. }
  142. if (target == DNN_TARGET_MYRIAD)
  143. {
  144. l1 = 0.001;
  145. lInf = 0.001;
  146. }
  147. if(target == DNN_TARGET_CUDA_FP16)
  148. {
  149. l1 = 0.0002;
  150. lInf = 0.0007;
  151. }
  152. normAssert(ref, out, "", l1, lInf);
  153. }
  154. typedef testing::TestWithParam<tuple<bool, Target> > Reproducibility_AlexNet;
  155. TEST_P(Reproducibility_AlexNet, Accuracy)
  156. {
  157. Target targetId = get<1>(GetParam());
  158. #if defined(OPENCV_32BIT_CONFIGURATION) && defined(HAVE_OPENCL)
  159. applyTestTag(CV_TEST_TAG_MEMORY_2GB);
  160. #else
  161. applyTestTag(targetId == DNN_TARGET_CPU ? CV_TEST_TAG_MEMORY_512MB : CV_TEST_TAG_MEMORY_1GB);
  162. #endif
  163. ASSERT_TRUE(ocl::useOpenCL() || targetId == DNN_TARGET_CPU);
  164. bool readFromMemory = get<0>(GetParam());
  165. Net net;
  166. {
  167. const string proto = findDataFile("dnn/bvlc_alexnet.prototxt");
  168. const string model = findDataFile("dnn/bvlc_alexnet.caffemodel", false);
  169. if (readFromMemory)
  170. {
  171. std::vector<char> dataProto;
  172. readFileContent(proto, dataProto);
  173. std::vector<char> dataModel;
  174. readFileContent(model, dataModel);
  175. net = readNetFromCaffe(dataProto.data(), dataProto.size(),
  176. dataModel.data(), dataModel.size());
  177. }
  178. else
  179. net = readNetFromCaffe(proto, model);
  180. ASSERT_FALSE(net.empty());
  181. }
  182. // Test input layer size
  183. std::vector<MatShape> inLayerShapes;
  184. std::vector<MatShape> outLayerShapes;
  185. net.getLayerShapes(MatShape(), 0, inLayerShapes, outLayerShapes);
  186. ASSERT_FALSE(inLayerShapes.empty());
  187. ASSERT_EQ(inLayerShapes[0].size(), 4);
  188. ASSERT_EQ(inLayerShapes[0][0], 1);
  189. ASSERT_EQ(inLayerShapes[0][1], 3);
  190. ASSERT_EQ(inLayerShapes[0][2], 227);
  191. ASSERT_EQ(inLayerShapes[0][3], 227);
  192. const float l1 = 1e-5;
  193. const float lInf = (targetId == DNN_TARGET_OPENCL_FP16) ? 4e-3 : 1e-4;
  194. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  195. net.setPreferableTarget(targetId);
  196. Mat sample = imread(_tf("grace_hopper_227.png"));
  197. ASSERT_TRUE(!sample.empty());
  198. net.setInput(blobFromImage(sample, 1.0f, Size(227, 227), Scalar(), false), "data");
  199. Mat out = net.forward("prob");
  200. Mat ref = blobFromNPY(_tf("caffe_alexnet_prob.npy"));
  201. normAssert(ref, out, "", l1, lInf);
  202. }
  203. INSTANTIATE_TEST_CASE_P(/**/, Reproducibility_AlexNet, Combine(testing::Bool(),
  204. testing::ValuesIn(getAvailableTargets(DNN_BACKEND_OPENCV))));
  205. TEST(Reproducibility_FCN, Accuracy)
  206. {
  207. applyTestTag(CV_TEST_TAG_LONG, CV_TEST_TAG_DEBUG_VERYLONG, CV_TEST_TAG_MEMORY_2GB);
  208. Net net;
  209. {
  210. const string proto = findDataFile("dnn/fcn8s-heavy-pascal.prototxt");
  211. const string model = findDataFile("dnn/fcn8s-heavy-pascal.caffemodel", false);
  212. net = readNetFromCaffe(proto, model);
  213. ASSERT_FALSE(net.empty());
  214. }
  215. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  216. Mat sample = imread(_tf("street.png"));
  217. ASSERT_TRUE(!sample.empty());
  218. std::vector<int> layerIds;
  219. std::vector<size_t> weights, blobs;
  220. net.getMemoryConsumption(shape(1,3,227,227), layerIds, weights, blobs);
  221. net.setInput(blobFromImage(sample, 1.0f, Size(500, 500), Scalar(), false), "data");
  222. Mat out = net.forward("score");
  223. Mat refData = imread(_tf("caffe_fcn8s_prob.png"), IMREAD_ANYDEPTH);
  224. int shape[] = {1, 21, 500, 500};
  225. Mat ref(4, shape, CV_32FC1, refData.data);
  226. normAssert(ref, out);
  227. }
  228. TEST(Reproducibility_SSD, Accuracy)
  229. {
  230. applyTestTag(CV_TEST_TAG_MEMORY_512MB, CV_TEST_TAG_DEBUG_LONG);
  231. Net net;
  232. {
  233. const string proto = findDataFile("dnn/ssd_vgg16.prototxt");
  234. const string model = findDataFile("dnn/VGG_ILSVRC2016_SSD_300x300_iter_440000.caffemodel", false);
  235. net = readNetFromCaffe(proto, model);
  236. ASSERT_FALSE(net.empty());
  237. }
  238. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  239. Mat sample = imread(_tf("street.png"));
  240. ASSERT_TRUE(!sample.empty());
  241. if (sample.channels() == 4)
  242. cvtColor(sample, sample, COLOR_BGRA2BGR);
  243. Mat in_blob = blobFromImage(sample, 1.0f, Size(300, 300), Scalar(), false);
  244. net.setInput(in_blob, "data");
  245. Mat out = net.forward("detection_out");
  246. Mat ref = blobFromNPY(_tf("ssd_out.npy"));
  247. normAssertDetections(ref, out, "", FLT_MIN);
  248. }
  249. typedef testing::TestWithParam<tuple<Backend, Target> > Reproducibility_MobileNet_SSD;
  250. TEST_P(Reproducibility_MobileNet_SSD, Accuracy)
  251. {
  252. const string proto = findDataFile("dnn/MobileNetSSD_deploy.prototxt", false);
  253. const string model = findDataFile("dnn/MobileNetSSD_deploy.caffemodel", false);
  254. Net net = readNetFromCaffe(proto, model);
  255. int backendId = get<0>(GetParam());
  256. int targetId = get<1>(GetParam());
  257. net.setPreferableBackend(backendId);
  258. net.setPreferableTarget(targetId);
  259. Mat sample = imread(_tf("street.png"));
  260. Mat inp = blobFromImage(sample, 1.0f / 127.5, Size(300, 300), Scalar(127.5, 127.5, 127.5), false);
  261. net.setInput(inp);
  262. Mat out = net.forward().clone();
  263. ASSERT_EQ(out.size[2], 100);
  264. float scores_diff = 1e-5, boxes_iou_diff = 1e-4;
  265. if (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD)
  266. {
  267. scores_diff = 1.5e-2;
  268. boxes_iou_diff = 6.3e-2;
  269. }
  270. else if (targetId == DNN_TARGET_CUDA_FP16)
  271. {
  272. scores_diff = 0.015;
  273. boxes_iou_diff = 0.07;
  274. }
  275. Mat ref = blobFromNPY(_tf("mobilenet_ssd_caffe_out.npy"));
  276. normAssertDetections(ref, out, "", FLT_MIN, scores_diff, boxes_iou_diff);
  277. // Check that detections aren't preserved.
  278. inp.setTo(0.0f);
  279. net.setInput(inp);
  280. Mat zerosOut = net.forward();
  281. zerosOut = zerosOut.reshape(1, zerosOut.total() / 7);
  282. const int numDetections = zerosOut.rows;
  283. // TODO: fix it
  284. if (targetId != DNN_TARGET_MYRIAD ||
  285. getInferenceEngineVPUType() != CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X)
  286. {
  287. ASSERT_NE(numDetections, 0);
  288. for (int i = 0; i < numDetections; ++i)
  289. {
  290. float confidence = zerosOut.ptr<float>(i)[2];
  291. ASSERT_EQ(confidence, 0);
  292. }
  293. }
  294. // There is something wrong with Reshape layer in Myriad plugin.
  295. if (backendId == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019
  296. || backendId == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH
  297. )
  298. {
  299. if (targetId == DNN_TARGET_MYRIAD || targetId == DNN_TARGET_OPENCL_FP16)
  300. return;
  301. }
  302. // Check batching mode.
  303. inp = blobFromImages(std::vector<Mat>(2, sample), 1.0f / 127.5, Size(300, 300), Scalar(127.5, 127.5, 127.5), false);
  304. net.setInput(inp);
  305. Mat outBatch = net.forward();
  306. // Output blob has a shape 1x1x2Nx7 where N is a number of detection for
  307. // a single sample in batch. The first numbers of detection vectors are batch id.
  308. // For Inference Engine backend there is -1 delimiter which points the end of detections.
  309. const int numRealDetections = ref.size[2];
  310. EXPECT_EQ(outBatch.size[2], 2 * numDetections);
  311. out = out.reshape(1, numDetections).rowRange(0, numRealDetections);
  312. outBatch = outBatch.reshape(1, 2 * numDetections);
  313. for (int i = 0; i < 2; ++i)
  314. {
  315. Mat pred = outBatch.rowRange(i * numRealDetections, (i + 1) * numRealDetections);
  316. EXPECT_EQ(countNonZero(pred.col(0) != i), 0);
  317. normAssert(pred.colRange(1, 7), out.colRange(1, 7));
  318. }
  319. }
  320. INSTANTIATE_TEST_CASE_P(/**/, Reproducibility_MobileNet_SSD, dnnBackendsAndTargets());
  321. typedef testing::TestWithParam<Target> Reproducibility_ResNet50;
  322. TEST_P(Reproducibility_ResNet50, Accuracy)
  323. {
  324. Target targetId = GetParam();
  325. applyTestTag(targetId == DNN_TARGET_CPU ? CV_TEST_TAG_MEMORY_512MB : CV_TEST_TAG_MEMORY_1GB);
  326. ASSERT_TRUE(ocl::useOpenCL() || targetId == DNN_TARGET_CPU);
  327. Net net = readNetFromCaffe(findDataFile("dnn/ResNet-50-deploy.prototxt"),
  328. findDataFile("dnn/ResNet-50-model.caffemodel", false));
  329. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  330. net.setPreferableTarget(targetId);
  331. float l1 = (targetId == DNN_TARGET_OPENCL_FP16) ? 3e-5 : 1e-5;
  332. float lInf = (targetId == DNN_TARGET_OPENCL_FP16) ? 6e-3 : 1e-4;
  333. Mat input = blobFromImage(imread(_tf("googlenet_0.png")), 1.0f, Size(224,224), Scalar(), false);
  334. ASSERT_TRUE(!input.empty());
  335. net.setInput(input);
  336. Mat out = net.forward();
  337. Mat ref = blobFromNPY(_tf("resnet50_prob.npy"));
  338. normAssert(ref, out, "", l1, lInf);
  339. if (targetId == DNN_TARGET_OPENCL || targetId == DNN_TARGET_OPENCL_FP16)
  340. {
  341. UMat out_umat;
  342. net.forward(out_umat);
  343. normAssert(ref, out_umat, "out_umat", l1, lInf);
  344. std::vector<UMat> out_umats;
  345. net.forward(out_umats);
  346. normAssert(ref, out_umats[0], "out_umat_vector", l1, lInf);
  347. }
  348. }
  349. INSTANTIATE_TEST_CASE_P(/**/, Reproducibility_ResNet50,
  350. testing::ValuesIn(getAvailableTargets(DNN_BACKEND_OPENCV)));
  351. typedef testing::TestWithParam<Target> Reproducibility_SqueezeNet_v1_1;
  352. TEST_P(Reproducibility_SqueezeNet_v1_1, Accuracy)
  353. {
  354. int targetId = GetParam();
  355. if(targetId == DNN_TARGET_OPENCL_FP16)
  356. applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
  357. Net net = readNetFromCaffe(findDataFile("dnn/squeezenet_v1.1.prototxt"),
  358. findDataFile("dnn/squeezenet_v1.1.caffemodel", false));
  359. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  360. net.setPreferableTarget(targetId);
  361. Mat input = blobFromImage(imread(_tf("googlenet_0.png")), 1.0f, Size(227,227), Scalar(), false, true);
  362. ASSERT_TRUE(!input.empty());
  363. Mat out;
  364. if (targetId == DNN_TARGET_OPENCL)
  365. {
  366. // Firstly set a wrong input blob and run the model to receive a wrong output.
  367. // Then set a correct input blob to check CPU->GPU synchronization is working well.
  368. net.setInput(input * 2.0f);
  369. out = net.forward();
  370. }
  371. net.setInput(input);
  372. out = net.forward();
  373. Mat ref = blobFromNPY(_tf("squeezenet_v1.1_prob.npy"));
  374. normAssert(ref, out);
  375. }
  376. INSTANTIATE_TEST_CASE_P(/**/, Reproducibility_SqueezeNet_v1_1,
  377. testing::ValuesIn(getAvailableTargets(DNN_BACKEND_OPENCV)));
  378. TEST(Reproducibility_AlexNet_fp16, Accuracy)
  379. {
  380. applyTestTag(CV_TEST_TAG_MEMORY_512MB);
  381. const float l1 = 1e-5;
  382. const float lInf = 3e-3;
  383. const string proto = findDataFile("dnn/bvlc_alexnet.prototxt");
  384. const string model = findDataFile("dnn/bvlc_alexnet.caffemodel", false);
  385. shrinkCaffeModel(model, "bvlc_alexnet.caffemodel_fp16");
  386. Net net = readNetFromCaffe(proto, "bvlc_alexnet.caffemodel_fp16");
  387. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  388. Mat sample = imread(findDataFile("dnn/grace_hopper_227.png"));
  389. net.setInput(blobFromImage(sample, 1.0f, Size(227, 227), Scalar()));
  390. Mat out = net.forward();
  391. Mat ref = blobFromNPY(findDataFile("dnn/caffe_alexnet_prob.npy"));
  392. normAssert(ref, out, "", l1, lInf);
  393. }
  394. TEST(Reproducibility_GoogLeNet_fp16, Accuracy)
  395. {
  396. const float l1 = 1e-5;
  397. const float lInf = 3e-3;
  398. const string proto = findDataFile("dnn/bvlc_googlenet.prototxt");
  399. const string model = findDataFile("dnn/bvlc_googlenet.caffemodel", false);
  400. shrinkCaffeModel(model, "bvlc_googlenet.caffemodel_fp16");
  401. Net net = readNetFromCaffe(proto, "bvlc_googlenet.caffemodel_fp16");
  402. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  403. std::vector<Mat> inpMats;
  404. inpMats.push_back( imread(_tf("googlenet_0.png")) );
  405. inpMats.push_back( imread(_tf("googlenet_1.png")) );
  406. ASSERT_TRUE(!inpMats[0].empty() && !inpMats[1].empty());
  407. net.setInput(blobFromImages(inpMats, 1.0f, Size(), Scalar(), false), "data");
  408. Mat out = net.forward("prob");
  409. Mat ref = blobFromNPY(_tf("googlenet_prob.npy"));
  410. normAssert(out, ref, "", l1, lInf);
  411. }
  412. // https://github.com/richzhang/colorization
  413. TEST_P(Test_Caffe_nets, Colorization)
  414. {
  415. applyTestTag(target == DNN_TARGET_CPU ? CV_TEST_TAG_MEMORY_512MB : CV_TEST_TAG_MEMORY_1GB);
  416. checkBackend();
  417. Mat inp = blobFromNPY(_tf("colorization_inp.npy"));
  418. Mat ref = blobFromNPY(_tf("colorization_out.npy"));
  419. Mat kernel = blobFromNPY(_tf("colorization_pts_in_hull.npy"));
  420. const string proto = findDataFile("dnn/colorization_deploy_v2.prototxt", false);
  421. const string model = findDataFile("dnn/colorization_release_v2.caffemodel", false);
  422. Net net = readNetFromCaffe(proto, model);
  423. net.setPreferableBackend(backend);
  424. net.setPreferableTarget(target);
  425. net.getLayer(net.getLayerId("class8_ab"))->blobs.push_back(kernel);
  426. net.getLayer(net.getLayerId("conv8_313_rh"))->blobs.push_back(Mat(1, 313, CV_32F, 2.606));
  427. net.setInput(inp);
  428. Mat out = net.forward();
  429. // Reference output values are in range [-29.1, 69.5]
  430. double l1 = 4e-4, lInf = 3e-3;
  431. if (target == DNN_TARGET_OPENCL_FP16)
  432. {
  433. l1 = 0.25;
  434. lInf = 5.3;
  435. }
  436. else if (target == DNN_TARGET_MYRIAD)
  437. {
  438. l1 = (getInferenceEngineVPUType() == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X) ? 0.5 : 0.25;
  439. lInf = (getInferenceEngineVPUType() == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X) ? 11 : 5.3;
  440. }
  441. else if(target == DNN_TARGET_CUDA_FP16)
  442. {
  443. l1 = 0.21;
  444. lInf = 4.5;
  445. }
  446. #if defined(INF_ENGINE_RELEASE)
  447. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH && target == DNN_TARGET_OPENCL_FP16)
  448. {
  449. l1 = 0.3; lInf = 10;
  450. }
  451. #endif
  452. normAssert(out, ref, "", l1, lInf);
  453. expectNoFallbacksFromIE(net);
  454. }
  455. TEST_P(Test_Caffe_nets, DenseNet_121)
  456. {
  457. applyTestTag(CV_TEST_TAG_MEMORY_512MB);
  458. checkBackend();
  459. const string proto = findDataFile("dnn/DenseNet_121.prototxt", false);
  460. const string weights = findDataFile("dnn/DenseNet_121.caffemodel", false);
  461. Mat inp = imread(_tf("dog416.png"));
  462. Model model(proto, weights);
  463. model.setInputScale(1.0 / 255).setInputSwapRB(true).setInputCrop(true);
  464. std::vector<Mat> outs;
  465. Mat ref = blobFromNPY(_tf("densenet_121_output.npy"));
  466. model.setPreferableBackend(backend);
  467. model.setPreferableTarget(target);
  468. model.predict(inp, outs);
  469. // Reference is an array of 1000 values from a range [-6.16, 7.9]
  470. float l1 = default_l1, lInf = default_lInf;
  471. if (target == DNN_TARGET_OPENCL_FP16)
  472. {
  473. #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_GE(2019020000)
  474. l1 = 0.045; lInf = 0.21;
  475. #else
  476. l1 = 0.017; lInf = 0.0795;
  477. #endif
  478. }
  479. else if (target == DNN_TARGET_MYRIAD)
  480. {
  481. l1 = 0.11; lInf = 0.5;
  482. }
  483. else if (target == DNN_TARGET_CUDA_FP16)
  484. {
  485. l1 = 0.04; lInf = 0.2;
  486. }
  487. normAssert(outs[0], ref, "", l1, lInf);
  488. if (target != DNN_TARGET_MYRIAD || getInferenceEngineVPUType() != CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X)
  489. expectNoFallbacksFromIE(model.getNetwork_());
  490. }
  491. TEST(Test_Caffe, multiple_inputs)
  492. {
  493. const string proto = findDataFile("dnn/layers/net_input.prototxt");
  494. Net net = readNetFromCaffe(proto);
  495. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  496. Mat first_image(10, 11, CV_32FC3);
  497. Mat second_image(10, 11, CV_32FC3);
  498. randu(first_image, -1, 1);
  499. randu(second_image, -1, 1);
  500. first_image = blobFromImage(first_image);
  501. second_image = blobFromImage(second_image);
  502. Mat first_image_blue_green = slice(first_image, Range::all(), Range(0, 2), Range::all(), Range::all());
  503. Mat first_image_red = slice(first_image, Range::all(), Range(2, 3), Range::all(), Range::all());
  504. Mat second_image_blue_green = slice(second_image, Range::all(), Range(0, 2), Range::all(), Range::all());
  505. Mat second_image_red = slice(second_image, Range::all(), Range(2, 3), Range::all(), Range::all());
  506. net.setInput(first_image_blue_green, "old_style_input_blue_green");
  507. net.setInput(first_image_red, "different_name_for_red");
  508. net.setInput(second_image_blue_green, "input_layer_blue_green");
  509. net.setInput(second_image_red, "old_style_input_red");
  510. Mat out = net.forward();
  511. normAssert(out, first_image + second_image);
  512. }
  513. TEST(Test_Caffe, shared_weights)
  514. {
  515. const string proto = findDataFile("dnn/layers/shared_weights.prototxt");
  516. const string model = findDataFile("dnn/layers/shared_weights.caffemodel");
  517. Net net = readNetFromCaffe(proto, model);
  518. Mat input_1 = (Mat_<float>(2, 2) << 0., 2., 4., 6.);
  519. Mat input_2 = (Mat_<float>(2, 2) << 1., 3., 5., 7.);
  520. Mat blob_1 = blobFromImage(input_1);
  521. Mat blob_2 = blobFromImage(input_2);
  522. net.setInput(blob_1, "input_1");
  523. net.setInput(blob_2, "input_2");
  524. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  525. Mat sum = net.forward();
  526. EXPECT_EQ(sum.at<float>(0,0), 12.);
  527. EXPECT_EQ(sum.at<float>(0,1), 16.);
  528. }
  529. typedef testing::TestWithParam<tuple<std::string, Target> > opencv_face_detector;
  530. TEST_P(opencv_face_detector, Accuracy)
  531. {
  532. std::string proto = findDataFile("dnn/opencv_face_detector.prototxt");
  533. std::string model = findDataFile(get<0>(GetParam()), false);
  534. dnn::Target targetId = (dnn::Target)(int)get<1>(GetParam());
  535. Net net = readNetFromCaffe(proto, model);
  536. Mat img = imread(findDataFile("gpu/lbpcascade/er.png"));
  537. Mat blob = blobFromImage(img, 1.0, Size(), Scalar(104.0, 177.0, 123.0), false, false);
  538. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  539. net.setPreferableTarget(targetId);
  540. net.setInput(blob);
  541. // Output has shape 1x1xNx7 where N - number of detections.
  542. // An every detection is a vector of values [id, classId, confidence, left, top, right, bottom]
  543. Mat out = net.forward();
  544. Mat ref = (Mat_<float>(6, 7) << 0, 1, 0.99520785, 0.80997437, 0.16379407, 0.87996572, 0.26685631,
  545. 0, 1, 0.9934696, 0.2831718, 0.50738752, 0.345781, 0.5985168,
  546. 0, 1, 0.99096733, 0.13629119, 0.24892329, 0.19756334, 0.3310290,
  547. 0, 1, 0.98977017, 0.23901358, 0.09084064, 0.29902688, 0.1769477,
  548. 0, 1, 0.97203469, 0.67965847, 0.06876482, 0.73999709, 0.1513494,
  549. 0, 1, 0.95097077, 0.51901293, 0.45863652, 0.5777427, 0.5347801);
  550. normAssertDetections(ref, out, "", 0.5, 1e-5, 2e-4);
  551. }
  552. // False positives bug for large faces: https://github.com/opencv/opencv/issues/15106
  553. TEST_P(opencv_face_detector, issue_15106)
  554. {
  555. std::string proto = findDataFile("dnn/opencv_face_detector.prototxt");
  556. std::string model = findDataFile(get<0>(GetParam()), false);
  557. dnn::Target targetId = (dnn::Target)(int)get<1>(GetParam());
  558. Net net = readNetFromCaffe(proto, model);
  559. Mat img = imread(findDataFile("cv/shared/lena.png"));
  560. img = img.rowRange(img.rows / 4, 3 * img.rows / 4).colRange(img.cols / 4, 3 * img.cols / 4);
  561. Mat blob = blobFromImage(img, 1.0, Size(300, 300), Scalar(104.0, 177.0, 123.0), false, false);
  562. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  563. net.setPreferableTarget(targetId);
  564. net.setInput(blob);
  565. // Output has shape 1x1xNx7 where N - number of detections.
  566. // An every detection is a vector of values [id, classId, confidence, left, top, right, bottom]
  567. Mat out = net.forward();
  568. Mat ref = (Mat_<float>(1, 7) << 0, 1, 0.9149431, 0.30424616, 0.26964942, 0.88733053, 0.99815309);
  569. normAssertDetections(ref, out, "", 0.2, 6e-5, 1e-4);
  570. }
  571. INSTANTIATE_TEST_CASE_P(Test_Caffe, opencv_face_detector,
  572. Combine(
  573. Values("dnn/opencv_face_detector.caffemodel",
  574. "dnn/opencv_face_detector_fp16.caffemodel"),
  575. Values(DNN_TARGET_CPU, DNN_TARGET_OPENCL)
  576. )
  577. );
  578. TEST_P(Test_Caffe_nets, FasterRCNN_vgg16)
  579. {
  580. applyTestTag(
  581. #if defined(OPENCV_32BIT_CONFIGURATION) && defined(HAVE_OPENCL)
  582. CV_TEST_TAG_MEMORY_2GB, // utilizes ~1Gb, but huge blobs may not be allocated on 32-bit systems due memory fragmentation
  583. #else
  584. (target == DNN_TARGET_CPU ? CV_TEST_TAG_MEMORY_1GB : CV_TEST_TAG_MEMORY_2GB),
  585. #endif
  586. CV_TEST_TAG_LONG,
  587. CV_TEST_TAG_DEBUG_VERYLONG
  588. );
  589. #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LT(2021040000)
  590. if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 || backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
  591. applyTestTag(target == DNN_TARGET_OPENCL ? CV_TEST_TAG_DNN_SKIP_IE_OPENCL : CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16);
  592. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
  593. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION);
  594. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 && target == DNN_TARGET_MYRIAD)
  595. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
  596. #endif
  597. #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_EQ(2021040000)
  598. // IE exception: Ngraph operation Reshape with name rpn_cls_score_reshape has dynamic output shape on 0 port, but CPU plug-in supports only static shape
  599. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
  600. applyTestTag(target == DNN_TARGET_OPENCL ? CV_TEST_TAG_DNN_SKIP_IE_OPENCL : CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16,
  601. CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION
  602. );
  603. // Check 'backward_compatible_check || in_out_elements_equal' failed at core/src/op/reshape.cpp:390:
  604. // While validating node 'v1::Reshape bbox_pred_reshape (bbox_pred[0]:f32{1,84}, Constant_241202[0]:i64{4}) -> (f32{?,?,?,?})' with friendly_name 'bbox_pred_reshape':
  605. // Requested output shape {1,6300,4,1} is incompatible with input shape Shape{1, 84}
  606. if (target == DNN_TARGET_MYRIAD)
  607. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION);
  608. #endif
  609. static Mat ref = (Mat_<float>(3, 7) << 0, 2, 0.949398, 99.2454, 210.141, 601.205, 462.849,
  610. 0, 7, 0.997022, 481.841, 92.3218, 722.685, 175.953,
  611. 0, 12, 0.993028, 133.221, 189.377, 350.994, 563.166);
  612. testFaster("faster_rcnn_vgg16.prototxt", "VGG16_faster_rcnn_final.caffemodel", ref);
  613. }
  614. TEST_P(Test_Caffe_nets, FasterRCNN_zf)
  615. {
  616. applyTestTag(
  617. #if defined(OPENCV_32BIT_CONFIGURATION) && defined(HAVE_OPENCL)
  618. CV_TEST_TAG_MEMORY_2GB,
  619. #else
  620. (target == DNN_TARGET_CPU ? CV_TEST_TAG_MEMORY_512MB : CV_TEST_TAG_MEMORY_1GB),
  621. #endif
  622. CV_TEST_TAG_DEBUG_LONG
  623. );
  624. #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_EQ(2021040000)
  625. // IE exception: Ngraph operation Reshape with name rpn_cls_score_reshape has dynamic output shape on 0 port, but CPU plug-in supports only static shape
  626. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
  627. applyTestTag(target == DNN_TARGET_OPENCL ? CV_TEST_TAG_DNN_SKIP_IE_OPENCL : CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16,
  628. CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION
  629. );
  630. #endif
  631. if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 ||
  632. backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && target == DNN_TARGET_OPENCL_FP16)
  633. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16);
  634. if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 ||
  635. backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && target == DNN_TARGET_MYRIAD)
  636. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
  637. if (target == DNN_TARGET_CUDA_FP16)
  638. applyTestTag(CV_TEST_TAG_DNN_SKIP_CUDA_FP16);
  639. static Mat ref = (Mat_<float>(3, 7) << 0, 2, 0.90121, 120.407, 115.83, 570.586, 528.395,
  640. 0, 7, 0.988779, 469.849, 75.1756, 718.64, 186.762,
  641. 0, 12, 0.967198, 138.588, 206.843, 329.766, 553.176);
  642. testFaster("faster_rcnn_zf.prototxt", "ZF_faster_rcnn_final.caffemodel", ref);
  643. }
  644. TEST_P(Test_Caffe_nets, RFCN)
  645. {
  646. applyTestTag(
  647. (target == DNN_TARGET_CPU ? CV_TEST_TAG_MEMORY_512MB : CV_TEST_TAG_MEMORY_2GB),
  648. CV_TEST_TAG_LONG,
  649. CV_TEST_TAG_DEBUG_VERYLONG
  650. );
  651. #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_EQ(2021040000)
  652. // Exception: Function contains several inputs and outputs with one friendly name! (HETERO bug?)
  653. if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH && target != DNN_TARGET_CPU)
  654. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION);
  655. #endif
  656. if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 ||
  657. backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && target == DNN_TARGET_OPENCL_FP16)
  658. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16);
  659. if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 ||
  660. backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && target == DNN_TARGET_MYRIAD)
  661. applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
  662. float scoreDiff = default_l1, iouDiff = default_lInf;
  663. if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
  664. {
  665. scoreDiff = 4e-3;
  666. iouDiff = 8e-2;
  667. }
  668. if (target == DNN_TARGET_CUDA_FP16)
  669. {
  670. scoreDiff = 0.0034;
  671. iouDiff = 0.12;
  672. }
  673. static Mat ref = (Mat_<float>(2, 7) << 0, 7, 0.991359, 491.822, 81.1668, 702.573, 178.234,
  674. 0, 12, 0.94786, 132.093, 223.903, 338.077, 566.16);
  675. testFaster("rfcn_pascal_voc_resnet50.prototxt", "resnet50_rfcn_final.caffemodel", ref, scoreDiff, iouDiff);
  676. }
  677. INSTANTIATE_TEST_CASE_P(/**/, Test_Caffe_nets, dnnBackendsAndTargets());
  678. }} // namespace