load image with openCV Mat c++

vidzz picture vidzz · Apr 19, 2013 · Viewed 46.8k times · Source

I want to load an image using Mat in openCV

My code is:

Mat I = imread("C:/images/apple.jpg", 0);
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", I ); 

I am getting the following error in a message box:

Unhandled exception at 0x70270149 in matching.exe: 0xC0000005: Access violation 
reading location 0xcccccccc.

Please note that I am including:

#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <iostream>
#include <math.h>

Answer

karlphillip picture karlphillip · Apr 19, 2013

I've talked about this so many times before, I guess it's pointless to do it again, but code defensively: if a method/function call can fail, make sure you know when it happens:

Mat I = imread("C:\\images\\apple.jpg", 0);
if (I.empty())
{
    std::cout << "!!! Failed imread(): image not found" << std::endl;
    // don't let the execution continue, else imshow() will crash.
}

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", I ); 
waitKey(0);

Note that Windows' path uses backslash \ instead of the standard / used on *nix systems. You need to escape the backslash when passing the filename: C:\\images\\apple.jpg

Calling waitKey() is mandatory if you use imshow().

EDIT:

If it's cv::imread() that is throwing the exception the only solution I know to work is downloading OpenCV sources and building it on the machine, since re-installing OpenCV doesn't fix the issue.