Created
July 19, 2018 17:54
-
-
Save fehlfarbe/af377886c1646279e17fa93bfc5733f9 to your computer and use it in GitHub Desktop.
Some simple templatematching
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 sys | |
| import cv2 | |
| import numpy as np | |
| FULL = "full.jpg" | |
| CROP = "crop.jpg" | |
| def template_matching(full, template, start=0.1, stop=1.0, step=0.1): | |
| crop_full = cv2.resize(template, tuple(np.roll(full.shape, 1))) | |
| best_val = 0 | |
| best_scale = 0 | |
| best_shape = (0, 0) | |
| best_loc = (0, 0) | |
| for s in np.arange(start, stop, step): | |
| tmp = cv2.resize(crop_full, (0, 0), fx=s, fy=s) | |
| res = cv2.matchTemplate(full_gray, tmp, cv2.TM_CCOEFF_NORMED) | |
| min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) | |
| #top_left = max_loc | |
| #bottom_right = (top_left[0] + w, top_left[1] + h) | |
| #factor = max_val / (tmp.shape[0]*tmp.shape[1]) | |
| print "trying scale ", s, max_val, 1.0/s#, "factor", factor | |
| if max_val > best_val: | |
| best_val = max_val | |
| best_scale = s | |
| best_shape = tmp.shape | |
| best_loc = max_loc | |
| #cv2.imshow("image", tmp) | |
| #cv2.imshow("template", cv2.convertScaleAbs(res)) | |
| #cv2.waitKey(1) | |
| return best_val, best_scale, best_shape, best_loc | |
| if __name__ == '__main__': | |
| cv2.namedWindow("image", cv2.WINDOW_NORMAL) | |
| cv2.namedWindow("template", cv2.WINDOW_NORMAL) | |
| full = cv2.imread(FULL) | |
| crop = cv2.imread(CROP) | |
| if crop.shape[0] > full.shape[0] or crop.shape[1] > full.shape[1]: | |
| print "crop is bigger than full image...abort" | |
| print "crop", crop.shape | |
| print "full", full.shape | |
| sys.exit(-1) | |
| full_gray = cv2.cvtColor(full, cv2.COLOR_BGR2GRAY) | |
| crop_gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY) | |
| best_val, best_scale, best_shape, best_loc = template_matching(full_gray, crop_gray) | |
| # get better result | |
| best_val, best_scale, best_shape, best_loc = template_matching(full_gray, crop_gray, | |
| best_scale-0.15, best_scale+0.15, 0.001) | |
| print "upper left corner:", best_loc | |
| print "width, height:", np.roll(best_shape, 1) | |
| print "middlepoint:", (best_loc[0]+best_shape[1]/2, best_loc[1]+best_shape[0]/2) | |
| print "zoom:", 1.0/best_scale | |
| cv2.rectangle(full, best_loc, (best_loc[0]+best_shape[1], best_loc[1]+best_shape[0]), (255, 255, 255), 5) | |
| cv2.imshow("image", full) | |
| cv2.waitKey(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment