OpenCV Error: Assertion failed (size.width>0 &&size.height>0) 简单代码
我正在尝试运行这个简单的 OpenCV 程序,但出现此错误:
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?
推荐答案
此错误表示您正在尝试显示空图像.当你用imshow
加载图片时,这通常是由于:
This error means that you are trying to show an empty image. When you load the image with imshow
, this is usually caused by:
- 你的图片路径错误(在 Windows 中转义两次目录分隔符,例如
imread("C:path oimage.png")
应该是:imread("C:\path\to\image.png")
或imread("C:/path/to/image.png")
); - 图片扩展名错误.(例如.jpg"不同于.jpeg");
- 您无权访问该文件夹.
排除其他问题的一个简单解决方法是将图像放在您的项目目录中,然后简单地将文件名 (imread("image.png")
传递给 imread
).
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")
).
记得加上waitKey();
,否则什么都看不到.
Remember to add waitKey();
, otherwise you won't see anything.
您可以检查图像是否已正确加载,例如:
You can check if an image has been loaded correctly like:
#include <opencv2opencv.hpp>
#include <iostream>
using namespace cv;
int main()
{
Mat3b img = imread("path_to_image");
if (!img.data)
{
std::cout << "Image not loaded";
return -1;
}
imshow("img", img);
waitKey();
return 0;
}
相关文章