1
votes

The sRGB-factors for grayscale conversion are B,G,R = 0.0722, 0.7152, 0.2126. https://en.wikipedia.org/wiki/Grayscale

Can this greyscale conversion be done (and if yes, how) on a Format24bppRgb image with a ColorMatrix? Or can this only be done pixel-wise?

1

1 Answers

1
votes

I'm not perfectly sure yet, but perhaps this is the answer:

Public Function ConvertToGrayscale(ByVal image As Bitmap) As Bitmap

    Dim grayscaleImage As Image = New Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb)
    Dim attributes As ImageAttributes = New System.Drawing.Imaging.ImageAttributes()

    Dim d1 As Double = 0.0722
    Dim d2 As Double = 0.7152
    Dim d3 As Double = 0.2126

    Dim grayscaleMatrix As New ColorMatrix(New Single()() {New Single() {d1, d1, d1, 0, 0}, New Single() {d2, d2, d2, 0, 0}, New Single() {d3, d3, d3, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
    attributes.SetColorMatrix(grayscaleMatrix)
    Using g As Graphics = Graphics.FromImage(grayscaleImage)
        g.DrawImage(image, New Rectangle(0, 0, grayscaleImage.Width, grayscaleImage.Height), 0, 0, grayscaleImage.Width, grayscaleImage.Height, GraphicsUnit.Pixel, attributes)
    End Using

    Return grayscaleImage

End Function