在image2中查找image1

 收藏

我目前在网站上找到了一段代码,但是我无法使其正常工作,它总是报告失败。请帮助。

Private Function FindImage(Image1 As Bitmap, Image2 As Bitmap) As Point

        For y = 0 To Image1.Height - Image2.Height - 1

            For x = 0 To Image1.Width - Image2.Width - 1

                ix = 0
                iy = 0
                cnt = 0

                While iy < Image2.Height And ix < Image2.Width And Image1.GetPixel(x + ix, y + iy) = Image2.GetPixel(ix, iy)

                    cnt += 1
                    ix += 1

                    If ix = Image2.Width Then

                        ix = 0
                        iy += 1

                    End If

                End While

                If cnt = Image2.Width * Image2.Height Then

                    MessageBox.Show("succes")
                    Return New Point(ix, iy)
                    Exit Function

                End If

            Next

        Next

        MessageBox.Show("fail")
        Return New Point(-1, -1)

    End Function
回复
  • 克制 回复

    根据制作较小图像的方式,可能无法获得逐像素比较的匹配结果。我发现,即使在jpg源文件上使用了(据说)无损裁剪,也至少有一个像素存在差异。但是,如果源文件是位图,则应该找到以下用法(pbx1和2是PictureBox控件)。请注意完全没有错误检查(例如bmp2比bmp1宽还是高)。

    Public Class Form1
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    
            pbx1.Image = Image.FromFile("e:\temp\pic1.bmp")
            pbx2.Image = Image.FromFile("e:\temp\pic2.bmp")
    
            Dim bmp1 As New Bitmap(pbx1.Image)
            Dim bmp2 As New Bitmap(pbx2.Image)
    
            For y As Integer = 0 To bmp1.Size.Height - bmp2.Size.Height - 1
                For x As Integer = 0 To bmp1.Size.Width - bmp2.Size.Width - 1
                    If CompareImage(bmp1, bmp2, x, y) Then
                        MsgBox("found at (" & x & "," & y & ")")
                        Exit Sub
                    End If
                Next
            Next
    
            MsgBox("not found")
    
        End Sub
    
        Function CompareImage(bmp1 As Bitmap, bmp2 As Bitmap, sx As Integer, sy As Integer) As Boolean
    
            'compare the rectangle from bmp1 starting at (x,y) with the bitmap bmp2
    
            For y As Integer = 0 To bmp2.Height - 1
                For x As Integer = 0 To bmp2.Width - 1
                    If Not bmp2.GetPixel(x, y).Equals(bmp1.GetPixel(x + sx, y + sy)) Then Return False
                Next
            Next
    
            Return True
    
        End Function
    
    End Class
    

  • 浅雨夕 回复

    图像2较小,两个都是位图,一个是屏幕截图,另一个是预制的位图,我需要在屏幕上定位一些东西。

  • 余温,散尽 回复

    首先,您要传递给该方法的图像是相同的图像,相同的大小,还是从image1拍摄的image2和较小的图像?