問題描述
我正在嘗試運(yùn)行這個(gè)簡(jiǎn)單的 OpenCV 程序,但出現(xiàn)此錯(cuò)誤:
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;
}
這個(gè)錯(cuò)誤的原因是什么?
What's the cause of this error?
推薦答案
此錯(cuò)誤表示您正在嘗試顯示空?qǐng)D像.當(dāng)你用imshow
加載圖片時(shí),這通常是由于:
This error means that you are trying to show an empty image. When you load the image with imshow
, this is usually caused by:
- 你的圖片路徑錯(cuò)誤(在 Windows 中轉(zhuǎn)義兩次目錄分隔符,例如
imread("C:path oimage.png")
應(yīng)該是:imread("C:\path\to\image.png")
或imread("C:/path/to/image.png")
); - 圖片擴(kuò)展名錯(cuò)誤.(例如.jpg"不同于.jpeg");
- 您無權(quán)訪問該文件夾.
排除其他問題的一個(gè)簡(jiǎn)單解決方法是將圖像放在您的項(xiàng)目目錄中,然后簡(jiǎn)單地將文件名 (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;
}
這篇關(guān)于OpenCV Error: Assertion failed (size.width>0 &&size.height>0) 簡(jiǎn)單代碼的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!