0

My goal is to read in a PGM image and produce an image with inverted color values. But when I put in this image, I get back this image. I'm programming in C, using Eclipse and MinGW GCC on Windows 7 (64-bit). Why is the image getting so drastically distorted?

int complement(PGMImage *img) {
int i, j;

// set up new PGM to copy onto
PGMImage* comImg = (PGMImage*)malloc(sizeof(PGMImage));
(*comImg).width = (*img).width;
(*comImg).height = (*img).height;

// invert each pixel
for(i = 0; i <= (*img).width; i++) {
    for(j = 0; j <= (*img).height; j++) {

        // set inverted value for each new pixel
        (*comImg).data[i][j].red = abs((*img).maxVal - (*img).data[i][j].red);
        (*comImg).data[i][j].green = abs((*img).maxVal - (*img).data[i][j].green);
        (*comImg).data[i][j].blue = abs((*img).maxVal - (*img).data[i][j].blue);
    }
}

// save a copy of the complement image
save("C:\\image_complement.pgm", comImg);
printf("A copy of your image has been saved as \"C:\\image_complement.pgm\"\n\n");
void free(comImg);
return 0;
}
James
  • 1
  • 1
  • Did you set `maxval` in `comImg`? Otherwise file might receive a garbage value. – luser droog Jul 25 '13 at 17:55
  • @luserdroog I added that, but I'm getting the same result. – James Jul 25 '13 at 18:14
  • Googling `PGMImage` I've found different incompatible definitions [here](http://sun.iwu.edu/~shelley/sie/zoo/journal/research.c.2.html) and [here](https://gist.github.com/hkulekci/2820788). Maybe your problem lies somewhere there. Have you already tried writing back the orginal image? – Ingo Leonhardt Jul 27 '13 at 08:55

2 Answers2

1

I'm not sure, but I would suspect the outer array index of your image to be the line and the inner to be the column. Thus I would expect that i should run to (*img).height and j to (*img).width.

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
  • I switched .height and .width, but that just gave me [this image](http://img59.imageshack.us/img59/9818/ipys.jpg), which is more or less the same problem. – James Jul 25 '13 at 18:06
1

I think <= should be < in both of your loops. With the revised image, from the comments to the other answer, it looks like it's "stepping over the edge" on each row.


Um, a pgm is a graymap, right? What does "red" "green" and "blue" mean?

luser droog
  • 18,988
  • 3
  • 53
  • 105
  • That's the way the header file is set up. I don't really get why it's called a graymap, but PGM files can have full color. – James Jul 25 '13 at 18:36
  • I'd recommend you try only accessing the "red" values. PGM files cannot have color (at least, not multiple channels like this). That's what PPM files are for. – luser droog Jul 25 '13 at 23:50