Update basic_process.py

main
pos97em56 5 months ago
parent bc48aac6c6
commit 38ce87d8bc

@ -1,351 +1,338 @@
import tkinter as tk import tkinter as tk
from tkinter import filedialog, messagebox, Toplevel from tkinter import filedialog, messagebox, Toplevel
from PIL import Image, ImageTk from PIL import Image, ImageTk
import numpy as np import numpy as np
import cv2 import cv2
import os import os
# 全局变量声明 # 全局变量声明
img_path = "" # 用于存储图像路径 img_path = "" # 用于存储图像路径
src = None # 用于存储已选择的图像 src = None # 用于存储已选择的图像
X = None # 用于存储第一张图像 X = None # 用于存储第一张图像
Y = None # 用于存储第二张图像 Y = None # 用于存储第二张图像
img_label = None # 用于存储显示选择的图片的标签 img_label = None # 用于存储显示选择的图片的标签
edge = None # 用于存储当前处理后的图像 edge = None # 用于存储当前处理后的图像
# 用于不同功能的Toplevel窗口 # 用于不同功能的Toplevel窗口
AffineWin = None AffineWin = None
TurnWin = None TurnWin = None
ArithWin = None ArithWin = None
def select_image(root): def select_image(root):
""" """
选择图像并显示在主窗口中 选择图像并显示在主窗口中
""" """
global img_path, src, img_label, edge global img_path, src, img_label, edge
# 打开文件对话框选择图像文件 # 打开文件对话框选择图像文件
img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.bmp")]) img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.bmp")])
if img_path: if img_path:
# 处理图像路径以确保反斜杠正确处理并使用UTF-8编码处理中文路径 # 处理图像路径以确保反斜杠正确处理并使用UTF-8编码处理中文路径
img_path_fixed = os.path.normpath(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) src_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
if src_temp is None: if src_temp is None:
messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径") messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径")
return return
src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2RGB) src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2RGB)
# 检查 img_label 是否存在且有效 # 检查 img_label 是否存在且有效
if img_label is None or not img_label.winfo_exists(): if img_label is None or not img_label.winfo_exists():
img_label = tk.Label(root) img_label = tk.Label(root)
img_label.pack(side=tk.TOP, pady=10) img_label.pack(side=tk.TOP, pady=10)
# 显示缩略图 # 显示缩略图
img = Image.open(img_path) img = Image.open(img_path)
img.thumbnail((160, 160)) img.thumbnail((160, 160))
img_tk = ImageTk.PhotoImage(img) img_tk = ImageTk.PhotoImage(img)
img_label.configure(image=img_tk) img_label.configure(image=img_tk)
img_label.image = img_tk img_label.image = img_tk
# 更新 edge 变量为 PIL.Image 对象,以便稍后保存 # 更新 edge 变量为 PIL.Image 对象,以便稍后保存
edge = Image.fromarray(src) edge = Image.fromarray(src)
else: else:
messagebox.showerror("错误", "没有选择图片路径") messagebox.showerror("错误", "没有选择图片路径")
def show_selected_image(root): def changeSize(event, img, LabelPic):
""" """
显示选定的图像 根据窗口大小调整图像大小
""" """
global img_label img_aspect = img.shape[1] / img.shape[0] # 计算图像的宽高比
img_label = tk.Label(root) new_aspect = event.width / event.height # 计算窗口的新宽高比
img_label.pack(side=tk.TOP, pady=10)
img = Image.open(img_path) if new_aspect > img_aspect:
img.thumbnail((160, 160)) new_width = int(event.height * img_aspect) # 根据新高度计算新宽度
img_tk = ImageTk.PhotoImage(img) new_height = event.height # 使用新高度
img_label.configure(image=img_tk) else:
img_label.image = img_tk new_width = event.width # 使用新宽度
new_height = int(event.width / img_aspect) # 根据新宽度计算新高度
def changeSize(event, img, LabelPic):
""" resized_image = cv2.resize(img, (new_width, new_height)) # 调整图像大小
根据窗口大小调整图像大小 image1 = ImageTk.PhotoImage(Image.fromarray(resized_image))
""" LabelPic.image = image1
img_aspect = img.shape[1] / img.shape[0] # 计算图像的宽高比 LabelPic['image'] = image1
new_aspect = event.width / event.height # 计算窗口的新宽高比
def savefile():
if new_aspect > img_aspect: """
new_width = int(event.height * img_aspect) # 根据新高度计算新宽度 保存处理后的图像文件
new_height = event.height # 使用新高度 """
else: global edge
new_width = event.width # 使用新宽度
new_height = int(event.width / img_aspect) # 根据新宽度计算新高度 # 打开保存文件对话框
filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")])
resized_image = cv2.resize(img, (new_width, new_height)) # 调整图像大小 if not filename:
image1 = ImageTk.PhotoImage(Image.fromarray(resized_image)) return
LabelPic.image = image1 if edge is not None:
LabelPic['image'] = image1 try:
edge.save(filename)
def savefile(): messagebox.showinfo("保存成功", "图片保存成功!")
""" except Exception as e:
保存处理后的图像文件 messagebox.showerror("保存失败", f"无法保存图片: {e}")
""" else:
global edge messagebox.showerror("保存失败", "没有图像可保存")
# 打开保存文件对话框 def affine_tra(root):
filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")]) """
if not filename: 对图像进行仿射变换
return """
if edge is not None: global src, AffineWin, edge
try:
edge.save(filename) #判断是否已经选取图片
messagebox.showinfo("保存成功", "图片保存成功!") if src is None:
except Exception as e: messagebox.showerror("错误", "没有选择图片!")
messagebox.showerror("保存失败", f"无法保存图片: {e}") return
else:
messagebox.showerror("保存失败", "没有图像可保存") rows, cols = src.shape[:2] # 获取图像的行和列
def affine_tra(root): # 设置图像仿射变化矩阵
""" post1 = np.float32([[50, 50], [200, 50], [50, 200]])
对图像进行仿射变换 post2 = np.float32([[10, 100], [200, 50], [100, 250]])
""" m = cv2.getAffineTransform(post1, post2)
global src, AffineWin, edge
# 图像仿射变换
#判断是否已经选取图片 result = cv2.warpAffine(src, m, (cols, rows))
if src is None:
messagebox.showerror("错误", "没有选择图片!") # 更新 edge 变量
return edge = Image.fromarray(result)
rows, cols = src.shape[:2] # 获取图像的行和列 # 创建Toplevel窗口
try:
# 设置图像仿射变化矩阵 if AffineWin:
post1 = np.float32([[50, 50], [200, 50], [50, 200]]) AffineWin.destroy()
post2 = np.float32([[10, 100], [200, 50], [100, 250]]) except Exception:
m = cv2.getAffineTransform(post1, post2) print("NVM")
finally:
# 图像仿射变换 AffineWin = Toplevel(root)
result = cv2.warpAffine(src, m, (cols, rows)) AffineWin.attributes('-topmost', True)
AffineWin.geometry("360x300")
# 更新 edge 变量 AffineWin.resizable(True, True)
edge = Image.fromarray(result) AffineWin.title("仿射变换结果")
# 创建Toplevel窗口 # 显示图像
try: LabelPic = tk.Label(AffineWin, text="IMG", width=360, height=240)
if AffineWin: image = ImageTk.PhotoImage(Image.fromarray(result))
AffineWin.destroy() LabelPic.image = image
except Exception: LabelPic['image'] = image
print("NVM")
finally: LabelPic.bind('<Configure>', lambda event: changeSize(event, result, LabelPic))
AffineWin = Toplevel(root) LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
AffineWin.attributes('-topmost', True)
AffineWin.geometry("360x300") # 添加保存按钮
AffineWin.resizable(True, True) btn_save = tk.Button(AffineWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14),
AffineWin.title("仿射变换结果") width=20, command=savefile)
btn_save.pack(pady=10)
# 显示图像
LabelPic = tk.Label(AffineWin, text="IMG", width=360, height=240) def turn(root):
image = ImageTk.PhotoImage(Image.fromarray(result)) """
LabelPic.image = image 对图像进行翻转操作
LabelPic['image'] = image """
global src, TurnWin, edge
LabelPic.bind('<Configure>', lambda event: changeSize(event, result, LabelPic))
LabelPic.pack(fill=tk.BOTH, expand=tk.YES) if src is None:
messagebox.showerror("错误", "没有选择图片!")
# 添加保存按钮 return
btn_save = tk.Button(AffineWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14),
width=20, command=savefile) # 水平镜像
btn_save.pack(pady=10) horizontal = cv2.flip(src, 1)
def turn(root): # 垂直镜像
""" vertical = cv2.flip(src, 0)
对图像进行翻转操作
""" # 对角镜像
global src, TurnWin, edge cross = cv2.flip(src, -1)
if src is None: # 将三种翻转图像组合成一个图像进行显示
messagebox.showerror("错误", "没有选择图片!") combined = np.hstack((horizontal, vertical, cross))
return
# 更新 edge 变量
# 水平镜像 edge = Image.fromarray(combined)
horizontal = cv2.flip(src, 1)
# 创建Toplevel窗口
# 垂直镜像 try:
vertical = cv2.flip(src, 0) if TurnWin:
TurnWin.destroy()
# 对角镜像 except Exception as e:
cross = cv2.flip(src, -1) print("NVM")
finally:
# 将三种翻转图像组合成一个图像进行显示 TurnWin = Toplevel(root)
combined = np.hstack((horizontal, vertical, cross)) TurnWin.attributes('-topmost', True)
TurnWin.geometry("720x300")
# 更新 edge 变量 TurnWin.resizable(True, True)
edge = Image.fromarray(combined) TurnWin.title("翻转结果")
# 创建Toplevel窗口 # 显示图像
try: LabelPic = tk.Label(TurnWin, text="IMG", width=720, height=240)
if TurnWin: image = ImageTk.PhotoImage(Image.fromarray(combined))
TurnWin.destroy() LabelPic.image = image
except Exception as e: LabelPic['image'] = image
print("NVM")
finally: LabelPic.bind('<Configure>', lambda event: changeSize(event, combined, LabelPic))
TurnWin = Toplevel(root) LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
TurnWin.attributes('-topmost', True)
TurnWin.geometry("720x300") # 添加保存按钮
TurnWin.resizable(True, True) btn_save = tk.Button(TurnWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
TurnWin.title("翻转结果") btn_save.pack(pady=10)
# 显示图像 def arithmetic(root):
LabelPic = tk.Label(TurnWin, text="IMG", width=720, height=240) """
image = ImageTk.PhotoImage(Image.fromarray(combined)) 对图像进行算术变换操作
LabelPic.image = image """
LabelPic['image'] = image global src, X, Y, ArithWin, img_label_first, img_label_second, edge
LabelPic.bind('<Configure>', lambda event: changeSize(event, combined, LabelPic)) final = None # 用于存储最终的算术运算结果
LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
def select_first_image():
# 添加保存按钮 """
btn_save = tk.Button(TurnWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile) 选择第一张图像
btn_save.pack(pady=10) """
global X, img_label_first
def arithmetic(root): ArithWin.attributes('-topmost', True) # 设置窗口为最上层
""" img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.bmp;*.jpeg")], parent=ArithWin)
对图像进行算术变换操作 ArithWin.attributes('-topmost', False) # 恢复窗口最上层属性
""" if img_path:
global src, X, Y, ArithWin, img_label_first, img_label_second, edge img_path_fixed = os.path.normpath(img_path)
img_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
final = None # 用于存储最终的算术运算结果 if img_temp is None:
messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径")
def select_first_image(): return
"""
选择第一张图像 image = cv2.cvtColor(img_temp, cv2.COLOR_BGR2RGB) # 转换颜色空间
""" img = Image.fromarray(image)
global X, img_label_first img.thumbnail((100, 100)) # 缩略图
ArithWin.attributes('-topmost', True) # 设置窗口为最上层 img_tk = ImageTk.PhotoImage(img)
img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.bmp;*.jpeg")], parent=ArithWin) img_label_first.configure(image=img_tk)
ArithWin.attributes('-topmost', False) # 恢复窗口最上层属性 img_label_first.image = img_tk
if img_path: else:
img_path_fixed = os.path.normpath(img_path) messagebox.showerror("错误", "没有选择图片路径")
img_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED) X = image.copy()
if img_temp is None:
messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径") def select_second_image():
return """
选择第二张图像
image = cv2.cvtColor(img_temp, cv2.COLOR_BGR2RGB) # 转换颜色空间 """
img = Image.fromarray(image) global Y, img_label_second
img.thumbnail((100, 100)) # 缩略图 ArithWin.attributes('-topmost', True) # 设置窗口为最上层
img_tk = ImageTk.PhotoImage(img) img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.bmp;*.jpeg")], parent=ArithWin)
img_label_first.configure(image=img_tk) ArithWin.attributes('-topmost', False) # 恢复窗口最上层属性
img_label_first.image = img_tk if img_path:
else: img_path_fixed = os.path.normpath(img_path)
messagebox.showerror("错误", "没有选择图片路径") img_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
X = image.copy() if img_temp is None:
messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径")
def select_second_image(): return
"""
选择第二张图像 image = cv2.cvtColor(img_temp, cv2.COLOR_BGR2RGB) # 转换颜色空间
""" img = Image.fromarray(image)
global Y, img_label_second img.thumbnail((100, 100)) # 缩略图
ArithWin.attributes('-topmost', True) # 设置窗口为最上层 img_tk = ImageTk.PhotoImage(img)
img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.bmp;*.jpeg")], parent=ArithWin) img_label_second.configure(image=img_tk)
ArithWin.attributes('-topmost', False) # 恢复窗口最上层属性 img_label_second.image = img_tk
if img_path: else:
img_path_fixed = os.path.normpath(img_path) messagebox.showerror("错误", "没有选择图片路径")
img_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED) Y = image.copy()
if img_temp is None:
messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径") def perform_operation(operation):
return """
执行图像算术运算
image = cv2.cvtColor(img_temp, cv2.COLOR_BGR2RGB) # 转换颜色空间 """
img = Image.fromarray(image) nonlocal final
img.thumbnail((100, 100)) # 缩略图 if X is None or Y is None:
img_tk = ImageTk.PhotoImage(img) messagebox.showerror("错误", "请选择两张图片")
img_label_second.configure(image=img_tk) return
img_label_second.image = img_tk
else: # 调整Y图像的尺寸和通道数与X一致
messagebox.showerror("错误", "没有选择图片路径") Y_resized = cv2.resize(Y, (X.shape[1], X.shape[0]))
Y = image.copy() if len(X.shape) != len(Y_resized.shape):
if len(X.shape) == 2:
def perform_operation(operation): Y_resized = cv2.cvtColor(Y_resized, cv2.COLOR_BGR2GRAY)
""" else:
执行图像算术运算 Y_resized = cv2.cvtColor(Y_resized, cv2.COLOR_GRAY2BGR)
"""
nonlocal final if operation == "add":
if X is None or Y is None: final = cv2.add(X, Y_resized)
messagebox.showerror("错误", "请选择两张图片") elif operation == "sub":
return final = cv2.subtract(X, Y_resized)
elif operation == "mult":
# 调整Y图像的尺寸和通道数与X一致 final = cv2.multiply(X, Y_resized)
Y_resized = cv2.resize(Y, (X.shape[1], X.shape[0]))
if len(X.shape) != len(Y_resized.shape): show_result(final)
if len(X.shape) == 2:
Y_resized = cv2.cvtColor(Y_resized, cv2.COLOR_BGR2GRAY) def show_result(result_image):
else: """
Y_resized = cv2.cvtColor(Y_resized, cv2.COLOR_GRAY2BGR) 显示运算结果图像
"""
if operation == "add": global edge # 更新全局变量 edge
final = cv2.add(X, Y_resized) edge = Image.fromarray(result_image)
elif operation == "sub":
final = cv2.subtract(X, Y_resized) result_window = Toplevel(root)
elif operation == "mult": result_window.attributes('-topmost', True)
final = cv2.multiply(X, Y_resized) result_window.geometry("620x480")
result_window.resizable(True, True)
show_result(final) result_window.title("运算结果")
def show_result(result_image): LabelPic = tk.Label(result_window, text="IMG", width=720, height=240)
""" image = ImageTk.PhotoImage(Image.fromarray(result_image))
显示运算结果图像 LabelPic.image = image
""" LabelPic['image'] = image
global edge # 更新全局变量 edge
edge = Image.fromarray(result_image) LabelPic.bind('<Configure>', lambda event: changeSize(event, result_image, LabelPic))
LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
result_window = Toplevel(root)
result_window.attributes('-topmost', True) # 添加保存按钮
result_window.geometry("620x480") btn_save = tk.Button(result_window, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
result_window.resizable(True, True) btn_save.pack(pady=10)
result_window.title("运算结果")
# 创建算术运算窗口
LabelPic = tk.Label(result_window, text="IMG", width=720, height=240) try:
image = ImageTk.PhotoImage(Image.fromarray(result_image)) if ArithWin:
LabelPic.image = image ArithWin.destroy()
LabelPic['image'] = image except Exception as e:
print("NVM")
LabelPic.bind('<Configure>', lambda event: changeSize(event, result_image, LabelPic)) finally:
LabelPic.pack(fill=tk.BOTH, expand=tk.YES) ArithWin = Toplevel(root)
ArithWin.attributes('-topmost', True)
# 添加保存按钮 ArithWin.geometry("720x480")
btn_save = tk.Button(result_window, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile) ArithWin.resizable(True, True)
btn_save.pack(pady=10) ArithWin.title("选择运算类型")
# 创建算术运算窗口 # 添加一个框架来容纳两个图像标签
try: frame = tk.Frame(ArithWin)
if ArithWin: frame.pack(pady=10)
ArithWin.destroy()
except Exception as e: img_label_first = tk.Label(frame)
print("NVM") img_label_first.pack(side=tk.LEFT, padx=10)
finally: img_label_second = tk.Label(frame)
ArithWin = Toplevel(root) img_label_second.pack(side=tk.RIGHT, padx=10)
ArithWin.attributes('-topmost', True)
ArithWin.geometry("720x480") # 添加选择图像和运算按钮
ArithWin.resizable(True, True) btn_select_first = tk.Button(ArithWin, text="选择第一张图片", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=select_first_image)
ArithWin.title("选择运算类型") btn_select_first.pack(pady=10)
btn_select_second = tk.Button(ArithWin, text="选择第二张图片", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=select_second_image)
# 添加一个框架来容纳两个图像标签 btn_select_second.pack(pady=10)
frame = tk.Frame(ArithWin) btn_add = tk.Button(ArithWin, text="加法", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=lambda: perform_operation("add"))
frame.pack(pady=10) btn_add.pack(pady=10)
btn_sub = tk.Button(ArithWin, text="减法", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=lambda: perform_operation("sub"))
img_label_first = tk.Label(frame) btn_sub.pack(pady=10)
img_label_first.pack(side=tk.LEFT, padx=10) btn_mult = tk.Button(ArithWin, text="乘法", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=lambda: perform_operation("mult"))
img_label_second = tk.Label(frame) btn_mult.pack(pady=10)
img_label_second.pack(side=tk.RIGHT, padx=10)
# 添加选择图像和运算按钮
btn_select_first = tk.Button(ArithWin, text="选择第一张图片", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=select_first_image)
btn_select_first.pack(pady=10)
btn_select_second = tk.Button(ArithWin, text="选择第二张图片", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=select_second_image)
btn_select_second.pack(pady=10)
btn_add = tk.Button(ArithWin, text="加法", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=lambda: perform_operation("add"))
btn_add.pack(pady=10)
btn_sub = tk.Button(ArithWin, text="减法", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=lambda: perform_operation("sub"))
btn_sub.pack(pady=10)
btn_mult = tk.Button(ArithWin, text="乘法", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=lambda: perform_operation("mult"))
btn_mult.pack(pady=10)

Loading…
Cancel
Save