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  # 全局变量，用于存储已选择的图像
X = None  # 用于存储第一张图像
Y = None  # 用于存储第二张图像
img_label = None  # 全局变量，用于存储显示选择的图片的标签
edge = None

GraylineWin = None
GraylogWin = None
EqualWin = None
RegulWin = 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 line_tra(root):
    global src, GraylineWin, edge

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

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

    a = 20
    b = 241
    c = 0
    d = 255

    result = (d - c) / (b - a) * gray_src + (b * c - a * d) / (b - a)

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

    # 创建 Toplevel 窗口
    try:
        GraylineWin.destroy()
    except Exception:
        print("NVM")
    finally:
        GraylineWin = Toplevel()
        GraylineWin.attributes('-topmost', True)
    GraylineWin.geometry("360x300")
    GraylineWin.resizable(True, True)  # 可缩放
    GraylineWin.title("线性变换结果")

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

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

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

    return

# 对数变换
def log_tra(root):
    global src, GraylogWin, edge

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

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

    C = 255 / np.log(1 + 255)

    result = np.array(C * np.log(1 + gray_src), np.float64)

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

    # 创建 Toplevel 窗口
    try:
        GraylogWin.destroy()
    except Exception:
        print("NVM")
    finally:
        GraylogWin = Toplevel()
        GraylogWin.attributes('-topmost', True)
    GraylogWin.geometry("360x300")
    GraylogWin.resizable(True, True)  # 可缩放
    GraylogWin.title("对数变换结果")

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

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

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

    return

# 直方图均衡化
def equal(root):
    global src, EqualWin, edge

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

    # 转变图像为灰度图
    gray_src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

    # 保存原始图像尺寸
    original_size = gray_src.shape

    # 图像放缩到 256 x 256
    gray_src_resized = cv2.resize(gray_src, (256, 256))

    # 图像的直方图
    hist = cv2.calcHist([gray_src_resized], [0], None, [256], [0, 256])

    # 灰度图均衡化
    equ_resized = cv2.equalizeHist(gray_src_resized)

    # 恢复均衡化后的图像到原始尺寸
    equ = cv2.resize(equ_resized, (original_size[1], original_size[0]))

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

    # 创建 Toplevel 窗口
    try:
        EqualWin.destroy()
    except Exception as e:
        print("NVM")
    finally:
        EqualWin = Toplevel()
        EqualWin.attributes('-topmost', True)
    EqualWin.geometry("360x300")
    EqualWin.resizable(True, True)  # 可缩放
    EqualWin.title("直方图均衡化结果")

    # 显示图像
    LabelPic = tk.Label(EqualWin, text="IMG", width=720, height=480)
    image = ImageTk.PhotoImage(Image.fromarray(equ))
    LabelPic.image = image
    LabelPic['image'] = image

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

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

    return

# 直方图正规化
def regul(root):
    global src, X, Y, RegulWin, img_label_ori, img_label_dst,edge

    def select_ori_image():
        global X, img_label_ori, src
        RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
        img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")], parent=RegulWin)
        RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性
        if img_path:
            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("错误", "无法读取图片，请选择有效的图片路径")
                RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
                RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性

            src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2GRAY)
            img = Image.open(img_path)
            img.thumbnail((100, 100))
            img_tk = ImageTk.PhotoImage(img)
            img_label_ori.configure(image=img_tk)
            img_label_ori.image = img_tk
        else:
            messagebox.showerror("错误", "没有选择图片路径")
            RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
            RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性
        X = src.copy()

    def select_dst_image():
        global Y, img_label_dst, src
        RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
        img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")], parent=RegulWin)
        RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性
        if img_path:
            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("错误", "无法读取图片，请选择有效的图片路径")
                RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
                RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性

            src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2GRAY)
            img = Image.open(img_path)
            img.thumbnail((100, 100))
            img_tk = ImageTk.PhotoImage(img)
            img_label_dst.configure(image=img_tk)
            img_label_dst.image = img_tk
        else:
            messagebox.showerror("错误", "没有选择图片路径")
            RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
            RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性
        Y = src.copy()

    def perform_operation():
        global jmin
        RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
        RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性
        if X is None or Y is None:
            messagebox.showerror("错误", "请选择两张图片")
            RegulWin.attributes('-topmost', True)  # 设置窗口为最上层
            RegulWin.attributes('-topmost', False)  # 恢复窗口最上层属性
            return

        # 调整Y图像的尺寸和通道数与X一致
        Y_resized = cv2.resize(Y, (X.shape[1], X.shape[0]))
        if len(X.shape) != len(Y_resized.shape):
            if len(X.shape) == 2:
                Y_resized = cv2.cvtColor(Y_resized, cv2.COLOR_BGR2GRAY)
            else:
                Y_resized = cv2.cvtColor(Y_resized, cv2.COLOR_GRAY2BGR)

        mHist1 = []
        mNum1 = []
        inhist1 = []
        mHist2 = []
        mNum2 = []
        inhist2 = []

        # 对原图像进行均衡化
        for i in range(256):
            mHist1.append(0)

        # 获取原图像像素点的宽度和高度
        row, col = X.shape
        for i in range(row):
            for j in range(col):
                mHist1[X[i, j]] = mHist1[X[i, j]] + 1  # 统计灰度值的个数
        mNum1.append(mHist1[0] / X.size)
        for i in range(0, 255):
            mNum1.append(mNum1[i] + mHist1[i + 1] / X.size)
        for i in range(256):
            inhist1.append(round(255 * mNum1[i]))

        # 对目标图像进行均衡化
        for i in range(256):
            mHist2.append(0)

        # 获取目标图像像素点的宽度和高度
        rows, cols = Y.shape
        for i in range(rows):
            for j in range(cols):
                mHist2[Y[i, j]] = mHist2[Y[i, j]] + 1
        mNum2.append(mHist2[0] / Y.size)
        for i in range(0, 255):
            mNum2.append(mNum2[i] + mHist2[i + 1] / Y.size)
        for i in range(256):
            inhist2.append(round(255 * mNum2[i]))

        # 进行规定化
        # 用于放入规定化后的图片像素
        g = []
        for i in range(256):
            a = inhist1[i]
            flag = True
            for j in range(256):
                if inhist2[j] == a:
                    g.append(j)
                    flag = False
                    break
            if flag == True:
                minp = 255
                for j in range(256):
                    b = abs(inhist2[j] - a)
                    if b < minp:
                        minp = b
                        jmin = j
                g.append(jmin)
        for i in range(row):
            for j in range(col):
                X[i, j] = g[X[i, j]]

        show_result(X)

    def show_result(result_image):
        global RegulWin, edge  # 更新全局变量 edge
        edge = Image.fromarray(result_image)

        try:
            RegulWin.destroy()
        except Exception as e:
            print("NVM")
        finally:
            RegulWin = Toplevel()
            RegulWin.attributes('-topmost', True)
        RegulWin.geometry("360x300")
        RegulWin.resizable(True, True)
        RegulWin.title("直方图正规化结果")

        LabelPic = tk.Label(RegulWin, text="IMG", width=720, height=240)
        image = ImageTk.PhotoImage(Image.fromarray(result_image))
        LabelPic.image = image
        LabelPic['image'] = image

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

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

    try:
        RegulWin.destroy()
    except Exception as e:
        print("NVM")
    finally:
        RegulWin = Toplevel()
        RegulWin.attributes('-topmost', True)
    RegulWin.geometry("720x480")
    RegulWin.resizable(True, True)
    RegulWin.title("选择图片")

    # 添加两个标签来显示选择的图片
    img_label_ori = tk.Label(RegulWin)
    img_label_ori.pack(pady=10)
    img_label_dst = tk.Label(RegulWin)
    img_label_dst.pack(pady=10)

    btn_select_first = tk.Button(RegulWin, text="选择原图片", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=select_ori_image)
    btn_select_first.pack(pady=10)
    btn_select_second = tk.Button(RegulWin, text="选择目标图片", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=select_dst_image)
    btn_select_second.pack(pady=10)
    btn_add = tk.Button(RegulWin, text="正规化", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=lambda: perform_operation())
    btn_add.pack(pady=10)

    return