画像をグレースケールに変換する

カラー調整行列を使ってNTSC 係数による加重平均法という方法で画像をグレースケールに変換します。

グレースケールにするといっても、いろいろな方法があるようです。[参考:グレースケールのひみつ]

実装例

Public Function GetGrayScaleImage(ByVal bmpSrc As Bitmap) As System.Drawing.Image
    ' NTSC 係数による加重平均法
    ' 係数
    Const R As Single = 0.298912F
    Const G As Single = 0.586611F
    Const B As Single = 0.114478F

    Dim arrColorMatrix As Single()() = _
                       {New Single() {R, R, R, 0, 0}, _
                        New Single() {G, G, G, 0, 0}, _
                        New Single() {B, B, B, 0, 0}, _
                        New Single() {0, 0, 0, 1, 0}, _
                        New Single() {0, 0, 0, 0, 1}}

    Dim objColorMatrix As Imaging.ColorMatrix = New Imaging.ColorMatrix(arrColorMatrix)

    Dim imgAttr As Imaging.ImageAttributes = New Imaging.ImageAttributes()
    ' カラー調整行列を設定します。 
    imgAttr.SetColorMatrix(objColorMatrix)
    ' 変換後のBitmapを生成。
    Dim bmpDest = New Bitmap(bmpSrc.Width, bmpSrc.Height)

    Dim grp As Graphics = Graphics.FromImage(bmpDest)
    ' セットした属性を適用して画像を描画します。
    grp.DrawImage(bmpSrc, New Rectangle(0, 0, bmpSrc.Width, bmpSrc.Height), _
                    0, 0, bmpSrc.Width, bmpSrc.Height, _
                    GraphicsUnit.Pixel, imgAttr)

    grp.Dispose()

    Return bmpDest

End Function