vb.net 教程 5-13 图像处理之像素处理 6 图像的二值化

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
这篇文章谈谈图像的二值化,也就是将彩色图像转为黑白图像。

步骤是:

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

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

    '黑白1
    Private Sub btn2Color_Click(sender As Object, e As EventArgs) Handles btn2Color1.Click
        Dim pSourceColor As Color
        Dim pDestColor As Color

        Dim destImg As New Bitmap(sourceImg.Width, sourceImg.Height)
        Dim R, G, B As Integer
        Dim AvgColor As Integer
        For i As Integer = 0 To sourceImg.Width - 1
            For j As Integer = 0 To sourceImg.Height - 1
                pSourceColor = sourceImg.GetPixel(i, j)
                R = pSourceColor.R
                G = pSourceColor.G
                B = pSourceColor.B
                AvgColor = (R + G + B) / 3
                If AvgColor >= 128 Then AvgColor = 255 Else AvgColor = 0
                pDestColor = Color.FromArgb(AvgColor, AvgColor, AvgColor)
                destImg.SetPixel(i, j, pDestColor)
            Next
        Next
        picDest.Image = destImg
    End Sub

处理后的图像如下:

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

    Private Sub btn2Color2_Click(sender As Object, e As EventArgs) Handles btn2Color2.Click
        Dim pSourceColor As Color
        Dim pDestColor As Color

        Dim destImg As New Bitmap(sourceImg.Width, sourceImg.Height)
        Dim R, G, B As Integer
        Dim HistGram(255) As Integer

        For i As Integer = 0 To sourceImg.Width - 1
            For j As Integer = 0 To sourceImg.Height - 1
                pSourceColor = sourceImg.GetPixel(i, j)
                HistGram(pSourceColor.R) += 1
            Next
        Next

        Dim threshold As Integer

        Dim allSum, allCount As Integer
        For k As Integer = 0 To 255
            allCount += HistGram(k)
            allSum += k * HistGram(k)
        Next
        threshold = allSum / allCount

        For i As Integer = 0 To sourceImg.Width - 1
            For j As Integer = 0 To sourceImg.Height - 1
                pSourceColor = sourceImg.GetPixel(i, j)
                R = pSourceColor.R

                If R >= threshold Then R = 255 Else R = 0
                pDestColor = Color.FromArgb(R, R, R)
                destImg.SetPixel(i, j, pDestColor)
            Next
        Next

        picDest.Image = destImg

    End Sub

运行如下:

 

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

 

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

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


 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值