Skip to content

Instantly share code, notes, and snippets.

@MichaelSnowden
Last active August 18, 2022 15:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelSnowden/2b5ab97322b1e8d1631df59c6a71a0e1 to your computer and use it in GitHub Desktop.
Save MichaelSnowden/2b5ab97322b1e8d1631df59c6a71a0e1 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
import sys
if len(sys.argv) < 3:
print 'Usage: python match.py <template.png> <image.png>'
sys.exit()
template_path = sys.argv[1]
template = cv2.imread(template_path, cv2.IMREAD_UNCHANGED)
channels = cv2.split(template)
zero_channel = np.zeros_like(channels[0])
mask = np.array(channels[3])
image_path = sys.argv[2]
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
mask[channels[3] == 0] = 1
mask[channels[3] == 100] = 0
# transparent_mask = None
# According to http://www.devsplanet.com/question/35658323, we can only use
# cv2.TM_SQDIFF or cv2.TM_CCORR_NORMED
# All methods can be seen here:
# http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html#which-are-the-matching-methods-available-in-opencv
method = cv2.TM_SQDIFF # R(x,y) = \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2 (essentially, sum of squared differences)
transparent_mask = cv2.merge([zero_channel, zero_channel, zero_channel, mask])
result = cv2.matchTemplate(image, template, method, mask=transparent_mask)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
print 'Lowest squared difference WITH mask', min_val
# Now we'll try it without the mask (should give a much larger error)
transparent_mask = None
result = cv2.matchTemplate(image, template, method, mask=transparent_mask)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
print 'Lowest squared difference WITHOUT mask', min_val
opencv-python==3.1.0.4
@NullYing
Copy link

NullYing commented Dec 18, 2018

I run it and show

cv2.error: /io/opencv/modules/imgproc/src/templmatch.cpp:822: error: (-215) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function matchTemplateMask

@mhkarimi
Copy link

same error

@LWSS
Copy link

LWSS commented Oct 15, 2019

same error

images need to both be rgba, do file image.png

@ed1chandler
Copy link

This works great until line 35 where it appears to insist that "transparent_mask" be of type UMat. (Or at least I think that's what it means.) The actual error is:
TypeError: Expected Ptr<cv::Umat> for argument '%s'
Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment