Reputation: 2789
I have a very simple function that saves a PPM image:
void WriteCImage(CImage *cimg, char *filename)
{
FILE *fp;
int i,n;
fp = fopen(filename,"w");
fprintf(fp,"P6\n");
fprintf(fp,"%d %d\n",cimg->C[0]->ncols,cimg->C[0]->nrows);
fprintf(fp,"255\n");
n = cimg->C[0]->ncols*cimg->C[0]->nrows;
for (i=0; i < n; i++)
{
fputc(cimg->C[0]->val[i],fp);
fputc(cimg->C[1]->val[i],fp);
fputc(cimg->C[2]->val[i],fp);
}
fclose(fp);
}
as you can see, this function receives a matrix (in CImage format) and writes the image data in the ASCII file. It seems correct, but every time I copy a grayscale image to a PPM image I have problems. Look at the code:
//that's a PGM grayscale image
gt = ReadImage(argv[1]);
//creating an RGB image with same dimensions of the PGM image
nwcimg = CreateCImage(gt->nrows,gt->ncols);
n=gt->nrows*gt->ncols;
//iterate through the PGM image
for(index=0;index<n;index++)
{
// just a copy of the grayscale image value to all 3 layeres
//of the PPM (RGB) image
nwcimg->C[0]->val[index]=gt->val[index];
nwcimg->C[1]->val[index]=gt->val[index];
nwcimg->C[2]->val[index]=gt->val[index];
}
WriteCImage(nwcimg,"gt-copied.ppm");
DestroyCImage(&nwcimg);
DestroyImage(>);
what problem i have? well, the code seems correct and simple. But when the cimage matrix/vector is written as a file, i can see that the two pictures are not the same. Seems like the pixels of the PGM image are 'shifted' or 'mirrored' in the copied image.
You can see the Image File and The RGB copy
Upvotes: 1
Views: 772
Reputation: 42165
Shouldn't
for(index=0;index<n;index++) {
nwcimg->C[0]->val[index]=gt->val[index];
nwcimg->C[1]->val[index]=gt->val[index];
nwcimg->C[2]->val[index]=gt->val[index];
be
for(index=0;index<n;index) {
nwcimg->C[0]->val[index]=gt->val[index++];
nwcimg->C[1]->val[index]=gt->val[index++];
nwcimg->C[2]->val[index]=gt->val[index++];
? The for
loop in your file writer writes 3 bytes per loop. The loop in your reader consumes only 1 byte per loop then copies it into three separate arrays.
Upvotes: 2