Skip to content

Instantly share code, notes, and snippets.

@suadanwar
Last active September 22, 2022 02:23
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 suadanwar/5c78f587c3c1da4dc57975fe111cc5d2 to your computer and use it in GitHub Desktop.
Save suadanwar/5c78f587c3c1da4dc57975fe111cc5d2 to your computer and use it in GitHub Desktop.
This is sample code for template matching tutorial using OpenCV on Raspberry Pi
import cv2
import numpy as np
img = cv2.imread("Cover.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("Raspberry Pi.jpg", 0)
w, h = template.shape[::-1]
count = 0
res = cv2.matchTemplate(gray_img, template, cv2.TM_CCORR_NORMED )
#methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR','cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
print(res)
threshold = 0.99;
loc = np.where(res >= threshold)
print(loc)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)#colour of rectangle(b,g,r)
count = count + 1
print(count)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
@wei1224hf
Copy link

Thank you for your sharing,
about the code below:
res >= threshold
how to caculate each threshold in each array?
If I want to get the top 5 , how to get them?

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