将彩色bmp转换为灰度bmp?
我正在尝试将彩色 BMP 文件转换为灰度 BMP。输入 bmp 是 24 位,我在输出处生成相同的 24 位 bmp,只是这次是灰度。
我使用的代码是
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;
}
r
、g
、b
数组是 RGB 颜色分量,我将它们放在 char * 中r,*g,*b
。
由于某些原因,我没有得到干净的输出。我附上了我在这个问题上得到的输出,它不完整,并且在一些地方包含白色和黑色区域。那么我在这里做错了什么?
- 是由于 lum 计算中的数据丢失还是由于将 int 存储为 char 时出现问题?
- 灰度bmp不能是24位吗?还是我在转换后存储 RGB 值的方式有问题?
对此的任何帮助将非常感激。谢谢。
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?
- Is it due to data loss in calculationg of lum or is there something wrong in storing int as a char?
- 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些实际上应该是
unsigned char
;如果char
碰巧在您的平台上进行了签名,那么此代码将不会执行您所期望的操作。These should really be
unsigned char
; ifchar
happens to be signed on your platform, then this code won't do what you expect.您需要将计算的输出限制在 [0,255] 内。您的计算看起来不错,但确定总是好的。
还要确保 r、g、b 数组是
unsigned char
。您可以在 int 中进行大量有符号/无符号混合(由于 2 的补码溢出覆盖了错误),但是当您转换为 float 时,符号必须是正确的。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.