Ask Your Question

Revision history [back]

Problems with template matching

Hello, my problem is as follows: I have to find an image in another. To do that initially use this:

First code:

img_rgb = cv2.imread('fondo_mapa.png')
template = cv2.imread('caja2.png', 0)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

# Almacenar la anchura (w) y la altura (h) de la plantilla
w, h = template.shape[::-1]

# Realizar operaciones de coincidencia
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)

# Especificar un umbral (threshold)
threshold = 0.8

# Almacenar las coordenadas del área coincidente en un array numpy
loc = np.where(res >= threshold)

Up to this point everything is going great. In the main image (img_rgb) I have four smaller images identical to the template (caja2.png).

The problem is that once the search is done I need to obtain the X, Y coordinates of the position where one of those coincidences is found (Only one !!).

Because I could not fix it then change to this other code:

Second code:

def FindSubImage(im1, im2):
    needle = cv2.imread(im1)
    haystack = cv2.imread(im2, 0)

    uso = cv2.cvtColor(needle, cv2.COLOR_BGR2GRAY)

    result = cv2.matchTemplate(uso, haystack, cv2.TM_CCORR_NORMED)
    #minMaxLoc(result,minVal,maxVal,minLoc,maxLoc, Mat());


    y,x = np.unravel_index(result.argmax(), result.shape)
    return x, y

 posicion = FindSubImage("mapa.png", "cajaX.png")

Now in x, and it is stored successfully the coordinates I need from the image, the problem is that this function is not exact and returns the information wrong because it detects for example the icons of the taskbar that have nothing to do with my image "cajaX.png". What I need, please, is for someone to help me with one of these two solutions:

  1. Obtain from my first code the coordinates x, and the first coincidence that the function finds. or:
  2. Make the coincidence of my second code is accurate and not errors in the search. I thought you can specify a threshold like in the first code but I do not know how to do it here.

Any help you can give me is well-received. Thank you