Question

I am trying to convert a colored BMP file to gray-scale BMP. The input bmp is 24 bit and I am producing the same 24 bit bmp at the output, only this time in gray-scale.

The code I am using is

for(int x = 0; x < max; x++)
{
    int lum;
    lum = (r[x]*0.30) + (g[x]*0.59) + (b[x]*0.11);
    r[x] = lum;
    g[x] = lum;
    b[x] = lum;
}

The r, g, b arrays are the RGB color components and I have them in a char *r,*g,*b.

For some reasons I am not getting a clean output. I am attaching the output I am getting with this question, its patchy and contains white and black areas at palces. So what am I doing wrong here?

  1. Is it due to data loss in calculationg of lum or is there something wrong in storing int as a char?
  2. Can gray-scale bmp not be 24 bit? or is it something wrong in the way I am storing rgb values after conversion?

Any help in this will be much appriciated. Thanks.

Was it helpful?

Solution

These should really be unsigned char; if char happens to be signed on your platform, then this code won't do what you expect.

OTHER TIPS

You need to clamp the output of your calculation to be in [0,255]. Your calculation looks ok, but it's always good to be sure.

Also make sure that the r, g, b arrays are unsigned char. You can get away with a lot of signed/unsigned mixing in int (due to 2's complement overflow covering the mistakes) but when you convert to float the signs must be right.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top