66 lines
2.2 KiB
Python
66 lines
2.2 KiB
Python
import cv2
|
|
import numpy as np
|
|
import imutils as im
|
|
|
|
from util import bbox_extend, bbox_round, image_crop, to_rect, bbox_add_position, bbox_center
|
|
|
|
IMG_SCALE_UP = 1
|
|
IMG_ROTATE = 0
|
|
|
|
|
|
class CornerTracker:
|
|
def __init__(self, reference: np.array, bbox: np.array, name: str = 'CornerTracker'):
|
|
self.ref = {'image': reference, 'bbox': bbox, 'offset': (0, 0)}
|
|
self.name = name
|
|
self._path = []
|
|
self.line_from = None
|
|
self.first_frame = True
|
|
|
|
def _print(self, s):
|
|
print(f"{self.name}: {s}")
|
|
|
|
def process(self, image: np.array):
|
|
crop_scaled = im.resize(image, IMG_SCALE_UP * image.shape[1], IMG_SCALE_UP * image.shape[0])
|
|
template = self.ref['image']
|
|
bb_template = self.ref['bbox']
|
|
|
|
template_scaled = im.resize(template, IMG_SCALE_UP * template.shape[0], IMG_SCALE_UP * template.shape[1])
|
|
matcher_res = cv2.matchTemplate(crop_scaled, template_scaled, cv2.TM_CCOEFF_NORMED)
|
|
|
|
(min_val, max_val, min_loc, max_loc) = cv2.minMaxLoc(matcher_res)
|
|
self._print(f"(min_val, max_val, min_loc, max_loc): {(min_val, max_val, min_loc, max_loc)}")
|
|
self._print(f"matcher_res : {matcher_res.shape}")
|
|
self._print(f"crop : {image.shape}")
|
|
self._print(f"crop_scaled : {crop_scaled.shape}")
|
|
self._print(f"template : {template.shape}")
|
|
self._print(f"template_scaled : {template_scaled.shape}")
|
|
|
|
matcher_start_x = max_loc[0]/IMG_SCALE_UP
|
|
matcher_start_y = max_loc[1]/IMG_SCALE_UP
|
|
if self.first_frame:
|
|
self.first_frame = False
|
|
offset_x = matcher_start_x - bb_template[0]
|
|
offset_y = matcher_start_y - bb_template[1]
|
|
self.ref['offset'] = (offset_x, offset_y)
|
|
self._print(f"offset : {(offset_x, offset_y)}")
|
|
|
|
matcher_start_x -= self.ref['offset'][0]
|
|
matcher_start_y -= self.ref['offset'][1]
|
|
|
|
self._print(f"matcher_start : {(matcher_start_x, matcher_start_y)}")
|
|
matcher_bbox_local = (round(matcher_start_x), round(matcher_start_y), template.shape[1], template.shape[0])
|
|
|
|
cv2.imshow(f"{self.name}: Matcher res", matcher_res)
|
|
# cv2.imshow("{self.name}: Matcher view", matcher_crop)
|
|
|
|
return matcher_bbox_local, matcher_res
|
|
|
|
def path_add(self, point):
|
|
if self.line_from is not None:
|
|
self._path.append({'from': self.line_from, 'to': point})
|
|
self.line_from = point
|
|
|
|
@property
|
|
def path(self):
|
|
return self._path
|