How I use .NET ColorMatrix to change colors?
I hav开发者_Python百科e an image that I would like to set pixels to White if pixel(x,y).R < 165.
After that I would like to set Black all the pixels that aren't White.
Can I do this using ColorMatrix?
You can't do that with a colormatrix. A colormatrix is good for linear transforms from one color to another. What you need is not linear.
A good way to do these relatively simple image manipulations is to get directly at the bitmap data yourself. Bob Powell has written an article on this at https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx. It explains how to lock a bitmap and access its data via the Marshal class.
It's good to have a struct along these lines:
[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();
}
}
}
Just create a new Pixel object, and you can set its data via the Int32 field and read back/modify the individual color components.
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;
}
精彩评论