diff --git a/ocv_template_matching.py b/ocv_template_matching.py index e318c3f..c5b22cb 100644 --- a/ocv_template_matching.py +++ b/ocv_template_matching.py @@ -1,9 +1,7 @@ import cv2 import sys -import imutils as im -from template_matcher import template_match_rotation -from util import bbox_extend, bbox_round, process_image_bbox, image_crop +from util import bbox_extend, bbox_round, image_crop, to_rect, bbox_add_position video = cv2.VideoCapture("./data/IMG_1730.MP4") @@ -20,25 +18,30 @@ if not ok: print('Cannot read video file') sys.exit() -bbox_template = cv2.selectROI("Image", image, False) -template = image_crop(image, bbox_extend(bbox_template, 0.5)) -cv2.imshow("Template", template) +bb_crop = bbox_extend(cv2.selectROI("Image", image, False), 1) +crop = image_crop(image.copy(), bb_crop) + +bb_template = cv2.selectROI("Image", crop, False) +template = image_crop(crop, bb_template) # Perform template match operations -res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) +res = cv2.matchTemplate(crop, template, cv2.TM_CCOEFF_NORMED) (min_val, max_val, min_loc, max_loc) = cv2.minMaxLoc(res) -h, w = (template.shape[0], template.shape[1]) +matcher_bbox_local = (max_loc[0], max_loc[1], template.shape[1], template.shape[0]) +matcher_top_left_local, matcher_bottom_right_local = to_rect(matcher_bbox_local) -print(f"(w, h): {(w, h)}, max_loc: {max_loc}") +matcher_bbox_global = bbox_round(bbox_add_position(matcher_bbox_local, bb_crop)) +matcher_top_left_global, matcher_bottom_right_global = to_rect(matcher_bbox_global) -top_left = max_loc -bottom_right = (top_left[0] + w, top_left[1] + h) +template_top_left, template_bottom_right = to_rect(bb_template) -cv2.rectangle(image, top_left, bottom_right, (0, 255, 0), 2) -cv2.rectangle(image, (bbox_template[0], bbox_template[1]), (bbox_template[0] + bbox_template[2], bbox_template[1] + bbox_template[3]), (0, 0, 255), 2) +cv2.rectangle(crop, template_top_left, template_bottom_right, (255, 0, 0), 3) +cv2.rectangle(crop, matcher_top_left_local, matcher_bottom_right_local, (0, 255, 0), 1) +cv2.rectangle(image, matcher_top_left_global, matcher_bottom_right_global, (0, 0, 255), 1) +cv2.imshow("Crop", crop) cv2.imshow("Image", image) cv2.imshow("Matcher", res)