How to Use Calculated Color Values with ColorMatrix?

Posted by Otaku on Stack Overflow See other posts from Stack Overflow or by Otaku
Published on 2010-06-10T01:13:50Z Indexed on 2010/06/10 1:22 UTC
Read the original article Hit count: 306

I am changing color values of each pixel in an image based on a calculation. The problem is that this takes over 5 seconds on my machine with a 1000x1333 image and I'm looking for a way to optimize it to be much faster.

I think ColorMatrix may be an option, but I'm having a difficult time figure out how I would get a set of pixel RGB values, use that to calculate and then set the new pixel value. I can see how this can be done if I was just modifying (multiplying, subtracting, etc.) the original value with ColorMatrix, but now how I can use the pixels returned value to use it to calculate and new value.

For example:

Sub DarkenPicture()
    Dim clrTestFolderPath = "C:\Users\Me\Desktop\ColorTest\"
    Dim originalPicture = "original.jpg"
    Dim Luminance As Single
    Dim bitmapOriginal As Bitmap = Image.FromFile(clrTestFolderPath + originalPicture)
    Dim Clr As Color
    Dim newR As Byte
    Dim newG As Byte
    Dim newB As Byte
    For x = 0 To bitmapOriginal.Width - 1
        For y = 0 To bitmapOriginal.Height - 1
            Clr = bitmapOriginal.GetPixel(x, y)
            Luminance = ((0.21 * (Clr.R) + (0.72 * (Clr.G)) + (0.07 * (Clr.B))/ 255
            newR = Clr.R * Luminance
            newG = Clr.G * Luminance
            newB = Clr.B * Luminance
            bitmapOriginal.SetPixel(x, y, Color.FromArgb(newR, newG, newB))
        Next
    Next
    bitmapOriginal.Save(clrTestFolderPath + "colorized.jpg", ImageFormat.Jpeg)
End Sub

The Luminance value is the calculated one. I know I can set ColorMatrix's M00, M11, M22 to 0, 0, 0 respectively and then put a new value in M40, M41, M42, but that new value is calculated based of a value multiplication and addition of that pixel's components (((0.21 * (Clr.R) + (0.72 * (Clr.G)) + (0.07 * (Clr.B)) and the result of that - Luminance - is multiplied by the color component).

Is this even possible with ColorMatrix?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about image-processing