How do I use .NET ColorMatrix to change colors?

I have an image in which I would like to set the pixels to white if the pixel is (x, y) .R <165.

After that I want to set black to all pixels that are not white.

Can I do this with ColorMatrix?

+4
source share
2 answers

You cannot do this with colormatrix. Colorormatrix is ​​good for linear transformations from one color to another. What you need is not linear.

+3
source

A good way to do these relatively simple manipulations with images is to directly obtain the bitmap data yourself. Bob Powell wrote an article about this at http://www.bobpowell.net/lockingbits.htm . It explains how to block a bitmap and access its data through the marshal's class.

It is good to have a structure 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 / change 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; } 
+1
source

All Articles