Skip to content

Instantly share code, notes, and snippets.

@tonmoay
Created December 20, 2016 05:18
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tonmoay/f9c1710d6eb47cd78290377ff2f61887 to your computer and use it in GitHub Desktop.
Save tonmoay/f9c1710d6eb47cd78290377ff2f61887 to your computer and use it in GitHub Desktop.
Template matching using OpenCV python. This code gets a real time frame from webcam & matches with faces in 'images' folder. After the lookup, it rectangles the webcam face & says with which face the webcam face matches
import cv2
from matplotlib import pyplot as plt
import numpy as np
cap = cv2.VideoCapture(0) #Webcam Capture
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
for i in range(3):
template = cv2.imread('images/face'+str(i)+'.jpg',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(gray,template,cv2.TM_SQDIFF)
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(frame,top_left, bottom_right, 255, 1)
cv2.putText(frame, 'Detected Face ID: '+str(i), (top_left[0],top_left[1]-10),
cv2.FONT_HERSHEY_PLAIN, 1.0, (255,255,255))
cv2.imshow('Test',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
@programmershan
Copy link

can u tell me where should i place the images folder.?

@khilad
Copy link

khilad commented Jan 9, 2018

where can i put image

@amrithmmh
Copy link

didnt work for me ...no detection.How many images to use for detection?

@amrithmmh
Copy link

template = cv2.imread('images/face'+str(i)+'.jpg',0)
how is the images named face1,.jpg...face2.jpg....face3.jpg etc?

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