im using matchtemplate to detect 67x45 sqaure on background. i think my code works fine without any problem but the problem is i have to set high threshold for it to detect successfully otherwise it would give so many false detections. so i tried changing method to cv2.TM_CCOEFF_NORMED but it didnt work well. i also tried to look for opencv document to understand how all these methods work but its really hard for me to understand since they just provide math formulas.. so my question is am i fine with my code? or is there a better way to accomplish what i want to do? (im also not sure if im using 'template' parameter in matchtemplate in the correct way)
import cv2
import numpy as np
import win32gui, win32ui, win32con
def imagesearch(per):
filename = 'target.png'
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
img1 = cv2.imread(filename)
template = cv2.imread('./map/6745.png', cv2.IMREAD_GRAYSCALE)
w, h = template.shape[::-1]
meth = [cv2.TM_CCOEFF, cv2.TM_CCOEFF_NORMED, cv2.TM_CCORR, cv2.TM_CCORR_NORMED, cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]
res = cv2.matchTemplate(img, template, meth[3], None, template)
threshold = per
loc = np.where(res>=threshold)
if loc[0].any():
for pt in zip(*loc[::-1]):
cv2.rectangle(img1, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)
cv2.imshow("dst", img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
imagesearch(0.99)
image
template
result with threshold = 0.99
result with threshold = 0.95
as @Christoph Rackwitz suggested,
import cv2
import numpy as np
import win32gui, win32ui, win32con
def imagesearch():
filename = 'target.png'
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
img1 = cv2.imread(filename)
template = cv2.imread('./map/6745.png', cv2.IMREAD_GRAYSCALE)
w, h = template.shape[::-1]
meth = [cv2.TM_CCOEFF, cv2.TM_CCOEFF_NORMED, cv2.TM_CCORR, cv2.TM_CCORR_NORMED, cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]
method = meth[5]
res = cv2.matchTemplate(img, template, meth[5], None, template)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
min_val,max_val,min_loc, max_loc = cv2.minMaxLoc(res)
top_left = min_loc
bottom_right = (top_left[0]+w,top_left[1]+h)
cv2.rectangle(img1,top_left,bottom_right,255,1)
cv2.imshow("dst", img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
imagesearch()
this one doesnt work either.