力为的技术博客

联系 聚合 管理
  154 Posts :: 1 Stories :: 561 Comments :: 0 Trackbacks
                                          由彩色到黑白

彩色图转换为灰度图公式很简单:
Y=0.3RED+0.59GREEN+0.11 Blue

用GDI+实现的方式由两种:
1. 直接用上述公式修改象素点
2. 用ColorMatrix。

下面是用ColorMatrix实现示例:

using namespace Gdiplus;
    Image img(wszFileName);
    Graphics graphics(GetDC()
->GetSafeHdc());
    ColorMatrix cm
= {0.3f0.3f0.3f00,
        
0.59f,0.59f,0.59f,00,
        
0.11f,0.11f,0.11f,00,
        
0,    0,    0,    10,
        
0,    0,    0,    01}
;
    ImageAttributes ia;
    ia.SetColorMatrix(
&cm);

    
float x = (float)img.GetWidth();
    
float y = (float)img.GetHeight();
    graphics.DrawImage(
&img, 
        RectF(
0.0f,0.0f,x,y,
        
0.0f,0.0f,x,y, 
        UnitPixel,
        
&ia);

效果图:
 CToG_001.JPG
程序下载
posted on 2005-11-16 10:13 力为 阅读(3331) 评论(9)  编辑 收藏 引用 所属分类: Tools

评论

# re: [GDI+]由彩色到黑白 2005-11-16 11:05 沐枫
能不能加上两种方法的性能比较。

一般情况下,ColorMatrix的性能比较差(如果直接改象素的程序写的好的话)。
似乎只要用到ImageAttributes,GDI+性能就大幅下降。很明显的一点就是:
带Alpha的图片显示
就是比
不带Alpha而且ColorKey的图片显示
来得快得多!  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2005-11-16 17:29 力为
To 沐枫 :
我又看了一下文档,MS说直接更改象素点比用color matrix慢很多。
MS应该是对的吧。 :)  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2006-01-19 14:34 武志文
GDI+,如果你把像素点改成用数组来做,肯定比你用getpiel速度要快N多倍.而colorMatrix 用的是数组方式来做的,肯定比直接用像素的快.至于数组跟colorMatrix 比,我没试过.对GDI+有一定的了解,加msn:sillnet@hotmail.com  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2006-04-06 15:41 wang
我想把用数据采集卡扫描到的二位数组绘成灰度图,请问怎么绘
能帮帮我么,谢谢
qq 187184137
sunice21@126.com  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2006-05-17 10:56 轮回
getpixel肯定是不行的.用lockbits,方法如下:

public static bool Invert0(Bitmap b)
{
BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
unsafe
{
byte * p = (byte *)(void *)Scan0;
int nOffset = stride - b.Width*3;
int nWidth = b.Width * 3;
int h=b.Height;

for(int y=0;y<h;++y)
{
for(int x=0; x < nWidth; ++x )
{
p[0] = (byte)(255-p[0]);
++p;
}
p += nOffset;
}
}
b.UnlockBits(bmData);
return true;
}

  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2006-11-09 09:34 jillzhang
经过测试,直接用数组比ColorMatrix要快一点  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2007-05-07 12:01 smartpig
请问可以把代码发给我学习一下看看吗?
smartpig2008@qq.com 谢谢啦!  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2007-11-22 19:58 firerabbit
类似功能,我再CDialog中都没有问题,为什么在Activex中就不工作了呢?
谁有这方面的经验?  回复  更多评论
  

# re: [GDI+]由彩色到黑白 2007-11-22 20:00 firerabbit
ia.SetColorMatrix(&cm);这一步老是不成功,返回值为2,我查了一下,是不正确的输入参数,谁遇到过类似情况?  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理