dnn: check for empty Net in .forward()
authorAlexander Alekhin <alexander.a.alekhin@gmail.com>
Mon, 5 Oct 2020 06:23:47 +0000 (06:23 +0000)
committerAlexander Alekhin <alexander.a.alekhin@gmail.com>
Mon, 5 Oct 2020 06:23:47 +0000 (06:23 +0000)
modules/dnn/src/dnn.cpp
modules/dnn/test/test_misc.cpp

index 8947791..1d145dd 100644 (file)
@@ -3486,11 +3486,16 @@ void Net::connect(String _outPin, String _inPin)
 Mat Net::forward(const String& outputName)
 {
     CV_TRACE_FUNCTION();
+    CV_Assert(!empty());
 
     String layerName = outputName;
 
     if (layerName.empty())
-        layerName = getLayerNames().back();
+    {
+        std::vector<String> layerNames = getLayerNames();
+        CV_Assert(!layerNames.empty());
+        layerName = layerNames.back();
+    }
 
     std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
     impl->setUpNet(pins);
@@ -3502,11 +3507,17 @@ Mat Net::forward(const String& outputName)
 AsyncArray Net::forwardAsync(const String& outputName)
 {
     CV_TRACE_FUNCTION();
+    CV_Assert(!empty());
+
 #ifdef CV_CXX11
     String layerName = outputName;
 
     if (layerName.empty())
-        layerName = getLayerNames().back();
+    {
+        std::vector<String> layerNames = getLayerNames();
+        CV_Assert(!layerNames.empty());
+        layerName = layerNames.back();
+    }
 
     std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
     impl->setUpNet(pins);
@@ -3527,11 +3538,16 @@ AsyncArray Net::forwardAsync(const String& outputName)
 void Net::forward(OutputArrayOfArrays outputBlobs, const String& outputName)
 {
     CV_TRACE_FUNCTION();
+    CV_Assert(!empty());
 
     String layerName = outputName;
 
     if (layerName.empty())
-        layerName = getLayerNames().back();
+    {
+        std::vector<String> layerNames = getLayerNames();
+        CV_Assert(!layerNames.empty());
+        layerName = layerNames.back();
+    }
 
     std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
     impl->setUpNet(pins);
@@ -4118,6 +4134,8 @@ std::vector<Ptr<Layer> > Net::getLayerInputs(LayerId layerId)
 
 std::vector<String> Net::getLayerNames() const
 {
+    CV_TRACE_FUNCTION();
+
     std::vector<String> res;
     res.reserve(impl->layers.size());
 
index 6df089e..11e0f0e 100644 (file)
@@ -99,6 +99,15 @@ TEST(readNet, do_not_call_setInput)  // https://github.com/opencv/opencv/issues/
     EXPECT_TRUE(res.empty()) << res.size;
 }
 
+TEST(Net, empty_forward_18392)
+{
+    cv::dnn::Net net;
+    Mat image(Size(512, 512), CV_8UC3, Scalar::all(0));
+    Mat inputBlob = cv::dnn::blobFromImage(image, 1.0, Size(512, 512), Scalar(0,0,0), true, false);
+    net.setInput(inputBlob);
+    EXPECT_ANY_THROW(Mat output = net.forward());
+}
+
 #ifdef HAVE_INF_ENGINE
 static
 void test_readNet_IE_do_not_call_setInput(Backend backendId)