0

image= cv2.imread('fullimage.jpg')
gray= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

template= cv2.imread('staravia.png',0)

result= cv2.matchTemplate(gray, template, cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc= cv2.minMaxLoc(result)

height, width= template.shape[:2]

top_left= max_loc
bottom_right= (top_left[0] + width, top_left[1] + height)
cv2.rectangle(image, top_left, bottom_right, (0,0,255),5)

cv2.imshow('staravia', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

So I'm using this code to identify this image: enter image description here

Inside of this image: enter image description here

But i'm getting enter image description here and this on another (same image but different template) enter image description here

What I'm trying to achieve is to check if the image is inside the template or not correctly.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • that's called "template matching". you aren't finding a "transparent image", you are finding a template. -- the issue here is that your template, when you overlay it over the "haystack", is larger than the instance of that critter in the picture. they need to appear the same size or else it doesn't work. you could scale the template down, or the haystack up, if you knew the scale, or you could try a few scales and try them out. – Christoph Rackwitz May 26 '22 at 13:27
  • see this? different scale: https://i.stack.imgur.com/gjRwo.png it's about 15% larger than in the scene. scaling to 413x412 gives perfect overlap – Christoph Rackwitz May 26 '22 at 13:36
  • The background is transparent in your template, which will not match well, because it will be stripped off when you read the image leaving a combination of black and white around the figure. So you need to read the input unchanged. Then extract the alpha channel and use that as a mask in matchTemplate(). Also use the BGR channels of the input. matchTemplate will work on a colored image. So you do not need to convert to gray. Be sure your template scale matches the scale of the region you want to find in the input and that the rotation matches as well. – fmw42 May 26 '22 at 15:23
  • See for example https://stackoverflow.com/questions/71302061/how-do-i-find-an-image-on-screen-ignoring-transparent-pixels/71302306#71302306 – fmw42 May 26 '22 at 15:25
  • Thank you guys, I will try the suggestions and post an update. – user3849771 May 26 '22 at 16:11

0 Answers0