将彩色图像转换为灰度图像

[复制链接]
查看3551 | 回复2 | 2008-12-3 20:05:00 | 显示全部楼层 |阅读模式

大部分视觉处理中用黑白的图像,以得到较好的测量测试效果,但是有些相机是彩色的,所以软件中要先将彩色变为灰度在处理,下面的这段代码可以做到这个:

VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 5010
ClientLeft = 60
ClientTop = 345
ClientWidth = 6000
LinkTopic = "Form1"
ScaleHeight = 5010
ScaleWidth = 6000
StartUpPosition = 3 'Windows Default
Begin VB.PictureBox Picture1
AutoSize = -1 'True
Height = 3180
Left = 600
Picture = "Form1.frx":0000
ScaleHeight = 3120
ScaleWidth = 5100
TabIndex = 1
Top = 600
Width = 5160
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 495
Left = 2640
TabIndex = 0
Top = 4320
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

Private Declare Function GetPixel Lib "gdi32" _
(ByVal hdc As Long, ByVal x As Long, ByVal Y As Long) As Long
Private Declare Function SetPixelV Lib "gdi32" _
(ByVal hdc As Long, ByVal x As Long, _
ByVal Y As Long, ByVal crColor As Long) As Long
Private tmpPic As Picture

Private Sub Form_Load()
Picture1.ScaleMode = 3
Picture1.AutoRedraw = True
Set tmpPic = Picture1.Picture
End Sub

Private Sub Command1_click()
Dim width5 As Long, heigh5 As Long, rgb5 As Long
Dim hdc5 As Long, i As Long, j As Long
Dim bBlue As Long, bRed As Long, bGreen As Long
Dim Y As Long

width5 = Picture1.ScaleWidth
heigh5 = Picture1.ScaleHeight
hdc5 = Picture1.hdc
For i = 1 To width5
For j = 1 To heigh5
rgb5 = GetPixel(hdc5, i, j)
bBlue = Blue(rgb5) '获得兰色值
bRed = Red(rgb5) '获得红色值
bGreen = Green(rgb5) '获得绿色值
'将三原色转换为灰度
Y = (9798 * bRed + 19235 * bGreen + 3735 * bBlue) \ 32768
'将灰度转换为RGB
rgb5 = RGB(Y, Y, Y)
SetPixelV hdc5, i, j, rgb5
Next j
Next i
Set Picture1.Picture = Picture1.Image
End Sub

Private Function Red(ByVal mlColor As Long) As Long
'从RGB值中获得红色值
Red = mlColor And &HFF
End Function
Private Function Green(ByVal mlColor As Long) As Long
'从RGB值中获得绿色值
Green = (mlColor \ &H100) And &HFF
End Function
Private Function Blue(ByVal mlColor As Long) As Long
''从RGB值中获得蓝色值
Blue = (mlColor \ &H10000) And &HFF
End Function

letyoufly | 2009-3-28 08:50:00 | 显示全部楼层
收藏了,以后用,谢谢
dcydu6 | 2010-12-21 11:04:00 | 显示全部楼层
好文章
您需要登录后才可以回帖 登录 | 注册哦

本版积分规则