如何使用VB.net比较两个图像?

时间:2014-10-25 19:18:48

标签: vb.net screenshot

我有一个小位图图片,我会做一个截图。我需要找到小图片是否是截图。我如何比较两个位图图像?然后返回坐标。

如果是MATLAB,(注意:我需要VB.net)

我的计划是什么

screenshot
for x_screen = 1: screen_width_x
     for y_screen = 1: screen_col_y 
      for x_pic = = 1: pic_width_x
       for y_pic = = 1: pic_col_y
       if screenshot(x_screen, y_screen) != pic(x_pic , y_pic)
       break
       end
    end
    xx = (x_screen)
    yy = (y_screen)
    end
    end

2 个答案:

答案 0 :(得分:2)

See Image comparison if you want something advanced此外,您还可以为此类任务寻找机器学习技巧。

这是天真的解决方案,而不是优化的解决方案(加上在本机代码中执行此类任务更好):

另外请注意,最好使用bmp文件进行检查。否则它将无法解决问题

Private Function FindSubImg2(img As Bitmap, subimg As Bitmap) As Point
    If (img.Width - subimg.Width < 0) Or (img.Height - subimg.Height < 0) Then Return Nothing 
    Dim stepxLen As Integer = img.Width - subimg.Width
    Dim stepyLen As Integer = img.Height - subimg.Height 
    Dim coor As Point
    Dim match As Boolean = False

    For oy As Integer = 0 To stepyLen
    For ox As Integer = 0 To stepxLen
            match = True 
            For x As Integer = 0 To subimg.Width - 1
                For y As Integer = 0 To subimg.Height - 1
                    'actually here we do not need ToArgb method. But it will skip unneeded Color comparisions
                    If img.GetPixel(x + ox, y + oy).ToArgb <> subimg.GetPixel(x, y).ToArgb Then
                        match = False
                        Exit For 'we can use goto operator instead of double exit for 
                    End If
                Next
                If match = False Then Exit For
            Next
            If match = True Then
                coor.X = ox
                coor.Y = oy
                Return coor
            End If 
        Next
    Next

    Return New Point(-1, -1)
End Function

Private Function FindSubImg(a As Bitmap, b As Bitmap) As Point

    Dim subimg As Bitmap
    Dim img As Bitmap

    If (a.Height <= b.Height AndAlso a.Width <= b.Width) Then
        subimg = a : img = b
        Return FindSubImg2(img, subimg)

    ElseIf (a.Height > b.Height AndAlso a.Width > b.Width) Then
        subimg = b : img = a
        Return FindSubImg2(img, subimg)
    Else
        Return New Point(-1, -1)
    End If


End Function

用法:

Dim p As Point = FindSubImg(New Bitmap("A.bmp"), New Bitmap("B.bmp"))

答案 1 :(得分:1)

尝试这样的事情:

Public Function CompareImages(ByVal img1 As Bitmap, ByVal img2 As Bitmap) As Boolean
    Dim i As Integer
    Dim j As Integer

    For i = 0 To img1.Width - 1
        For j = 0 To img2.Height - 1
            If img1.GetPixel(i, j) <> img2.GetPixel(i, j) Then
                Return False
            End If
        Next
    Next
    Return True
End Function

示例电话:

CompareImages(New Bitmap("f:\img1.bmp"), New Bitmap("f:\img2.bmp"))