|
楼主 |
发表于 2015-8-11 14:09
|
显示全部楼层
本帖最后由 wangg913 于 2015-8-11 15:47 编辑
迭代法获取最佳阈值
首先假定一个阈值 T0
T0为最大灰度值和最小灰度值的平均值
即,分别求出最大灰度值 iMax 和最小灰度值 iMin
第二步,根据 T0 将灰度图片分为前景色和背景色,分别求出前景色平均灰度值AvgFore和背景色的平均灰度值AvgBack
- AvgBack = (∑( i = iMin to T0) i * Histogram(i)) / (∑( i = iMin to T0) Histogram(i))
复制代码- AvgFore = (∑( i =(T0 + 1) to iMax) i * Histogram(i)) / (∑( i = (T0 + 1) to iMax) Histogram(i))
复制代码 然后求得迭代阈值 T1,并进行判断是否为目标阈值。
- T1 = (AvgBack + AvgFore) \ 2
复制代码 如果 T1 = T0 ,则 T1 即为目标阈值;
否则,T0 = T1,继续从第二步进行迭代取值,直至 T1 = T0 为止。
完整代码如下:
- Private Function Iteration() As Boolean '迭代法获取最佳阈值
- Dim A As Long, B As Long, C As Long
- Dim iMin As Integer, iMax As Integer
- Dim iItThreshold As Integer, bError As Byte
- Dim lIntegralBack As Long, lIntegralFore As Long
- Dim lSumBack As Long, lSumFore As Long
- Dim dAvgBack As Double, dAvgFore As Double
- For A = 0 To lWid - 1
- For B = 0 To lHei - 1
- If iMin > lGreyLvl(A, B) Then
- iMin = lGreyLvl(A, B)
- End If
- If iMax < lGreyLvl(A, B) Then
- iMax = lGreyLvl(A, B)
- End If
- Next
- Next
- bError = 1 '设定误差范围
- C = 0
- iThreshold = 0
- iItThreshold = (iMax + iMin) \ 2 '设定初始迭代阈值为最大灰度值和最小灰度值的均值
- Do While Math.Abs(iThreshold - iItThreshold) > bError
- lSumBack = 0
- lSumFore = 0
- lIntegralBack = 0
- lIntegralFore = 0
- For A = iMin To iItThreshold '背景色阈值
- lSumBack = lSumBack + lHistogram(A)
- lIntegralBack = lIntegralBack + lHistogram(A) * A
- Next
- For B = iItThreshold + 1 To iMax '前景色阈值
- lSumFore = lSumFore + lHistogram(B)
- lIntegralFore = lIntegralFore + lHistogram(B) * B
- Next
- dAvgBack = IIf(lSumBack <> 0, lIntegralBack / lSumBack, 0)
- dAvgFore = IIf(lSumFore <> 0, lIntegralFore / lSumFore, 0)
- iThreshold = iItThreshold
- iItThreshold = (dAvgBack + dAvgFore) \ 2 '渐进逼近目标阈值
- C = C + 1
- If C > 999 Then
- Iteration = False
- Exit Function
- End If
- Loop
- Iteration = True
- End Function
复制代码
|
评分
-
1
查看全部评分
-
|