c# - 什么是好的 TRUE 黑白颜色矩阵?

标签 c# vb.net image image-processing colormatrix

我想将图像从彩色转换为黑白(即没有灰度,只有黑白)。有没有人有一个很好的颜色矩阵来实现这个?

最佳答案

我终于找到了解决问题的方法:

  1. 使用众所周知的颜色矩阵将图像转换为灰度。
  2. 使用 ImageAttributes 类的 SetThreshold 方法来设置将黑色与白色分开的阈值。

这是 C# 代码:

using (Graphics gr = Graphics.FromImage(SourceImage)) // SourceImage is a Bitmap object
        {                
            var gray_matrix = new float[][] { 
                new float[] { 0.299f, 0.299f, 0.299f, 0, 0 }, 
                new float[] { 0.587f, 0.587f, 0.587f, 0, 0 }, 
                new float[] { 0.114f, 0.114f, 0.114f, 0, 0 }, 
                new float[] { 0,      0,      0,      1, 0 }, 
                new float[] { 0,      0,      0,      0, 1 } 
            };

            var ia = new System.Drawing.Imaging.ImageAttributes();
            ia.SetColorMatrix(new System.Drawing.Imaging.ColorMatrix(gray_matrix));
            ia.SetThreshold(0.8); // Change this threshold as needed
            var rc = new Rectangle(0, 0, SourceImage.Width, SourceImage.Height);
            gr.DrawImage(SourceImage, rc, 0, 0, SourceImage.Width, SourceImage.Height, GraphicsUnit.Pixel, ia);                
        }

我已经对这段代码进行了基准测试,它比逐像素操作快大约 40 倍。

关于c# - 什么是好的 TRUE 黑白颜色矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2746103/

相关文章:

c# - WPF - 强制 ShowDialog 返回

c# - 如何将字符串数组传递给属性构造函数?

asp.net 如何在 web-forms VB 语言中为 Namespace 编码

asp.net - 如何从Date对象中减去一个月?

ios - 如何从 JSON 查询中获取编码图像并将其编码为 Objective-C 中的 UIImage?

c# - 在 LINQ 查询中创建新对象

c# - DataGridView:以不同方式突出显示单元格和行

css - 背景图像可以超出 div 的边界吗?

vb.net - 检测已安装的 Excel 版本(和 Service Pack)

来自 MySQL 的 Android 图片请求