import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import Toplevel
from PIL import Image, ImageTk
import numpy as np
import math
import cv2
import os

img_path = ""  # 全局变量，用于存储图像路径
src = None  # 全局变量，用于存储已选择的图像
X = None  # 用于存储第一张图像
Y = None  # 用于存储第二张图像
img_label = None  # 全局变量，用于存储显示选择的图片的标签

GeomeanWin = None
SortstatWin = None
SelectWin = None

def select_image(root):
    global img_path, src, img_label, edge

    img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.bmp")])
    if img_path:
        # 确保路径中的反斜杠正确处理，并使用 UTF-8 编码处理中文路径
        img_path_fixed = os.path.normpath(img_path)

        # 图像输入
        src_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
        if src_temp is None:
            messagebox.showerror("错误", "无法读取图片，请选择有效的图片路径")
            return
        src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2RGB)

        # 检查 img_label 是否存在且有效
        if img_label is None or not img_label.winfo_exists():
            img_label = tk.Label(root)
            img_label.pack(side=tk.TOP, pady=10)

        img = Image.open(img_path)
        img.thumbnail((160, 160))
        img_tk = ImageTk.PhotoImage(img)
        img_label.configure(image=img_tk)
        img_label.image = img_tk

        # 定义 edge 变量为 PIL.Image 对象，以便稍后保存
        edge = Image.fromarray(src)
    else:
        messagebox.showerror("错误", "没有选择图片路径")

def show_selected_image(root):
    global img_label
    img_label = tk.Label(root)
    img_label.pack(side=tk.TOP, pady=10)
    img = Image.open(img_path)
    img.thumbnail((160, 160))
    img_tk = ImageTk.PhotoImage(img)
    img_label.configure(image=img_tk)
    img_label.image = img_tk

def changeSize(event, img, LabelPic):
    img_aspect = img.shape[1] / img.shape[0]
    new_aspect = event.width / event.height

    if new_aspect > img_aspect:
        new_width = int(event.height * img_aspect)
        new_height = event.height
    else:
        new_width = event.width
        new_height = int(event.width / img_aspect)

    resized_image = cv2.resize(img, (new_width, new_height))
    image1 = ImageTk.PhotoImage(Image.fromarray(resized_image))
    LabelPic.image = image1
    LabelPic['image'] = image1

def savefile():
    global edge

    filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")])
    if not filename:
        return
    # 确保 edge 变量已定义
    if edge is not None:
        try:
            edge.save(filename)
            messagebox.showinfo("保存成功", "图片保存成功！")
        except Exception as e:
            messagebox.showerror("保存失败", f"无法保存图片: {e}")
    else:
        messagebox.showerror("保存失败", "没有图像可保存")

#几何均值滤波
def geo_mean_filter(root):
    global src, GeomeanWin, edge

    # 判断是否已经选取图片
    if src is None:
        messagebox.showerror("错误", "没有选择图片！")
        return

    image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

    # 待输出的图片
    output = np.zeros(image.shape, np.uint8)
    # 遍历图像，进行均值滤波
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            # 计算均值,完成对图片src的几何均值滤波
            ji = 1.0

            # 遍历滤波器内的像素值
            for k in range(-1, 2):
                if 0 <= j + k < image.shape[1]:
                    ji *= image[i, j + k]

            # 滤波器的大小为1*3
            geom_mean = math.pow(ji, 1 / 3.0)
            output[i, j] = int(geom_mean)

    # 更新 edge 变量
    edge = Image.fromarray(output)

    # 创建Toplevel窗口
    try:
        GeomeanWin.destroy()
    except Exception:
        print("NVM")
    finally:
        GeomeanWin = Toplevel()
        GeomeanWin.attributes('-topmost', True)
    GeomeanWin.geometry("720x300")
    GeomeanWin.resizable(True, True)  # 可缩放
    GeomeanWin.title("几何均值滤波结果")

    # 显示图像
    LabelPic = tk.Label(GeomeanWin, text="IMG", width=360, height=240)
    image = ImageTk.PhotoImage(Image.fromarray(output))
    LabelPic.image = image
    LabelPic['image'] = image

    LabelPic.bind('<Configure>', lambda event: changeSize(event, output, LabelPic))
    LabelPic.pack(fill=tk.BOTH, expand=tk.YES)

    # 添加保存按钮
    btn_save = tk.Button(GeomeanWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
                         command=savefile)
    btn_save.pack(pady=10)

    return

#排序统计类滤波
def sort_stat_filter(root):
    global src, SortstatWin, combined, edge

    # 判断是否已经选取图片
    if src is None:
        messagebox.showerror("错误", "没有选择图片！")
        return

    image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

    # 待输出的图片
    output_max = np.zeros(image.shape, np.uint8)
    output_median = np.zeros(image.shape, np.uint8)
    output_min = np.zeros(image.shape, np.uint8)

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            # 用于存储3x3邻域像素值
            neighbors = []
            for m in range(-1, 2):
                for n in range(-1, 2):
                    if 0 <= i + m < image.shape[0] and 0 <= j + n < image.shape[1]:
                        neighbors.append(image[i + m, j + n])

            # 最大值滤波
            output_max[i, j] = max(neighbors)

            # 中值滤波
            output_median[i, j] = np.median(neighbors)

            # 最小值滤波
            output_min[i, j] = min(neighbors)

            combined = np.hstack((output_max, output_median, output_min))

    # 更新 edge 变量
    edge = Image.fromarray(combined)

    # 创建Toplevel窗口
    try:
        SortstatWin.destroy()
    except Exception:
        print("NVM")
    finally:
        SortstatWin = Toplevel()
        SortstatWin.attributes('-topmost', True)
    SortstatWin.geometry("720x300")
    SortstatWin.resizable(True, True)  # 可缩放
    SortstatWin.title("排序统计类滤波结果")

    # 显示图像
    LabelPic = tk.Label(SortstatWin, text="IMG", width=360, height=240)
    image = ImageTk.PhotoImage(Image.fromarray(combined))
    LabelPic.image = image
    LabelPic['image'] = image

    LabelPic.bind('<Configure>', lambda event: changeSize(event, combined, LabelPic))
    LabelPic.pack(fill=tk.BOTH, expand=tk.YES)

    # 添加保存按钮
    btn_save = tk.Button(SortstatWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
                         command=savefile)
    btn_save.pack(pady=10)

    return

#选择性滤波
def selective_filter(root):
    global src, SelectWin, combined, edge

    # 判断是否已经选取图片
    if src is None:
        messagebox.showerror("错误", "没有选择图片！")
        return

    image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

    # 待输出的图片
    output_low_pass = np.zeros(image.shape, np.uint8)
    output_high_pass = np.zeros(image.shape, np.uint8)
    output_band_pass = np.zeros(image.shape, np.uint8)
    output_band_stop = np.zeros(image.shape, np.uint8)

    # 边界
    low_pass_threshold = 100
    high_pass_threshold = 100
    band_pass_low_threshold = 100
    band_pass_high_threshold = 200
    band_stop_low_threshold = 100
    band_stop_high_threshold = 200

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            pixel_value = image[i][j]

            # 低通滤波器
            if pixel_value <= low_pass_threshold:
                output_low_pass[i][j] = pixel_value
            else:
                output_low_pass[i][j] = 0

            # 高通滤波器
            if pixel_value >= high_pass_threshold:
                output_high_pass[i][j] = pixel_value
            else:
                output_high_pass[i][j] = 0

            # 带通滤波器
            if band_pass_low_threshold < pixel_value <= band_pass_high_threshold:
                output_band_pass[i][j] = pixel_value
            else:
                output_band_pass[i][j] = 0

            # 带阻滤波器
            if band_stop_low_threshold < pixel_value <= band_stop_high_threshold:
                output_band_stop[i][j] = 0
            else:
                output_band_stop[i][j] = pixel_value

        combined = np.hstack((output_low_pass, output_high_pass, output_band_pass, output_band_stop))

    # 更新 edge 变量
    edge = Image.fromarray(combined)

    # 创建Toplevel窗口
    try:
        SelectWin.destroy()
    except Exception:
        print("NVM")
    finally:
        SelectWin = Toplevel()
        SelectWin.attributes('-topmost', True)
    SelectWin.geometry("720x300")
    SelectWin.resizable(True, True)  # 可缩放
    SelectWin.title("选择性滤波结果")

    # 显示图像
    LabelPic = tk.Label(SelectWin, text="IMG", width=360, height=240)
    image = ImageTk.PhotoImage(Image.fromarray(combined))
    LabelPic.image = image
    LabelPic['image'] = image

    LabelPic.bind('<Configure>', lambda event: changeSize(event, combined, LabelPic))
    LabelPic.pack(fill=tk.BOTH, expand=tk.YES)

    # 添加保存按钮
    btn_save = tk.Button(SelectWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
                         command=savefile)
    btn_save.pack(pady=10)

    return