Converting color bmp to grayscale bmp?

老子叫甜甜 提交于 2019-12-11 06:36:21

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4147639/converting-color-bmp-to-grayscale-bmp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!