Threshold

This algorithm converts specified image to binary image that has only two colors black and white.

   



									Public Shared Sub ApplyThreshold(ByRef bmp As Bitmap, thresholdValue As Short)
	Dim MaxVal As Integer = 768

	If thresholdValue < 0 Then
		Return
	ElseIf thresholdValue > MaxVal Then
		Return
	End If

	Dim bmpData As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
	Dim TotalRGB As Integer
	Dim ptr As IntPtr = bmpData.Scan0
	Dim stopAddress As Integer = CInt(ptr) + bmpData.Stride * bmpData.Height

	While CInt(ptr) <> stopAddress
		TotalRGB = CInt(Marshal.ReadByte(ptr)) + CInt(Marshal.ReadByte(ptr + 1)) + CInt(Marshal.ReadByte(ptr + 2))

		If TotalRGB <= thresholdValue Then
			Marshal.WriteByte(ptr + 2, 0)
			Marshal.WriteByte(ptr + 1, 0)
			Marshal.WriteByte(ptr, 0)
		Else
			Marshal.WriteByte(ptr + 2, 255)
			Marshal.WriteByte(ptr + 1, 255)
			Marshal.WriteByte(ptr, 255)
		End If

		ptr += 3
	End While

	bmp.UnlockBits(bmpData)
End Sub
								


Example

									DIm b As Bitmap = CType(Image.FromFile("rose.jpg"), Bitmap)
ApplyThreshold(b, 400)