Home > Software engineering >  I can't get matchtemplate in opencv to work
I can't get matchtemplate in opencv to work

Time:02-17

I have this bit of code:

import cv2 as cv
import numpy as np

haystack = cv.imread('cards4/deck 4.png', cv.IMREAD_REDUCED_COLOR_2)
grayhaystack = cv.cvtColor(haystack, cv.COLOR_BGR2GRAY)

needle = cv.imread('cards4/eightofspades.png', cv.IMREAD_REDUCED_COLOR_2)
grayneedle =cv.cvtColor(needle, cv.COLOR_BGR2GRAY)

cv.imshow('Needle', needle)
cv.imshow('Haystack', haystack)

#methods available :[cv.TM_CCOEFF, cv.TM_CCOEFF_NORMED, cv.TM_CCORR, cv.TMO_CCORR_NORMED, cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]
result = cv.matchTemplate(grayhaystack, grayneedle, cv.TM_SQDIFF_NORMED)


min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
needle_w = needle.shape[1]
needle_h = needle.shape[0]
top_left = max_loc
bottom_right = (top_left[0]   needle_w, top_left[1]   needle_h)
cv.rectangle(grayhaystack, top_left, bottom_right, (0, 255,0), 2, cv.LINE_4)

cv.imshow('Haystack', grayhaystack)
cv.imshow('Result', result)
cv.waitKey(0)

I took the needle image directly on the haystack image and i tried every different methods available and i always get a bad result.

Is there any way to make this work

enter image description here

  • Related