#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 5.6
#  in conjunction with Tcl version 8.6
#    Nov 17, 2020 09:15:35 AM IST  platform: Windows NT

import sys
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import cv2
from tkinter import filedialog
from collections import Counter
import statistics
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

import newCropmanagement_support

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = tk.Tk()
    top = Land_area_detector (root)
    newCropmanagement_support.init(root, top)
    root.mainloop()

w = None
def create_Land_area_detector(rt, *args, **kwargs):
    '''Starting point when module is imported by another module.
       Correct form of call: 'create_Land_area_detector(root, *args, **kwargs)' .'''
    global w, w_win, root
    #rt = root
    root = rt
    w = tk.Toplevel (root)
    top = Land_area_detector (w)
    newCropmanagement_support.init(w, top, *args, **kwargs)
    return (w, top)

def destroy_Land_area_detector():
    global w
    w.destroy()
    w = None

class Land_area_detector:

    def OpenFile(self):
        filename = filedialog.askopenfilename()
        image = cv2.imread(filename)
        imageRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        plt.imshow(imageRGB)
        plt.show()
        return filename

    def landArea(self):
        filename = filedialog.askopenfilename()
        image = cv2.imread(filename)
        imageRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        medianBlur = cv2.medianBlur(imageGray, 3)

        v = np.median(medianBlur)
        sigma = 0.33
        lower_thresh = int(max(0, (1 - sigma) * v))
        upper_thresh = int(min(255, (1 + sigma) * v))
        edges = cv2.Canny(image, lower_thresh, upper_thresh)
        dialte = cv2.dilate(edges, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)))
        contours, hierarchy = cv2.findContours(dialte, 1, 2)
        print("no of contours found= " + str(len(contours)))
        number = 0
        areas = []

        for contour in contours:
            area = cv2.contourArea(contour)
            areas.append(area)

        mean = statistics.mean(areas)
        for area in areas:
            if (area > mean):
                number = number + 1
                print(area)
                print("Area of land: " + str(area * 400) + "sqKm")
                self.Areas.insert(number, area)
        self.NoOfPlots.insert(1, number)

    def cropHealthMeasure(self):
        def RGB2HEX(color):
            return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

        filename = filedialog.askopenfilename()
        image = cv2.imread(filename)
        imageRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        modified_image = cv2.resize(imageRGB, (600, 400), interpolation=cv2.INTER_AREA)
        modified_image = modified_image.reshape(modified_image.shape[0] * modified_image.shape[1], 3)
        clf = KMeans(n_clusters=8)
        labels = clf.fit_predict(modified_image)
        counts = Counter(labels)
        center_colors = clf.cluster_centers_
        ordered_colors = [center_colors[i] for i in counts.keys()]
        hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
        rgb_colors = [ordered_colors[i] for i in counts.keys()]
        plt.figure(figsize=(8, 6))
        plt.pie(counts.values(), colors=hex_colors, autopct='%.1f%%')
        plt.show()
        plt.savefig("pie.png")
        return rgb_colors
    def displayScale(self):
        image=cv2.imread("C:\\Users\\poornima\\Documents\\cs\\cs314\\project\\images\\1280px-NDVI_062003.png")
        imageRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        img_res = imageRGB[733:839, 196:1085]
        img_resBgr = cv2.cvtColor(img_res, cv2.COLOR_RGB2BGR)
        cv2.imshow("scale", img_resBgr)
        cv2.imwrite("scale.jpg",img_resBgr)
        return img_resBgr


    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'

        top.geometry("971x734+397+163")
        top.minsize(148, 1)
        top.maxsize(1924, 1055)
        top.resizable(1,  1)
        top.title("Land Area ")
        top.configure(background="#11fd58")

        self.OprnFile = tk.Button(top)
        self.OprnFile.place(relx=0.033, rely=0.044, height=33, width=86)
        self.OprnFile.configure(activebackground="#ececec")
        self.OprnFile.configure(activeforeground="#000000")
        self.OprnFile.configure(background="#67cf74")
        self.OprnFile.configure(disabledforeground="#a3a3a3")
        self.OprnFile.configure(font="-family {Segoe UI} -size 10")
        self.OprnFile.configure(foreground="#000000")
        self.OprnFile.configure(highlightbackground="#d9d9d9")
        self.OprnFile.configure(highlightcolor="black")
        self.OprnFile.configure(pady="0")
        self.OprnFile.configure(text='''Open File''')
        self.OprnFile.configure(command=self.OpenFile)

        self.LandArea = tk.Button(top)
        self.LandArea.place(relx=0.031, rely=0.163, height=43, width=126)
        self.LandArea.configure(activebackground="#ececec")
        self.LandArea.configure(activeforeground="#000000")
        self.LandArea.configure(background="#4be45f")
        self.LandArea.configure(disabledforeground="#a3a3a3")
        self.LandArea.configure(foreground="#000000")
        self.LandArea.configure(highlightbackground="#d9d9d9")
        self.LandArea.configure(highlightcolor="black")
        self.LandArea.configure(pady="0")
        self.LandArea.configure(text='''Find Land Area''')
        self.LandArea.configure(command=self.landArea)
        self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
        top.configure(menu = self.menubar)

        self.Areas = tk.Listbox(top)
        self.Areas.place(relx=0.227, rely=0.272, relheight=0.229, relwidth=0.302)

        self.Areas.configure(background="white")
        self.Areas.configure(disabledforeground="#a3a3a3")
        self.Areas.configure(font="TkFixedFont")
        self.Areas.configure(foreground="#000000")

        self.cropHealth = tk.Button(top)
        self.cropHealth.place(relx=0.072, rely=0.531, height=43, width=126)
        self.cropHealth.configure(activebackground="#ececec")
        self.cropHealth.configure(activeforeground="#000000")
        self.cropHealth.configure(background="#70e747")
        self.cropHealth.configure(disabledforeground="#a3a3a3")
        self.cropHealth.configure(foreground="#000000")
        self.cropHealth.configure(highlightbackground="#d9d9d9")
        self.cropHealth.configure(highlightcolor="black")
        self.cropHealth.configure(pady="0")
        self.cropHealth.configure(text='''Find Crop health''')
        self.cropHealth.configure(command=self.cropHealthMeasure)

        self.scale = tk.Button(top)
        self.scale.place(relx=0.731, rely=0.545, height=43, width=96)
        self.scale.configure(activebackground="#ececec")
        self.scale.configure(activeforeground="#000000")
        self.scale.configure(background="#7ef35c")
        self.scale.configure(cursor="fleur")
        self.scale.configure(disabledforeground="#a3a3a3")
        self.scale.configure(foreground="#000000")
        self.scale.configure(highlightbackground="#d9d9d9")
        self.scale.configure(highlightcolor="black")
        self.scale.configure(pady="0")
        self.scale.configure(text='''Display scale''')
        self.scale.configure(command=self.displayScale)
        self.NoOfPlots = tk.Listbox(top)
        self.NoOfPlots.place(relx=0.371, rely=0.163, relheight=0.049
                , relwidth=0.135)
        self.NoOfPlots.configure(background="white")
        self.NoOfPlots.configure(disabledforeground="#a3a3a3")
        self.NoOfPlots.configure(font="TkFixedFont")
        self.NoOfPlots.configure(foreground="#000000")

        self.Label1 = tk.Label(top)
        self.Label1.place(relx=0.185, rely=0.163, height=33, width=170)
        self.Label1.configure(background="#caf3be")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(text='''No of Land Plots''')

        self.Label2 = tk.Label(top)
        self.Label2.place(relx=0.021, rely=0.286, height=34, width=190)
        self.Label2.configure(background="#b9f9bb")
        self.Label2.configure(cursor="fleur")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Areas of plots in sqm''')




if __name__ == '__main__':
    vp_start_gui()





