OpenCV – cvLoadImage() can NOT load JPG image

jpegopencvvisual-studio-2008

I'm a newbie in OpenCV and want to ask a basic question about loading image.

I using OpenCV2.0 and Visual Studio 2008 on windows7.

From what I read and understand there are "cvLoadImage()" function to load image in OpenCV.

I currently try very basic program to load and showed picture in windows.

This is my code:

#include "stdafx.h"
#include <cv.h>
#include <highgui.h>

int _tmain(int argc, _TCHAR* argv[])
{
  IplImage* img = cvLoadImage("C:/hello.jpg");

  if (!img)
    printf("Image can NOT Load!!!\n");

  cvNamedWindow("myfirstwindow");
  cvShowImage("myfirstwindow", img);

  cvWaitKey(0);
  cvReleaseImage(&img);

return 0;
}

The result is I can get the window with gray color but the image wasn't show.
I had tried other solution such as put the image inside the project folder and then called it, but still have the same result.

However, when I tried to using other type of image such as .png it successfully loaded.

Is there anyone that have the same problem previously or know any solution to solve this problem?

Thanks,

-jwiil-

Best Answer

This is because the path you are giving to your program is not actually pointing towards anything.

If you are putting the image in the same folder then you need to call

cvLoadImage("hello.jpg");

if the image is anywhere else then as @vasile commented you need to call

cvLoadImage("C:\\hello.jpg");

Also I have edited your code so it exits if the image is not loaded properly

#include "stdafx.h"
#include <cv.h>
#include <highgui.h>

int _tmain(int argc, _TCHAR* argv[])
{
  IplImage* img = cvLoadImage("C:/hello.jpg");

  if (!img)
  {
    printf("Image can NOT Load!!!\n");
    return 1;
  }

  cvNamedWindow("myfirstwindow");
  cvShowImage("myfirstwindow", img);

  cvWaitKey(0);
  cvReleaseImage(&img);

return 0;
}