How can i show an image from its pixels which are already saved in a file ?

241 Views Asked by At

I m using opencv and c++ to save an image's pixels in a file, now i want to restore the image in order to show it again. could you give some suggestions?

[update: included code from OP's comments] I'm using these loops to save my image's pixels in a file

for(int row=0; row<a;row++) 
    for(int col=0;col<b;col++) { 
        pixel[row][col]= ((uchar *)(img->imageData + row*img->widthStep))[col*img->nChannels +0]; 

Now i m trying to read these pixel in order to show the image

2

There are 2 best solutions below

1
On
img->imageData = malloc(a*img->widthStep);  //do this if you didnt allocate the memory before. a*img->widthStep shouldbe the right size of memor needed if imn ot wrong.   
for(int row=0; row<a;row++) 
{
     for(int col=0;col<b;col++) 
     { 
  ((uchar*)(img->imageData + row*img->widthStep))[col*img->nChannels +0] = pixel[row][col];
   // you didnt say what is th type of date in imadeData : put other casts if necessary.
        }
    }

do you take all the information in img->imageData and put it in pixel in your original code ?

so, the answer of karlphillip : " you need to mempcy() the pixels read to new_image->imageData" is what i did in my code.

0
On

The standard (recommended) way to store image data in the disk is putting the pixels in an image container (jpg/png/bmp/tiff/...) and save that to a file. OpenCV handles this process very easily, since you already have img as IplImage* all you need to do is call cvSaveImage() and give the name of the file:

if (!cvSaveImage("output.png", img))
{
    // print cvSaveImage failed and deal with error
}

then, to read this file from the disk use can use cvLoadImage(), which you have probably used already.

If, for some mysteryous reason you are actually storing just the pixels in a file it would be perfectly understandable that you want to read them back to an IplImage structure. For this purpose, the function you are looking for is cvCreateImage():

IplImage* new_img = cvCreateImage(cvSize(width, height), /*img depth*/, /* nChannels*/);

after creating new_image you need to mempcy() the pixels read to new_image->imageData.

However, you need to know beforehand what's the actual size of the image to be able to use this approach. If you are just storing the pixels of the image inside the file then I suggest you store the size of the image as a part of the filename.

One benefit from using OpenCV functions to deal with images is that your system will be able to recognize and display them (which is so important for debugging purposes).