五笔打字通主页
将图像中R,G,B三元色的值设置为相等,可以将彩色图片转为灰度图,常用算法有加权平均值法,平均值法和最大值法。下面提供的是加权平均值法的代码。
加权平均值法的原理是根据重要性和其它指标对R,G,G进行加权平均。计算公式为:R=G=G=(WR*R+WG*G+WB*B)/3 常用的权力为:WR=0.3,WG=0.59,WB=0.11,在以下的例子,为了计算方便,采用的公式是 gray = (3 * r + 6 * g + b) / 10
先在窗体上画两个图片框,一个按钮,再自行准备好一个彩色的小图片,并将这个小图片设置为picture1的picture属性。
图片转灰度图VB代码如下,大家一起研究下:
' 返回指定点颜色的红色成分的数值
Private Function Red(x, y) As Integer
Dim color As Long
color = Picture1.Point(y, x)
If color <> -1 Then
Red = color Mod 256
Else
Red = 0
End If
End Function
' 返回指定点颜色的绿色成分的数值
Private Function Green(x, y) As Integer
Dim color As Long
color = Picture1.Point(y, x)
If color <> -1 Then
Green = (color \ 256) Mod 256
Else
Green = 0
End If
End Function
' 返回指定点颜色的蓝色成分的数值
Function Blue(y, x) As Integer
Dim color As Long
color = Picture1.Point(x, y)
If color <> -1 Then
Blue = color \ 256 \ 256
Else
Blue = 0
End If
End Function
' 灰度
Private Sub gray()
Dim i As Integer, j As Integer
Dim x As Long, y As Long
Dim r As Integer, g As Integer, b As Integer
Dim gray As Integer
x = Picture1.ScaleWidth
y = Picture1.ScaleHeight
Picture2.Cls
For i = 1 To y - 2
For j = 1 To x - 2
r = Red(i, j)
g = Green(i, j)
b = Blue(i, j)
gray = (3 * r + 6 * g + b) / 10
Picture2.PSet (j, i), RGB(gray, gray, gray)
Next j
Next i
End Sub
Private Sub Command1_Click()
gray
End Sub
来源:济亨网
本文链接:http://wb86.com/post/49.html