import cv2
import sys
import numpy as np
import imutils as im


def template_match_rotation(source, template, angle, center, rot_min=-1.0, rot_max=+1.0, n_steps=10, scale=1):
	best_angle = 0
	best_r = 0
	best_max_loc = 0
	best_res = None

	im_source = im.resize(source, scale * source.shape[0], scale * source.shape[1])
	for dangle in np.linspace(rot_min, rot_max, n_steps):
		# rotated and scale up to IMG_SCALE_UP-size
		im_template = im.rotate(template, angle + dangle, center=center, scale=scale)

		# Perform template match operations
		res = cv2.matchTemplate(im_source, im_template, cv2.TM_CCOEFF_NORMED)
		(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(res)

		r = maxVal
		if r > best_r:
			best_r = r
			best_angle = dangle
			best_max_loc = (maxLoc[0]/scale, maxLoc[1]/scale)
			best_res = res
		else:
			break

	angle += best_angle
	loc_x = best_max_loc[0]
	loc_y = best_max_loc[1]

	return angle, (loc_x, loc_y), best_res
