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

# load test images
my_path = glob.glob("signs/*.jpg")
images = []
for img in my_path:
	# read sign image
	img_read = cv.imread(img)
	# resize sign image
	img_w = 150
	img_h = 150
	img_resize = cv.resize(img_read, (img_w, img_h), interpolation = cv.INTER_AREA)
	# vector of sign images
	images.append(img_resize)
	
# load templates
my_path = glob.glob("templates/*.jpg")
templates = []
for tmp in my_path:
	# read template
	tmp_read = cv.imread(tmp)
	# resize template
	tmp_w = 150
	tmp_h = 150
	template_resize = cv.resize(tmp_read, (tmp_w, tmp_h), interpolation = cv.INTER_AREA)
	# vector of templates
	templates.append(template_resize)
	
# convert color to print
def convert_color(image, matched_template):
	RGB_sign = cv.cvtColor(image, cv.COLOR_BGR2RGB)
	RGB_matched_sign = cv.cvtColor(matched_template, cv.COLOR_BGR2RGB)
	return(RGB_sign, RGB_matched_sign)				

# print results
def print_images(RGB_sign, RGB_matched_sign, matchTemplate_method):
	plt.figure('Match template recognition')
	plt.subplot(121),plt.imshow(RGB_sign)
	plt.title('Detected sign'), plt.xticks([]), plt.yticks([])
	plt.subplot(122),plt.imshow(RGB_matched_sign)
	plt.title('Recognited sign'), plt.xticks([]), plt.yticks([])
	plt.suptitle(matchTemplate_method)
	plt.show()
	
# match template methods
matchTemplate_methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR', 'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']

# run testing images
for image in images:
	image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
	best_corr = 0
	for template in templates:
		template_gray = cv.cvtColor(template, cv.COLOR_BGR2GRAY)
		# match template methods testing
		for matchTemplate_method in matchTemplate_methods:
			method = eval(matchTemplate_method)
		
			# result of actual method
			res = cv.matchTemplate(image_gray, template_gray, method)
			min_corr, max_corr, min_loc, max_loc = cv.minMaxLoc(res)
			print(max_corr)
			
			# looking for the best correlation value
			if max_corr > best_corr:
				# save the best correlation
				best_corr = max_corr
				# save the best sign template 
				matched_template = template.copy()
	
	RGB_sign, RGB_matched_sign = convert_color(image, matched_template)
	print_images(RGB_sign, RGB_matched_sign, matchTemplate_method)
				

				
	
	
	

