无法读取opencv中的图像

Can not read image in opencv

本文关键字:图像 opencv 读取      更新时间:2023-10-16

我是opencv的新手,我开始制作一个简单的代码来读取和显示gui中的图像,我在qt IDE中工作,首先我编写了这段代码

#include <opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>

int main()
{
   cv::Mat image=cv::imread("image.jpg");
   cv::namedWindow("My Image");
   cv::imshow("My Image",image);
   cv::waitKey(0);
   cv::destroyAllWindows();
   return 1;
 }

但它在控制台中显示一个白色窗口和错误,然后显示另一个窗口"未响应"消息,然后停止工作,这是屏幕截图http://pbrd.co/1u2A0ow然后我写了另一个有效代码来检查图像是否已读取

int main()
{
Mat image;
cout<<"Size is"<<image.size().height<<","<<image.size().width<<endl;
image=imread("image.jpg");
//Checking first if the image have been read
if(!image.data)
{
    cout<<"n No image has created n"<<endl;
}
return 1;

}

它显示消息,这意味着图像没有被读取,所以问题是如何成功读取和加载图像注意:main.cpp文件的同一文件夹中的图像http://pbrd.co/1u2Bmj1

正如您所说,以下代码显示该文件不存在:

QFile file("image.jpg");
     if(file.exists())
         cout<<"n exist n"<<endl;
     else
         cout<<"n not exist n"<<endl;

解决方案:

首先,试着设置你的图像的完整路径。由于某些原因,Qt在错误的位置搜索您的文件,所以设置完整路径。

例如:

cv::Mat image=cv::imread("G:\2\qt.jpg");
QFile file("G:\2\qt.jpg");
if(file.exists())
    cout<<"n exist n"<<endl;
else
    cout<<"n not exist n"<<endl;

或者UNIX风格:

cv::Mat image=cv::imread("G:/2/qt.jpg");
QFile file("G:/2/qt.jpg");
if(file.exists())
    qDebug()<<"n exist n"<<endl;
else
     qDebug()<<"n not exist n"<<endl;

程序似乎不知道映像在哪里。请尝试将main.cpp作为程序将使用的库之一。这样,程序将能够找到并打开图像。