Skip to content

Instantly share code, notes, and snippets.

@NullYing
Last active February 13, 2019 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NullYing/45f3247ff51c2b27e5caebae8212fc31 to your computer and use it in GitHub Desktop.
Save NullYing/45f3247ff51c2b27e5caebae8212fc31 to your computer and use it in GitHub Desktop.
带有alpha通道的模板匹配(局限性:只能匹配从图中截取的某一部分)
import cv2
import numpy as np
def main():
# 加载原始RGB图像
img_rgb = cv2.imread("test.png", cv2.IMREAD_UNCHANGED)
# 加载将要搜索的图像模板
template = cv2.imread('logo.png', cv2.IMREAD_UNCHANGED)
# 记录图像模板的尺寸
h = template.shape[0]
w = template.shape[1]
channels = cv2.split(template)
mask = np.array(channels[3])
transparent_mask = cv2.merge([mask, mask, mask, mask])
res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCORR_NORMED,
mask=transparent_mask)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
print(min_val)
top_left = min_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img_rgb, top_left, bottom_right, (7, 249, 151), 2)
cv2.imshow('Detected', img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment