Ask Your Question

cv::dnn::blobFromImage() works in python but fails in c++

asked 2020-12-04 09:21:20 -0500

hammockman gravatar image

updated 2020-12-04 09:27:18 -0500

I am using opencv dnn.Net with the same network and with the same image in python and C++. While in python everything is ok, in C++ I get an access violation error from an opencv.dll.

Here is my code in python:

net = cv2.dnn.readNet(model, config, "Caffe")
    input_img = cv2.imread(image_path)
    blob = cv2.dnn.blobFromImage(input_img, 1.0, (40, 40), 0, False, False, cv2.CV_32F )
    result = net.forward()

In this case no errors and I get the expected output.

Now the code in c++:

net = cv::dnn::readNet(model, config, "Caffe");
    cv::Mat blob;
    blob = cv::dnn::blobFromImage(input_image, 1.0, cv::Size(40,40), cv::Scalar(0,0,0), false, false, CV_32F);

In this case I get access violation as I run net.forward().

Both images are the same, and the are alreay 40x40, 3 channels. model and config are the same paths in python and c++ so the same caffe`model is being used.

Here is the error transcript in case this can be a hint:

Exception thrown at 0x00007FFD2C1B12DE (vcruntime140.dll) in my_exe.exe: 0xC0000005: Access violation reading location 0x000001F972DB9000.

Why is the code failing in C++? How can I fix it?

edit retag flag offensive close merge delete


opencv version ? os ? did you build the python bindings ?

can you put your model somewhere, so ppl can try to reproduce the problem ?

berak gravatar imageberak ( 2020-12-04 13:00:21 -0500 )edit

The OpenCV used in C++ is the default one coming with OpenVino, version 4.3, the OpenCV used in python is version 4.4. I am running my code on Windows10. The model can be found at this link (I am using the deploy version):

hammockman gravatar imagehammockman ( 2020-12-07 02:12:56 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2020-12-07 08:58:34 -0500

hammockman gravatar image

I was missing the following, which apparently is required to run the net in C++:


(The above for CPU inference).

edit flag offensive delete link more


it would be really interesting to see, if the bug (related to your model and the ie backend, which seems to be choosen automatically) is still there in later opencv versions

berak gravatar imageberak ( 2020-12-07 12:28:02 -0500 )edit

Question Tools

1 follower


Asked: 2020-12-04 09:21:20 -0500

Seen: 95 times

Last updated: Dec 07 '20