vb.net 教程 5-13 图像处理之像素处理 6

前端之家收集整理的这篇文章主要介绍了vb.net 教程 5-13 图像处理之像素处理 6前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这篇文章谈谈图像的二值化,也就是将彩色图像转为黑白图像。

步骤是:

彩色图像的灰度化,根据灰度和阈值来确定颜色是黑色还是白色。

通常情况下将阈值设置为128:

  1. '黑白1
  2. Private Sub btn2Color_Click(sender As Object,e As EventArgs) Handles btn2Color1.Click
  3. Dim pSourceColor As Color
  4. Dim pDestColor As Color
  5.  
  6. Dim destImg As New Bitmap(sourceImg.Width,sourceImg.Height)
  7. Dim R,G,B As Integer
  8. Dim AvgColor As Integer
  9. For i As Integer = 0 To sourceImg.Width - 1
  10. For j As Integer = 0 To sourceImg.Height - 1
  11. pSourceColor = sourceImg.GetPixel(i,j)
  12. R = pSourceColor.R
  13. G = pSourceColor.G
  14. B = pSourceColor.B
  15. AvgColor = (R + G + B) / 3
  16. If AvgColor >= 128 Then AvgColor = 255 Else AvgColor = 0
  17. pDestColor = Color.FromArgb(AvgColor,AvgColor,AvgColor)
  18. destImg.SetPixel(i,j,pDestColor)
  19. Next
  20. Next
  21. picDest.Image = destImg
  22. End Sub

处理后的图像如下:

可以看出选择128作为阈值实际并不是很好,网上有大量的求阈值的方法,比如大律法等,下面我采用的是一种比较简单的算法:

  1. Private Sub btn2Color2_Click(sender As Object,e As EventArgs) Handles btn2Color2.Click
  2. Dim pSourceColor As Color
  3. Dim pDestColor As Color
  4.  
  5. Dim destImg As New Bitmap(sourceImg.Width,B As Integer
  6. Dim HistGram(255) As Integer
  7.  
  8. For i As Integer = 0 To sourceImg.Width - 1
  9. For j As Integer = 0 To sourceImg.Height - 1
  10. pSourceColor = sourceImg.GetPixel(i,j)
  11. HistGram(pSourceColor.R) += 1
  12. Next
  13. Next
  14.  
  15. Dim threshold As Integer
  16.  
  17. Dim allSum,allCount As Integer
  18. For k As Integer = 0 To 255
  19. allCount += HistGram(k)
  20. allSum += k * HistGram(k)
  21. Next
  22. threshold = allSum / allCount
  23.  
  24. For i As Integer = 0 To sourceImg.Width - 1
  25. For j As Integer = 0 To sourceImg.Height - 1
  26. pSourceColor = sourceImg.GetPixel(i,j)
  27. R = pSourceColor.R
  28.  
  29. If R >= threshold Then R = 255 Else R = 0
  30. pDestColor = Color.FromArgb(R,R,R)
  31. destImg.SetPixel(i,pDestColor)
  32. Next
  33. Next
  34.  
  35. picDest.Image = destImg
  36.  
  37. End Sub

运行如下:


由于本人数学不是很好,更多的算法以后有空研究后再发出来,大家也可以网上搜索一下相应的算法。

由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看 vb.net 教程 目录

猜你在找的VB相关文章