改善图像比较功能

时间:2014-08-05 06:13:11

标签: vb.net

我正在研究视觉检测系统。我的一个关键功能是将捕获的图像与数据库中的图像进行比较。比较将揭示缺失的部分或损坏的部分。我尝试过使用像素比较,但这种方法不可靠,因为它需要每次都捕获完全相似的图像。有没有办法改善这个功能,使其更加通用。在某种程度上,即使捕获的图像稍微偏移或旋转,它也必须检测图像的差异。请指导我使用VB.Net。以下是我目前的代码。

   Private Sub btnGo_Click(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles btnGo.Click
    Me.Cursor = Cursors.WaitCursor
    Application.DoEvents()
    ' Load the images.
    Dim bm1 As Bitmap = Image.FromFile("C:\Users\pnasguna\Desktop\A56.jpg")
    Dim bm2 As Bitmap = Image.FromFile("C:\Users\pnasguna\Desktop\A54.jpg")
    ' Make a difference image.
    Dim wid As Integer = Math.Min(bm1.Width, bm2.Width)
    Dim hgt As Integer = Math.Min(bm1.Height, bm2.Height)
    Dim bm3 As New Bitmap(wid, hgt)
    ' Create the difference image.
    Dim are_identical As Boolean = True
    Dim eq_color As Color = Color.White
    Dim ne_color As Color = Color.Red
    For x As Integer = 0 To wid - 1
        For y As Integer = 0 To hgt - 1
            If bm1.GetPixel(x, y).Equals(bm2.GetPixel(x,y)) Then
                bm3.SetPixel(x, y, eq_color)
            Else
                bm3.SetPixel(x, y, ne_color)
                are_identical = False
            End If
        Next y
    Next x
    ' Display the result.
    PictureBox1.Image = bm3
    Me.Cursor = Cursors.Default
    If (bm1.Width <> bm2.Width) OrElse (bm1.Height <> bm2.Height) Then are_identical =False
    If are_identical Then
        MessageBox.Show("The images are identical")
    Else
        MessageBox.Show("The images are different")
    End If
    bm1.Dispose()
    bm2.Dispose()
End Sub

1 个答案:

答案 0 :(得分:3)

您可以将XnaFan ImageComparison库作为满足需求的示例来检查源代码

enter image description here

enter image description here

它揭示了像素之间的差异,可以比较具有相似系数的图像,我写了两个基本的例子:

     Imports XnaFan.ImageComparison

    ' ===================================================
    ' Get percentage difference value between two images:
    ' ===================================================

    Dim img1 As Image = Image.FromFile("C:\Image1.jpg")
    Dim img2 As Image = Image.FromFile("C:\Image2.jpg")

    Dim PercentageDifference As Single =
        ImageTool.PercentageDifference(img1:=img1, img2:=img2, threshold:=3)

    MessageBox.Show(String.Format("Percentage Difference: {0}%",
                                  CSng(PercentageDifference * 100I).ToString("n1")))


    ' ========================================
    ' Get difference image between two images:
    ' ========================================

    Dim img1 As Image = Image.FromFile("C:\Image1.jpg")
    Dim img2 As Image = Image.FromFile("C:\Image2.jpg")

    Dim DifferenceBitmap As Bitmap =
        ImageTool.GetDifferenceImage(img1:=img1,
                                     img2:=img2,
                                     adjustColorSchemeToMaxDifferenceFound:=True,
                                     absoluteText:=False)

    PictureBox1.Image = DifferenceBitmap

如果您想要更复杂的东西,可以使用AForge(成像)库进行相似性比较