Can not read image in opencv

2019-02-21 09:17发布

问题:

I am new to opencv and I am starting to make a simple code to read and display image in gui ,I am working in qt IDE, first I wirte this block of code

#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;
 }

But it displays a white window and error in console and then display another window "not responsive" message and then stop working, This is a screen shot http://pbrd.co/1u2A0ow Then I wrote another validity code to check wheater or not the image is been read

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;

}

It displays the message, which means that the image is not read,So The question is How can I successfully read and load image note: The image in the same folder of main.cpp file http://pbrd.co/1u2Bmj1

回答1:

As you said following code showed you that file not exist:

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

Solution:

First of all, try to set full path to your image. For some reasons Qt search your file in wrong place, so set full path.

For example:

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;

Or UNIX style:

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;


回答2:

it seems that the program does not know where the image is. Try to include main.cpp as one of the libraries that the program will use. That way, the program will be able to find and open the image.