Last active
May 18, 2019 09:38
-
-
Save vanmik/35cce2d3e7f62fdc4ec2605ccb8d1ee7 to your computer and use it in GitHub Desktop.
template_matching example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import shutil | |
| import numpy as np | |
| import argparse | |
| import imutils | |
| import glob | |
| import cv2 | |
| template = cv2.imread('logo_with_title.png') | |
| template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) | |
| template = cv2.Canny(template, 50, 200) | |
| (tH, tW) = template.shape[:2] | |
| current_dir = os.path.dirname(__file__) | |
| results_dir = os.path.join(current_dir, 'results') | |
| shutil.rmtree(results_dir) | |
| try: | |
| os.mkdir(results_dir) | |
| except OSError: | |
| pass | |
| for imagePath in glob.glob("targets/*.*"): | |
| image = cv2.imread(imagePath) | |
| gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
| found = None | |
| for scale in np.linspace(0.2, 1.0, 20)[::-1]: | |
| resized = imutils.resize(gray, width = int(gray.shape[1] * scale)) | |
| r = gray.shape[1] / float(resized.shape[1]) | |
| if resized.shape[0] < tH or resized.shape[1] < tW: | |
| break | |
| edged = cv2.Canny(resized, 50, 200) | |
| result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF) | |
| (_, maxVal, _, maxLoc) = cv2.minMaxLoc(result) | |
| if found is None or maxVal > found[0]: | |
| found = (maxVal, maxLoc, r) | |
| try: | |
| (_, maxLoc, r) = found | |
| except TypeError: | |
| continue | |
| (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r)) | |
| (endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r)) | |
| # debug bounding box | |
| cv2.rectangle(image, (startX, startY), (endX, endY), (255, 0, 0), 2) | |
| result_path = os.path.join(results_dir, os.path.basename(imagePath)) | |
| cv2.imwrite(result_path, image) | |
| print(result_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment