Wednesday, January 7, 2009

Image Processing II : Two Ways for Grayscale

There may be many ways to process grayscale but I want to give two examples for it. One of them is very easy like taking average of colors. And the other one is better but uses color matrix. You must define a color matrix to use as image attribute. I like the second algorithm. Anyway, Let's see codes...

'--------------------Code--------------------
Public Shared Function GrayscaleAverage(ByVal img As Image) As Image
Dim rslt As System.Drawing.Image
Dim btmpImg, btmpRslt As New Bitmap(img.Width, img.Height)
btmpImg = DirectCast(img, Bitmap)
btmpRslt = DirectCast(img, Bitmap)
Dim rC, gC, bC, lum As Integer
For i As Integer = 0 To btmpImg.Width - 1
For j As Integer = 0 To btmpImg.Height - 1
rC = btmpImg.GetPixel(i, j).R
gC = btmpImg.GetPixel(i, j).G
bC = btmpImg.GetPixel(i, j).B
lum = Math.Round(0.3 * rC + 0.59 * gC + 0.11 * bC)
btmpRslt.SetPixel(i, j, Color.FromArgb(lum, lum, lum))
Next
Next
rslt = DirectCast(btmpRslt, Image)
Return rslt
End Function
'--------------------Code--------------------


Second function realized with color matrix. You can use another color matrix. may b

'--------------------Code--------------------
Public Shared Function GrayscaleMatrix(ByVal img As Image) As Image
Dim rslt As System.Drawing.Image
Dim btmpImg As New Bitmap(img.Width, img.Height)
btmpImg = DirectCast(img, Bitmap)
Dim g As Graphics = Graphics.FromImage(btmpImg)
Dim cm As ColorMatrix = New ColorMatrix(New Single()() _
{New Single() {0.5, 0.5, 0.5, 0, 0}, _
New Single() {0.5, 0.5, 0.5, 0, 0}, _
New Single() {0.5, 0.5, 0.5, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1}})
'You can use other color matrix

Dim ia As ImageAttributes = New ImageAttributes()
ia.SetColorMatrix(cm)
g.DrawImage(img, New Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia)
g.Dispose()
rslt = DirectCast(btmpImg, Image)
Return rslt
End Function
'--------------------Code--------------------



Also we can see the difference between two algorithms here.

image taken from here

The other color matrix is here.

'--------------------Code--------------------
'Gilles Khouzams
Dim cm As ColorMatrix = New ColorMatrix(New Single()() _
{New Single() {0.3, 0.3, 0.3, 0, 0}, _
New Single() {0.59, 0.59, 0.59, 0, 0}, _
New Single() {0.11, 0.11, 0.11, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1}})
'--------------------Code--------------------


I will continue with edge finding and background extraction. Like Photoshop, isn't it?

No comments: