我如何使用.NET ColorMatrix来改变颜色?

4

我有一张图片,如果像素(x,y).R < 165,我想将像素设置为白色。

之后,我想将不是白色的所有像素都设置为黑色。

我可以使用ColorMatrix来完成这个操作吗?

2个回答

3

您无法使用颜色矩阵完成此操作。颜色矩阵适用于将一种颜色线性转换为另一种颜色。而您所需的变换不是线性的。


@Hans:你能详细说明一下吗? - Pedery
这是Jan的答案。我希望他能接着回答。如果这个问题没有帮到你,请提出自己的问题。 - Hans Passant

1
一种处理这些相对简单的图像操作的好方法是直接获取位图数据。Bob Powell在https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx上撰写了一篇文章,详细介绍了如何锁定位图并通过Marshal类访问其数据。
最好有一个类似于以下结构的结构:
[StructLayout(LayoutKind.Explicit)]
public struct Pixel
{
    // These fields provide access to the individual
    // components (A, R, G, and B), or the data as
    // a whole in the form of a 32-bit integer
    // (signed or unsigned). Raw fields are used
    // instead of properties for performance considerations.
    [FieldOffset(0)]
    public int Int32;
    [FieldOffset(0)]
    public uint UInt32;
    [FieldOffset(0)]
    public byte Blue;
    [FieldOffset(1)]
    public byte Green;
    [FieldOffset(2)]
    public byte Red;
    [FieldOffset(3)]
    public byte Alpha;


    // Converts this object to/from a System.Drawing.Color object.
    public Color Color {
        get {
            return Color.FromArgb(Int32);
        }
        set {
            Int32 = Color.ToArgb();
        }
    }
}

只需创建一个新的像素对象,您就可以通过Int32字段设置其数据,并读取/修改各个颜色分量。
Pixel p = new Pixel();
p.Int32 = pixelData[pixelIndex]; // index = x + y * stride
if(p.Red < 165) {
    p.Int32 = 0; // Reset pixel
    p.Alpha = 255; // Make opaque
    pixelData[pixelIndex] = p.Int32;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接