Saving an image in OpenCV

Sujay Ghosh picture Sujay Ghosh · May 12, 2009 · Viewed 112k times · Source

I am new to OpenCV, and trying to capture an image, and then save it to a file. I am posting the code for your reference, below.

The jpg file is being saved, but it is black.

// Capture the Image from the webcam
CvCapture *pCapturedImage = cvCreateCameraCapture(0);

// Get the frame
IplImage *pSaveImg = cvQueryFrame(pCapturedImage);

// Save the frame into a file
cvSaveImage("test.jpg". ,pSaveImg); // A JPG FILE IS BEING SAVED
                                    // OF 6KB , BUT IT IS BLACK

All of the functions are succesful. I have tried the above code in both XP and Vista - the result is a black image on both. Please let me know what I am missing out.

Answer

Barney Szabolcs picture Barney Szabolcs · Dec 4, 2012

If you use C++, it is best to use C++ interface:

using namespace cv;
// Capture the Image from the webcam
VideoCapture cap(0);

// Get the frame
Mat save_img; cap >> save_img;

if(save_img.empty())
{
  std::cerr << "Something is wrong with the webcam, could not get frame." << std::endl;
}
// Save the frame into a file
imwrite("test.jpg", save_img); // A JPG FILE IS BEING SAVED