Reputation: 511
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?
Any help in this will be much appriciated. Thanks.
Upvotes: 1
Views: 6110
Reputation: 93700
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.
Upvotes: 2
Reputation: 272467
These should really be unsigned char
; if char
happens to be signed on your platform, then this code won't do what you expect.
Upvotes: 6