Files
ocv_template_matching/ocv_template_matching.py
T

53 lines
1.5 KiB
Python

import cv2
import sys
from util import bbox_extend, bbox_round, image_crop, to_rect, bbox_add_position
video = cv2.VideoCapture("./data/IMG_1730.MP4")
# Exit if video not open
# d.
if not video.isOpened():
print("Could not open video")
sys.exit()
# Read first frame.
ok, image = video.read()
if not ok:
print('Cannot read video file')
sys.exit()
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(crop, template, cv2.TM_CCOEFF_NORMED)
(min_val, max_val, min_loc, max_loc) = cv2.minMaxLoc(res)
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)
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)
template_top_left, template_bottom_right = to_rect(bb_template)
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)
while True:
# Exit if ESC pressed
k = cv2.waitKey(1) & 0xff
if k == 27:
break