How to save an IplImage?
When we have an IplImage, how can we save it so we can use it later, or view it as an image outside of our code (such as via png, or jpeg)?
As a code example, I have the following:
void SaveImage()
{
CvSize size;
IplImage *rgb_img;
int i = 0;
size.height = HEIGHT;
size.width = WIDTH;
rgb_img = cvCreateImageHeader(size, IPL_DEPTH_8U, 3);
rgb_img->imageData = my_device.ColorBuffer;
rgb_img->imageDataOrigin = rgb_img->imageData;
/*for (i = 2; i < rgb_img->imageSize; i+= 3)
{
// confirming all values print correctly
printf("%d, ", rgb_img->imageData[i]);
}*/
cvSaveImage("foo.png",rgb_img);
}
I have printed out all of the values in the commented out for loop, and it seems like the data is in the buffer correctl开发者_C百科y. Using cvShowImage to display the image also works correctly, so it seems like the structure of the image is fine.
void SaveImage()
{
CvSize size;
IplImage *rgb_img;
int i = 0;
size.height = HEIGHT;
size.width = WIDTH;
rgb_img = cvCreateImageHeader(size, IPL_DEPTH_8U, 3);
rgb_img->imageData = my_device.ColorBuffer;
// You should NOT have the line below or OpenCV will try to deallocate your data
//rgb_img->imageDataOrigin = rgb_img->imageData;
for (i = 0; i < size.height; i++)
{
for (j = 0;j < size.width; j++)
{
// confirming all values print correctly
printf("%c, ", rgb_img->imageData[i*width + j]);
}
}
cvSaveImage("foo.png",rgb_img);
}
Running this should not crash.
Some problems with your code
- You use %f to print but IPL_DEPTH_8U is 1-byte uchar
To save:
cvSaveImage(outFileName,img)
If you wanted to check it had saved, you could do the following:
if(!cvSaveImage(outFileName,img)) printf("Could not save: %s\n",outFileName);
Taken from http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html#SECTION00052000000000000000 - top result on Google for "opencv write iplimage".
精彩评论