template matching from cropped image with retransformation on global image

This commit is contained in:
2024-06-30 22:54:03 +02:00
parent 78f1aec00d
commit 9aeb49bf19
+16 -13
View File
@@ -1,9 +1,7 @@
import cv2 import cv2
import sys import sys
import imutils as im
from template_matcher import template_match_rotation from util import bbox_extend, bbox_round, image_crop, to_rect, bbox_add_position
from util import bbox_extend, bbox_round, process_image_bbox, image_crop
video = cv2.VideoCapture("./data/IMG_1730.MP4") video = cv2.VideoCapture("./data/IMG_1730.MP4")
@@ -20,25 +18,30 @@ if not ok:
print('Cannot read video file') print('Cannot read video file')
sys.exit() sys.exit()
bbox_template = cv2.selectROI("Image", image, False) bb_crop = bbox_extend(cv2.selectROI("Image", image, False), 1)
template = image_crop(image, bbox_extend(bbox_template, 0.5)) crop = image_crop(image.copy(), bb_crop)
cv2.imshow("Template", template)
bb_template = cv2.selectROI("Image", crop, False)
template = image_crop(crop, bb_template)
# Perform template match operations # 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) (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 template_top_left, template_bottom_right = to_rect(bb_template)
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(image, top_left, bottom_right, (0, 255, 0), 2) cv2.rectangle(crop, template_top_left, template_bottom_right, (255, 0, 0), 3)
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, 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("Image", image)
cv2.imshow("Matcher", res) cv2.imshow("Matcher", res)