import glob
import cv2 as cv
import numpy as np
from time import time
from matplotlib import pyplot as plt
 
# load test image
def load_images():
	my_path = glob.glob("sign_photos/slunce/hlavni_silnice/*.jpg")
	images = []
	for img in my_path:
		img_read = cv.imread(img)
		# read size
		h, w, _ = img_read.shape
		# reducing size
		w = w//1
		h = h//1
		img_resize = cv.resize(img_read, (w, h), interpolation = cv.INTER_NEAREST)
		images.append(img_resize)
	return(images)

# thresh detection
def shape_detection(image, thresh_method, thresh_value):	
	value = eval(thresh_value)
	
	# convert color to gray
	gray_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
	
	# thresholding
	if thresh_value in ['cv.THRESH_OTSU', 'cv.THRESH_TRIANGLE']:
		thresh, thresh_image = cv.threshold(gray_img, 0, 255, thresh_method + value)		# get auto thrash value (otsu, triangle)
	else:
		thresh, thresh_image = cv.threshold(gray_img, value, 255, thresh_method)			# user thrash value
		
	print(thresh)
	
	# adaptive thresholding
	#thresh_image = cv.adaptiveThreshold(gray_img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 15, 1)
	
	# find contours
	_, contours, _ = cv.findContours(thresh_image, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
	
	for contour in contours:
		# ignore too small and large area of contours
		h, w, _ = image.shape
		image_area = w*h
		contour_area = cv.contourArea(contour)
		
		if (contour_area < image_area * 0.0005) | (contour_area > image_area * 0.02):
			continue
		
		# find possitions of detected contours
		x, y, w, h = cv.boundingRect(contour)
		
		# draw ractangle around detected objects
		cv.rectangle(image, (x, y), (x+w, y+h), (0,255,255), 5)	# zluta
		
	return(thresh_image, image)
			
# convert color to print
def convert_color(image):
	RGB_detected_signs = cv.cvtColor(image, cv.COLOR_BGR2RGB)
	return(RGB_detected_signs)
	
# print results
def print_images(thresh_image, RGB_detected_signs, thresh_method):
	plt.figure('Shape based detection')
	plt.subplot(121),plt.imshow(thresh_image, cmap='gray')
	plt.title('Thresh image'), plt.xticks([]), plt.yticks([])
	plt.subplot(122),plt.imshow(RGB_detected_signs)
	plt.title('Detected signs'), plt.xticks([]), plt.yticks([])
	plt.suptitle(thresh_method)
	plt.show()

# thresh_methods
thresh_methods = ['cv.THRESH_BINARY', 'cv.THRESH_BINARY_INV', 'cv.THRESH_TOZERO', 'cv.THRESH_TOZERO_INV']
thresh_values = ['15', '30', '45', '60', '75', '90','105', '120', 'cv.THRESH_OTSU', 'cv.THRESH_TRIANGLE']
			
# run testing images with different thresh methods

for thresh_method in thresh_methods:
	print(thresh_method)
	method = eval(thresh_method)
	for thresh_value in thresh_values:
		images = load_images()
		for image in images:
			begin = time()
			thresh_image, image = shape_detection(image, method, thresh_value)
			print('cas detekce = ', (time() - begin) * 1000, '[ms]')
			RGB_detected_signs = convert_color(image)
			print_images(thresh_image, RGB_detected_signs, thresh_method)
			
	
  
	
			
