import glob
import cv2 as cv
import numpy as np
from time import time
from matplotlib import pyplot as plt

# parametrs
# match template methods
# matchTemplate_methods = ['cv.TM_CCOEFF', 'cv.TM_CCORR', 'cv.TM_SQDIFF']
matchTemplate_methods = ['cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF_NORMED']

# load test images
my_path = glob.glob("sign_photos/slunce/dej_prednost_v_jizde/*.jpg")
images = []
for img in my_path:
	img_read = cv.imread(img)
	images.append(img_read)
	
# load template
template = cv.imread('Dej_prednost_v_jizde.jpg')
temp_w = temp_h = 150
template_resize = cv.resize(template, (temp_w, temp_h))
template = template_resize
template_copy = template.copy()

# run testing images
for image in images:

	# match template methods testing
	for matchTemplate_method in matchTemplate_methods:
		method = eval(matchTemplate_method)
			
		matched_sign = image.copy()
		
		# restart correlation value
		best_corr = 0
		
		# begin measure
		begin = time()
		
		# template size testing
		for scale in np.linspace(0.4, 1.0, 5):
			
			# restart template size
			template = template_copy
			
			# change template shape
			shape = template.shape
			temp_h = int(shape[0] * scale)
			temp_w = int(shape[1] * scale)
			#print('template shape (h, w) =', temp_h, temp_w)
			
			# resize template
			template_resize = cv.resize(template, (temp_w, temp_h))
			template = template_resize
			
			# result of actual method
			res = cv.matchTemplate(image, template, method)
			min_corr, max_corr, min_loc, max_loc = cv.minMaxLoc(res)
			
			if max_corr > best_corr:
				best_corr = max_corr
				found = (max_loc, min_loc, temp_w, temp_h)	
				result = res.copy()
		
		# points of detected rectangle
		if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
			top_left = found[1]
		else:
			top_left = found[0]
			
		# finish measure
		finish = time()
		
		# print results
		print('match template method =', matchTemplate_method)
		print('time to solve =', (finish - begin) * 1000, '[ms]')
		print('max correlation =', best_corr)
		print('template shape (h, w) =', found[2], found[3])
		
		bottom_right = (top_left[0] + found[2], top_left[1] + found[3])
		# draw rectangle on matched sign
		cv.rectangle(matched_sign, top_left, bottom_right, (0, 255, 0), 15)
		# convert color to print with pyplot as plt matched_sign
		RGB_template = cv.cvtColor(template, cv.COLOR_BGR2RGB)
		RGB_matched_sign = cv.cvtColor(matched_sign, cv.COLOR_BGR2RGB)
				
		# print results
		plt.subplot(121),plt.imshow(result, cmap = 'gray')
		plt.title('Mapa korelačních hodnot'), plt.xticks([]), plt.yticks([])
		plt.subplot(122),plt.imshow(RGB_matched_sign)
		plt.title('Detekovaná značka'), plt.xticks([]), plt.yticks([])
		plt.suptitle(matchTemplate_method)
		plt.show()
			
	
