Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active June 4, 2017 13:35
Show Gist options
  • Save dboyliao/18f8cbe6e07462fc14eb1aa1970f7e32 to your computer and use it in GitHub Desktop.
Save dboyliao/18f8cbe6e07462fc14eb1aa1970f7e32 to your computer and use it in GitHub Desktop.
Example script for object detection with opencv template matching
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# http://docs.opencv.org/trunk/df/dfb/group__imgproc__object.html#ga586ebfb0a7fb604b35a23d85391329be
from __future__ import print_function
import argparse
import sys
try:
import cv2
except ImportError:
print("Install opencv python binding first", file=sys.stderr)
sys.exit(1)
def main(src_path, tepl_path, method=cv2.TM_CCORR_NORMED):
"""
Main function for object detection with template matching
"""
img = cv2.imread(src_path, cv2.IMREAD_COLOR)
template = cv2.imread(tepl_path, cv2.IMREAD_COLOR)
resp = cv2.matchTemplate(img, template, method)
_, _, min_loc, max_loc = cv2.minMaxLoc(resp)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
ori = min_loc
else:
ori = max_loc
print("ori: {}".format(ori))
tepl_h, tepl_w = template.shape[:2]
buttom_right = (ori[0]+tepl_w, ori[1]+tepl_h)
cv2.rectangle(img, ori, buttom_right, (0, 0, 255), 2)
cv2.imwrite("result.png", img)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="object detecting with template matching")
parser.add_argument("src_path", metavar="SRC_PATH", help="source image path")
parser.add_argument("tepl_path", metavar="TEPL_PATH", help="template image path")
args = vars(parser.parse_args())
main(**args)
@dboyliao
Copy link
Author

dboyliao commented Jun 4, 2017

source image
messi5

@dboyliao
Copy link
Author

dboyliao commented Jun 4, 2017

template
template

@dboyliao
Copy link
Author

dboyliao commented Jun 4, 2017

result:
result

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