We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,549 Members — Technology Publication meets Social Media

# Find image1 in image2

I currently found a piece of code on a website but i can't get it to work it always reports fail. Pls help.

``````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
``````
3
Contributors
3
Replies
23 Hours
Discussion Span
9 Months Ago
Last Updated
4
Views
achilleus1234
Newbie Poster
3 posts since Jun 2010
Reputation Points: 10
Skill Endorsements: 0

For a start what images are you passing in to the method, are they the same image and the same size or is image2 and smaller image taken from image1?

hericles
Veteran Poster
1,065 posts since Nov 2007
Reputation Points: 156
Skill Endorsements: 9

Image 2 is smaller, both bitmaps, one is a screenshot other is a premade bitmap, i need to locate something on the screen.

achilleus1234
Newbie Poster
3 posts since Jun 2010
Reputation Points: 10
Skill Endorsements: 0

Depending on how the smaller image was made you may not get a match comparing pixel by pixel. I have found that even using a (supposedly) lossless crop on jpg source files there are differences in at least one pixel. However, if your source files are bitmaps you should find the following of use (pbx1 & 2 are PictureBox controls). Please note the complete lack of error checking (like if bmp2 is wider or taller than 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

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
``````
Reverend Jim
Carpe per diem
Moderator
3,584 posts since Aug 2010
Reputation Points: 561