简体   繁体   中英

error: (-215:Assertion failed) m.dims <= 2 in function 'FormattedImpl' in cv::dnn

I am loading a pre-trained TensorFlow model in the opencv dnn module using the following code -

cv::dnn::Net net = cv::dnn::readNetFromTensorflow("frozen_inference_graph.pb",
                                                   "graph.pbtxt");

net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA); //Run model on GPU
net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);

Mat image = imread("img.jpeg");
Mat resized;
cv::resize(image, resized, cv::Size(300, 300));
cout<<resized.size()<<endl;
cout<<"Resized"<<endl;
auto input_image = dnn::blobFromImage(image, 1.0, cv::Size(300, 300),
                                      cv::Scalar(127.5, 127.5, 127.5),
                                      false, false, CV_32F);
cout<<"Now setting Input";
net.setInput(input_image);
auto detections = net.forward();
cout<<detections;
return 0;

However the I get the following error as mentioned in the question -

what():  OpenCV(4.4.0) /home/atharva/opencv-4.4.0/modules/core/src/out.cpp:87: error: (-215:Assertion failed) m.dims <= 2 in function 'FormattedImpl'

Could someone please point out what the mistake is?. I believe there is some problem in BlobFromImage as nothing after it is getting printed. TIA

This error occurs because you are trying to print a cv::Mat to standard output that has more than 2 dimensions. With cv::dnn , the output after using net.forward() is 4-dimensional. However I have no idea what model you are using because the output structure of the blob is different depending on what task you are trying to do. If I had to guess you are doing some sort of object detection given your choice of variable names. In that case, usually the first dimension is the batch size and since you are using only one image, the batch size is 1. The second dimension is the number of channels in the output. As you're doing object detection on the image, this will also be size 1. The third and fourth dimensions are the number of rows and columns for the final output layer.

Going on faith, you can extract a 2D version of this cv::Mat to print out to standard output by doing:

cv::Mat output(detections.size[2], detections.size[3], CV_32F, detection.ptr<float>());

Now that this is a 2D matrix, you can print out this instead by doing std::cout << output << std::endl; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM