from segmentation import  segment_image,convolve_to_image_UserPaint,merege_small_components
from math_function import smooth_image
import cv2
from PIL import Image
import numpy as np
import tkinter as tk
from tkinter import filedialog
from scipy.misc import toimage
import time

   

print ("Please choose an image to be segmented\n")
# browsing for an image path
root = tk.Tk()
root.withdraw()
input_types= (("JPG File", "*.jpg;*.jpeg*;.jpe*;.jtif"),("TIF File", "*.tif;*.tiff"),("BMP File", "*.bmp;*.dib"),("PNG File", "*.png"),("All Files","*.*"))
image_path = filedialog.askopenfilename(initialdir="../input_image/",filetypes =input_types,title = "Choose an image")
root.destroy()
image_file = Image.open(image_path)
# display the source image
image_file.show()

  
#paramters
sigma = 0.8  #for gausian mask
K = 700     # threshould
parent_component_index=-1 #defult 
comp_min_size =200 # minmom components
   
size = image_file.size
mode= image_file.mode

print ('Image format ',image_file.format)
print ('Image mode ',mode)
print ('Image size ',size)
print ('\n\n')
 
smooth_img=smooth_image(image_file,sigma)
   
   
if mode == 'RGB':
    filter_img = np.dstack(smooth_img) 
    filter_img=toimage(filter_img)
    # show image after gaussian filter for RGB image
    filter_img.show()
    filter_img.save("output_image/img_gaussian.png")

   
algorithm1=False

image,forest,sorted_graph = segment_image(smooth_img, size, K,mode, comp_min_size,algorithm1)

# show image segmentation 
print ("final image\n")
image.show()
image.save("output_image/img_final.png")

 


RED=[0,0,255]
color=BLUE = [255,0,0]

drawing = False         # flag for drawing curves
thickness = 3           # brush thickness

   
def  onmouse(event,x,y,flags,param):
    global img,drawing,color

    # draw touchup curves

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        print ("Press_down\n")
        cv2.circle(img,(x,y),thickness,color,-1)
       

    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing == True: 
            cv2.circle(img,(x,y),thickness,color,-1)
            print ("the_Mouse_is_moving\n")
            

    elif event == cv2.EVENT_LBUTTONUP:
       
        if drawing == True:
            print ("left_mouse\n")
            drawing = False
            cv2.circle(img,(x,y),thickness,color,-1)
    return
 
#open the image after segmntaion, its found in output folder
root = tk.Tk()
root.withdraw()
input_types= (("JPG File", "*.jpg;*.jpeg*;.jpe*;.jtif"),("TIF File", "*.tif;*.tiff"),("BMP File", "*.bmp;*.dib"),("PNG File", "*.png"),("All Files","*.*"))
image_path = filedialog.askopenfilename(initialdir="../input_image/",filetypes =input_types,title = "Choose an image")
root.destroy()   
    
img = cv2.imread(image_path)
# input windows
cv2.namedWindow('input')
cv2.setMouseCallback('input',onmouse)
cv2.moveWindow('input',img.shape[1]+10,90)
parent_component_BLUE=-1
parent_component_RED=-2

while(1):

 
    cv2.imshow('input',img)
 
    k = 0xFF & cv2.waitKey(1)
   
    if k == ord('r'): #color=red
       print ("change color to RED\n")
       color=RED
       
    if k==ord('b') :#color = Blue
       print ("change color to BLUE\n")
       color=BLUE

    if k == ord('u'): # merge conponent that user paint
        indexed = np.array(img)       
        height=size[0]
        width=size[1]
        for y in range(height):
            for x in range(width):
                 if(indexed[x][y][0]==255):
                    print(x,y,"blue")
                    forest.nodes[forest.nodes[y * width + x].parent].parent_component=parent_component_BLUE
                 elif(indexed[x][y][2]==255):
                    print(x,y,"red")
                    print(x,y,forest.nodes[forest.nodes[y * width + x].parent].parent)
                    forest.nodes[forest.nodes[y * width + x].parent].parent_component=parent_component_RED
                    print(x,y,forest.nodes[forest.nodes[y * width + x].parent].parent)

        
        img_user=convolve_to_image_UserPaint(forest,size)
        img_user.show()

    if k == ord('m'):   #merge small conponot ,Paramter min_size
        
        img_merge=merege_small_components(forest, sorted_graph, comp_min_size,size)
        img_merge.show()

    
    if k == 27:     # esc to exit
        print ("Thanks for choosing Majed segmentation services \n")
        cv2.destroyAllWindows()
        time.sleep(2)
        break




