|||
Visual Basic与图像处理 (二)
6、阈值变换
图像的阈值变换可以将一幅图像变为黑白二值图像,即按照设定的阈值,如果图像中像素点的灰度值小于该阈值,则将该像素点的灰度值设定为0,在图像中显示为黑色,否则将改点的灰度值设定为255,在图像中显示为白色。有时候为强化阈值后的效果,也会将阈值结果进行反相。
阈值变换的原理可以表达为如下的函数形式:
这里的T就是设定的阈值。
阈值变换的实现方法也比较简单,在本例示范时,增加了一个水平滚动条用于设定阈值,其余界面与灰度线性变换的类似,软件的界面如下图所示:
这里用一个ThresholdValued窗体级别变量作为阈值,其中阈值变换按钮对于的代码如下:
Private Sub cmdThresholdTrans_Click()
Dim i As Integer, j As Integer
Dim PixelValue As Long
Dim r As Integer, g As Integer, b As Integer
Dim GrayValue As Integer
Dim NGrayValue As Integer
ThresholdValue = Val(txtThreshold)
'设置目标图像的高度和宽度
DestImHeight = SourceImHeight
DestImWidth = SourceImWidth
'设置目标PictureBox的大小
PicDest.Height = DestImHeight
PicDest.Width = DestImWidth
'彩色图像的阈值变换
For i = 0 To SourceImHeight - 1
For j = 0 To SourceImWidth - 1
PixelValue = PicSource.Point(j, i)
r = PixelValue Mod 256
g = (PixelValue 256) Mod 256
b = PixelValue 65536
'插入图像处理的过程,对r, g, b进行处理
GrayValue = 0.3 * r + 0.59 * g + 0.11 * b
If GrayValue < ThresholdValue Then NGrayValue = 0 Else NGrayValue = 255
PicDest.PSet (j, i), RGB(NGrayValue, NGrayValue, NGrayValue)
Next j
Next i
End Sub
滚动条对应的代码如下:
Private Sub HScroll1_Change()
txtThreshold = Str(HScroll1.Value)
End Sub
当文本框失去焦点时,也自动更改阈值,对应的代码如下:
Private Sub txtThreshold_LostFocus()
HScroll1.Value = Val(txtThreshold)
End Sub
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-5-5 18:16
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社