Search code examples
c++qtopencvimread

Can not read image in opencv


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


Solution

  • 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;