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

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

FreqsharWin = 0
AirsharWin = 0

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 select_image(root):
    global img_path, src, img_label

    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
        src = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
    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((200, 200))
    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 freq_shar(root):
    global src, FreqsharWin, edge

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

    def Ideal_HighPassFilter(rows, cols, crow, ccol, D0=40):
        # 创建空白图像以存储滤波结果
        Ideal_HighPass = np.zeros((rows, cols), np.uint8)

        # 计算理想高通滤波器
        for i in range(rows):
            for j in range(cols):
                D = np.sqrt((i - crow) ** 2 + (j - ccol) ** 2)
                if D >= D0:
                    Ideal_HighPass[i, j] = 255

        # 应用滤波器到频域表示
        mask = Ideal_HighPass[:, :, np.newaxis]
        fshift = dft_shift * mask

        # 逆傅里叶变换以获得处理后的图像
        f_ishift = np.fft.ifftshift(fshift)
        img_back = cv2.idft(f_ishift)
        img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])

        # 归一化图像到0-255
        cv2.normalize(img_back, img_back, 0, 255, cv2.NORM_MINMAX)
        img_back = np.uint8(img_back)

        return img_back

    def ButterWorth_HighPassFilter(rows, cols, crow, ccol, D0=40, n=2):
        # 创建空白图像以存储滤波结果
        ButterWorth_HighPass = np.zeros((rows, cols), np.uint8)

        # 计算 Butterworth 高通滤波器
        for i in range(rows):
            for j in range(cols):
                D = np.sqrt((i - crow) ** 2 + (j - ccol) ** 2)
                if D == 0:
                    ButterWorth_HighPass[i, j] = 0  # 如果 D = 0，直接赋值为 0，避免除以零错误
                else:
                    ButterWorth_HighPass[i, j] = 255 / (1 + (D0 / D) ** (2 * n))

        # 应用滤波器到频域表示
        mask = ButterWorth_HighPass[:, :, np.newaxis]
        fshift = dft_shift * mask

        # 逆傅里叶变换以获得处理后的图像
        f_ishift = np.fft.ifftshift(fshift)
        img_back = cv2.idft(f_ishift)
        img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])

        # 归一化图像到0-255
        cv2.normalize(img_back, img_back, 0, 255, cv2.NORM_MINMAX)
        img_back = np.uint8(img_back)

        return img_back

    def Gauss_HighPassFilter(rows, cols, crow, ccol, D0=40):
        # 创建空白图像以存储滤波结果
        Gauss_HighPass = np.zeros((rows, cols), np.uint8)

        # 计算 Gauss 高通滤波器
        for i in range(rows):
            for j in range(cols):
                D = np.sqrt((i - crow) ** 2 + (j - ccol) ** 2)
                Gauss_HighPass[i, j] = 255 * (1 - np.exp(-0.5 * (D ** 2) / (D0 ** 2)))

        # 应用滤波器到频域表示
        mask = Gauss_HighPass[:, :, np.newaxis]
        fshift = dft_shift * mask

        # 逆傅里叶变换以获得平滑后的图像
        f_ishift = np.fft.ifftshift(fshift)
        img_back = cv2.idft(f_ishift)
        img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])

        # 归一化图像到0-255
        cv2.normalize(img_back, img_back, 0, 255, cv2.NORM_MINMAX)
        img_back = np.uint8(img_back)

        return img_back

    # 读取灰度图像
    im = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

    # 获取图像尺寸
    rows, cols = im.shape
    crow, ccol = rows // 2, cols // 2  # 中心位置

    # 获取图像的频域表示
    dft = cv2.dft(np.float32(im), flags=cv2.DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)

    # 理想高通滤波器
    Ideal_HighPass = Ideal_HighPassFilter(rows, cols, crow, ccol)
    # 巴特沃斯高通滤波器
    ButterWorth_HighPass = ButterWorth_HighPassFilter(rows, cols, crow, ccol)
    # 高斯高通滤波器
    Gauss_HighPass = Gauss_HighPassFilter(rows, cols, crow, ccol)

    combined = np.hstack((Ideal_HighPass, ButterWorth_HighPass, Gauss_HighPass))

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

    # 创建Toplevel窗口
    try:
        FreqsharWin.destroy()
    except Exception as e:
        print("NVM")
    finally:
        FreqsharWin = Toplevel()
        FreqsharWin.attributes('-topmost', True)
    FreqsharWin.geometry("720x300")
    FreqsharWin.resizable(True, True)  # 可缩放
    FreqsharWin.title("频域锐化结果")

    # 显示图像
    LabelPic = tk.Label(FreqsharWin, text="IMG", width=720, 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(FreqsharWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
                         command=savefile)
    btn_save.pack(pady=10)

    return

#空域锐化
def air_shar(root):
    global src, AirsharWin, edge

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

    def Roberts(Image_In, height, width):
        # 创建输出图像
        Roberts = np.zeros((height - 1, width - 1), dtype=np.uint8)

        # 进行Roberts边缘检测
        for i in range(height - 1):
            for j in range(width - 1):
                tmp = abs(int(Image_In[i + 1, j + 1]) - int(Image_In[i, j])) + abs(
                    int(Image_In[i + 1, j]) - int(Image_In[i, j + 1]))
                tmp = max(0, min(255, tmp))  # 确保结果在0到255之间
                Roberts[i, j] = tmp

        return Roberts

    def Sobel(Image_In, height, width):
        # 创建输出图像
        Image_Sobel = np.zeros((height - 2, width - 2), dtype=np.uint8)

        # 进行Sobel边缘检测
        for i in range(1, height - 1):
            for j in range(1, width - 1):
                # 使用Sobel算子计算水平和垂直方向的梯度
                tmp1 = abs(-int(Image_In[i - 1, j - 1]) - 2 * int(Image_In[i - 1, j]) - int(Image_In[i - 1, j + 1]) +
                           int(Image_In[i + 1, j - 1]) + 2 * int(Image_In[i + 1, j]) + int(Image_In[i + 1, j + 1]))
                tmp2 = abs(-int(Image_In[i - 1, j - 1]) - 2 * int(Image_In[i, j - 1]) - int(Image_In[i + 1, j - 1]) +
                           int(Image_In[i - 1, j + 1]) + 2 * int(Image_In[i, j + 1]) + int(Image_In[i + 1, j + 1]))
                tmp = tmp1 + tmp2
                tmp = max(0, min(255, tmp))  # 确保结果在0到255之间
                Image_Sobel[i - 1, j - 1] = tmp

        return Image_Sobel

    def Prewitt(Image_In, height, width):
        # 创建输出图像
        Image_Prewitt = np.zeros((height - 2, width - 2), dtype=np.uint8)

        # 进行Prewitt边缘检测
        for i in range(1, height - 1):
            for j in range(1, width - 1):
                # 使用Prewitt算子计算水平和垂直方向的梯度
                tmp1 = abs(-int(Image_In[i - 1, j - 1]) - int(Image_In[i - 1, j]) - int(Image_In[i - 1, j + 1]) +
                           int(Image_In[i + 1, j - 1]) + int(Image_In[i + 1, j]) + int(Image_In[i + 1, j + 1]))
                tmp2 = abs(-int(Image_In[i - 1, j - 1]) - int(Image_In[i, j - 1]) - int(Image_In[i + 1, j - 1]) +
                           int(Image_In[i - 1, j + 1]) + int(Image_In[i, j + 1]) + int(Image_In[i + 1, j + 1]))
                tmp = tmp1 + tmp2
                tmp = max(0, min(255, tmp))  # 确保结果在0到255之间
                Image_Prewitt[i - 1, j - 1] = tmp

        return Image_Prewitt

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

    # 获取图像的尺寸
    height, width = im.shape

    # Roberts
    Rob = Roberts(im, height, width)
    # Sobel
    Sob = Sobel(im, height, width)
    # Prewitt
    Pre = Prewitt(im, height, width)
    # # Laplacian
    # Lap = Laplacian(im, height, width)

    # 找出最小的尺寸
    min_height = min(Rob.shape[0], Sob.shape[0], Pre.shape[0])
    min_width = min(Rob.shape[1], Sob.shape[1], Pre.shape[1])

    # 对所有结果进行裁剪，使它们的尺寸一致
    Rob = Rob[:min_height, :min_width]
    Sob = Sob[:min_height, :min_width]
    Pre = Pre[:min_height, :min_width]
    # Lap = Lap[:min_height, :min_width]

    combined = np.hstack((Rob, Sob, Pre))

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

    # 创建Toplevel窗口
    try:
        AirsharWin.destroy()
    except Exception as e:
        print("NVM")
    finally:
        AirsharWin = Toplevel()
        AirsharWin.attributes('-topmost', True)
    AirsharWin.geometry("720x300")
    AirsharWin.resizable(True, True)  # 可缩放
    AirsharWin.title("空域锐化结果")

    # 显示图像
    LabelPic = tk.Label(AirsharWin, text="IMG", width=720, 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(AirsharWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
                         command=savefile)
    btn_save.pack(pady=10)

    return