在花了一个小时试图解决这个问题后,我决定作为一个问题。
我在图像相关项目中使用VB.Net 2010。在这一步中,我必须比较两个图像的像素颜色,以确定它们的相似程度。为此,我设计了以下代码:
''get both images as bitmaps
Dim act As New Bitmap("cam.bmp")
Dim map As New Bitmap(bmap)
''declare the variable that counts the different pixels
Dim count As Integer = 0
''declare the variables that represent the colors
Dim val As Long = 0
Dim valr As Long = 0
Dim valg As Long = 0
Dim valb As Long = 0
''analize both images pixel by pixel
For x = 1 To act.Width - 1 Step 1
For y = 1 To act.Height - 1 Step 1
valr = 0
valg = 0
valb = 0
''determine how different the pixels are
valr = Math.Abs(act.GetPixel(x, y).R - map.GetPixel(x, y).R)
valg = Math.Abs(act.GetPixel(x, y).G - map.GetPixel(x, y).G)
valb = Math.Abs(act.GetPixel(x, y).B - map.GetPixel(x, y).B)
val = Long.Parse(Int((valr + valg + valb) / 3).ToString)
''if enough different, add 1 to count
If val > 50 Then
count += 1
End If
Next
Next
''show how many pixels are different in proportion
MsgBox((count / (act.Width * act.Height)).ToString)
当此代码运行时,valr = Math.Abs(act.GetPixel(x, y).R - map.GetPixel(x, y).R)
部分会发生溢出。没有其他问题发生。
答案 0 :(得分:1)
问题在于GetPixel
返回Color
而Color.R
返回Byte
。从另一个字节中减去一个字节时,结果是一个字节,但字节是无符号的,不能保持负值。如果第二个值大于第一个值,则在调用Math.Abs
方法之前得到OverflowException。
为避免这种情况,您可以使用CInt
将字节转换为整数,然后再减去它们。
valr = Math.Abs(CInt(act.GetPixel(x, y).R) - CInt(map.GetPixel(x, y).R))
valg = Math.Abs(CInt(act.GetPixel(x, y).G) - CInt(map.GetPixel(x, y).G))
valb = Math.Abs(CInt(act.GetPixel(x, y).B) - CInt(map.GetPixel(x, y).B))