user3191398 user3191398 - 3 months ago 67
C++ Question

OpenCV Error: Assertion failed (size.width>0 && size.height>0) simple code

I am trying to run this simple OpenCV program, but i got this error:

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file .../opencv/modules/highgui/src/window.cpp, line 276


#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;

int main()
cout << "Hello World!" << endl;

cv::Mat inputImage = cv::imread("/home/beniz1.jpg");
cv::imshow("Display Image", inputImage);

return 0;

What's the cause of this error?


This error means that you are trying to show an empty image. When you load the image with imshow, this is usually caused by:

  1. The path of your image is wrong (in Windows escape twice directory delimiters, e.g. imread("C:\path\to\image.png") should be: imread("C:\\path\\to\\image.png"), or imread("C:/path/to/image.png"));
  2. The image extension is wrong. (e.g. ".jpg" is different from ".jpeg");
  3. You don't have the rights to access the folder.

A simple workaround to exclude other problems is to put the image in your project dir, and simply pass to imread the filename (imread("image.png")).

Remember to add waitKey();, otherwise you won't see anything.

You can check if an image has been loaded correctly like:

#include <opencv2\opencv.hpp>
#include <iostream>
using namespace cv;

int main()
    Mat3b img = imread("path_to_image");

    if (!
        std::cout << "Image not loaded";
        return -1;

    imshow("img", img);
    return 0;