Update digital_morphology.py

main
pos97em56 5 months ago
parent 38ce87d8bc
commit 4d549d031f

@ -1,343 +1,330 @@
import tkinter as tk import tkinter as tk
from tkinter import filedialog, messagebox from tkinter import filedialog, messagebox
from tkinter import Toplevel from tkinter import 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 # 用于存储已选择的图像
img_label = None # 用于存储显示选择的图片的标签 img_label = None # 用于存储显示选择的图片的标签
edge = None # 用于存储处理后的图像以便保存 edge = None # 用于存储处理后的图像以便保存
# 用于存储不同窗口的全局变量 # 用于存储不同窗口的全局变量
CorrodeWin = None CorrodeWin = None
DilaWin = None DilaWin = None
OpenWin = None OpenWin = None
CloseWin = None CloseWin = None
def select_image(root): def select_image(root):
""" """
选择并显示图像 选择并显示图像
""" """
global img_path, src, img_label global img_path, src, img_label
# 打开文件选择对话框 # 打开文件选择对话框
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)
# 显示图像 # 显示图像
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
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")])
if not filename:
resized_image = cv2.resize(img, (new_width, new_height)) return
image1 = ImageTk.PhotoImage(Image.fromarray(resized_image)) if edge is not None:
LabelPic.image = image1 try:
LabelPic['image'] = image1 edge.save(filename)
messagebox.showinfo("保存成功", "图片保存成功!")
def savefile(): except Exception as e:
""" messagebox.showerror("保存失败", f"无法保存图片: {e}")
保存处理后的图像 else:
""" messagebox.showerror("保存失败", "没有图像可保存")
global edge
# 腐蚀
filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")]) def corrode(root):
if not filename: """
return 腐蚀操作
if edge is not None: """
try: global src, CorrodeWin, edge
edge.save(filename)
messagebox.showinfo("保存成功", "图片保存成功!") # 判断是否已经选取图片
except Exception as e: if src is None:
messagebox.showerror("保存失败", f"无法保存图片: {e}") messagebox.showerror("错误", "没有选择图片!")
else: return
messagebox.showerror("保存失败", "没有图像可保存")
# 定义结构元素(该处使用矩形3*3结构)
# 腐蚀 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3), anchor=None)
def corrode(root):
""" # 腐蚀图像
腐蚀操作 eroded = cv2.erode(src, kernel)
"""
global src, CorrodeWin, edge # 更新 edge 变量
edge = Image.fromarray(eroded)
# 判断是否已经选取图片
if src is None: # 创建 Toplevel 窗口
messagebox.showerror("错误", "没有选择图片!") try:
return CorrodeWin.destroy()
except Exception:
# 定义结构元素(该处使用矩形3*3结构) print("NVM")
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3), anchor=None) finally:
CorrodeWin = Toplevel(root)
# 腐蚀图像 CorrodeWin.attributes('-topmost', True)
eroded = cv2.erode(src, kernel) CorrodeWin.geometry("360x300")
CorrodeWin.resizable(True, True) # 可缩放
# 更新 edge 变量 CorrodeWin.title("腐蚀结果")
edge = Image.fromarray(eroded)
# 显示图像
# 创建 Toplevel 窗口 LabelPic = tk.Label(CorrodeWin, text="IMG", width=360, height=240)
try: image = ImageTk.PhotoImage(Image.fromarray(eroded))
CorrodeWin.destroy() LabelPic.image = image
except Exception: LabelPic['image'] = image
print("NVM")
finally: LabelPic.bind('<Configure>', lambda event: changeSize(event, eroded, LabelPic))
CorrodeWin = Toplevel(root) LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
CorrodeWin.attributes('-topmost', True)
CorrodeWin.geometry("360x300") # 添加保存按钮
CorrodeWin.resizable(True, True) # 可缩放 btn_save = tk.Button(CorrodeWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
CorrodeWin.title("腐蚀结果") btn_save.pack(pady=10)
# 显示图像 return
LabelPic = tk.Label(CorrodeWin, text="IMG", width=360, height=240)
image = ImageTk.PhotoImage(Image.fromarray(eroded)) # 膨胀
LabelPic.image = image def dilatation(root):
LabelPic['image'] = image """
膨胀操作
LabelPic.bind('<Configure>', lambda event: changeSize(event, eroded, LabelPic)) """
LabelPic.pack(fill=tk.BOTH, expand=tk.YES) global src, DilaWin, edge
# 添加保存按钮 # 判断是否已经选取图片
btn_save = tk.Button(CorrodeWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile) if src is None:
btn_save.pack(pady=10) messagebox.showerror("错误", "没有选择图片!")
return
return
# 定义结构元素(该处使用矩形3*3结构)
# 膨胀 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3), anchor=None)
def dilatation(root):
""" # 膨胀图像
膨胀操作 dilated = cv2.dilate(src, kernel)
"""
global src, DilaWin, edge # 更新 edge 变量
edge = Image.fromarray(dilated)
# 判断是否已经选取图片
if src is None: # 创建 Toplevel 窗口
messagebox.showerror("错误", "没有选择图片!") try:
return DilaWin.destroy()
except Exception:
# 定义结构元素(该处使用矩形3*3结构) print("NVM")
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3), anchor=None) finally:
DilaWin = Toplevel(root)
# 膨胀图像 DilaWin.attributes('-topmost', True)
dilated = cv2.dilate(src, kernel) DilaWin.geometry("360x300")
DilaWin.resizable(True, True) # 可缩放
# 更新 edge 变量 DilaWin.title("膨胀结果")
edge = Image.fromarray(dilated)
# 显示图像
# 创建 Toplevel 窗口 LabelPic = tk.Label(DilaWin, text="IMG", width=360, height=240)
try: image = ImageTk.PhotoImage(Image.fromarray(dilated))
DilaWin.destroy() LabelPic.image = image
except Exception: LabelPic['image'] = image
print("NVM")
finally: LabelPic.bind('<Configure>', lambda event: changeSize(event, dilated, LabelPic))
DilaWin = Toplevel(root) LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
DilaWin.attributes('-topmost', True)
DilaWin.geometry("360x300") # 添加保存按钮
DilaWin.resizable(True, True) # 可缩放 btn_save = tk.Button(DilaWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
DilaWin.title("膨胀结果") btn_save.pack(pady=10)
# 显示图像 return
LabelPic = tk.Label(DilaWin, text="IMG", width=360, height=240)
image = ImageTk.PhotoImage(Image.fromarray(dilated)) # 开运算
LabelPic.image = image def open_op(root):
LabelPic['image'] = image """
开运算操作
LabelPic.bind('<Configure>', lambda event: changeSize(event, dilated, LabelPic)) """
LabelPic.pack(fill=tk.BOTH, expand=tk.YES) global src, OpenWin, edge
# 添加保存按钮 # 判断是否已经选取图片
btn_save = tk.Button(DilaWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile) if src is None:
btn_save.pack(pady=10) messagebox.showerror("错误", "没有选择图片!")
return
return
# 交叉结构元
# 开运算 kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
def open_op(root):
""" # 进行开运算
开运算操作 open_result = cv2.morphologyEx(src, cv2.MORPH_OPEN, kernel)
"""
global src, OpenWin, edge # 更新 edge 变量
edge = Image.fromarray(open_result)
# 判断是否已经选取图片
if src is None: # 创建 Toplevel 窗口
messagebox.showerror("错误", "没有选择图片!") try:
return OpenWin.destroy()
except Exception:
# 交叉结构元 print("NVM")
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5)) finally:
OpenWin = Toplevel(root)
# 进行开运算 OpenWin.attributes('-topmost', True)
open_result = cv2.morphologyEx(src, cv2.MORPH_OPEN, kernel) OpenWin.geometry("360x300")
OpenWin.resizable(True, True) # 可缩放
# 更新 edge 变量 OpenWin.title("开运算结果")
edge = Image.fromarray(open_result)
# 显示图像
# 创建 Toplevel 窗口 LabelPic = tk.Label(OpenWin, text="IMG", width=360, height=240)
try: image = ImageTk.PhotoImage(Image.fromarray(open_result))
OpenWin.destroy() LabelPic.image = image
except Exception: LabelPic['image'] = image
print("NVM")
finally: LabelPic.bind('<Configure>', lambda event: changeSize(event, open_result, LabelPic))
OpenWin = Toplevel(root) LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
OpenWin.attributes('-topmost', True)
OpenWin.geometry("360x300") # 添加保存按钮
OpenWin.resizable(True, True) # 可缩放 btn_save = tk.Button(OpenWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
OpenWin.title("开运算结果") btn_save.pack(pady=10)
# 显示图像 return
LabelPic = tk.Label(OpenWin, text="IMG", width=360, height=240)
image = ImageTk.PhotoImage(Image.fromarray(open_result)) # 闭运算
LabelPic.image = image def close_op(root):
LabelPic['image'] = image """
闭运算操作
LabelPic.bind('<Configure>', lambda event: changeSize(event, open_result, LabelPic)) """
LabelPic.pack(fill=tk.BOTH, expand=tk.YES) global src, CloseWin, edge
# 添加保存按钮 # 判断是否已经选取图片
btn_save = tk.Button(OpenWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile) if src is None:
btn_save.pack(pady=10) messagebox.showerror("错误", "没有选择图片!")
return
return
# 交叉结构元
# 闭运算 kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (10, 10))
def close_op(root):
""" # 进行闭运算
闭运算操作 close_result = cv2.morphologyEx(src, cv2.MORPH_CLOSE, kernel)
"""
global src, CloseWin, edge # 更新 edge 变量
edge = Image.fromarray(close_result)
# 判断是否已经选取图片
if src is None: # 创建 Toplevel 窗口
messagebox.showerror("错误", "没有选择图片!") try:
return CloseWin.destroy()
except Exception:
# 交叉结构元 print("NVM")
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (10, 10)) finally:
CloseWin = Toplevel(root)
# 进行闭运算 CloseWin.attributes('-topmost', True)
close_result = cv2.morphologyEx(src, cv2.MORPH_CLOSE, kernel) CloseWin.geometry("360x300")
CloseWin.resizable(True, True) # 可缩放
# 更新 edge 变量 CloseWin.title("闭运算结果")
edge = Image.fromarray(close_result)
# 显示图像
# 创建 Toplevel 窗口 LabelPic = tk.Label(CloseWin, text="IMG", width=360, height=240)
try: image = ImageTk.PhotoImage(Image.fromarray(close_result))
CloseWin.destroy() LabelPic.image = image
except Exception: LabelPic['image'] = image
print("NVM")
finally: LabelPic.bind('<Configure>', lambda event: changeSize(event, close_result, LabelPic))
CloseWin = Toplevel(root) LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
CloseWin.attributes('-topmost', True)
CloseWin.geometry("360x300") # 添加保存按钮
CloseWin.resizable(True, True) # 可缩放 btn_save = tk.Button(CloseWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
CloseWin.title("闭运算结果") btn_save.pack(pady=10)
# 显示图像 return
LabelPic = tk.Label(CloseWin, text="IMG", width=360, height=240)
image = ImageTk.PhotoImage(Image.fromarray(close_result)) # 边缘检测
LabelPic.image = image def edge_detection(root):
LabelPic['image'] = image """
边缘检测操作
LabelPic.bind('<Configure>', lambda event: changeSize(event, close_result, LabelPic)) """
LabelPic.pack(fill=tk.BOTH, expand=tk.YES) global src, EdgeWin, edge
# 添加保存按钮 # 判断是否已经选取图片
btn_save = tk.Button(CloseWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile) if src is None:
btn_save.pack(pady=10) messagebox.showerror("错误", "没有选择图片!")
return
return
# 使用 Sobel 算子进行边缘检测
# 边缘检测 sobelx = cv2.Sobel(cv2.cvtColor(src, cv2.COLOR_RGB2GRAY), cv2.CV_64F, 1, 0, ksize=5)
def edge_detection(root): sobely = cv2.Sobel(cv2.cvtColor(src, cv2.COLOR_RGB2GRAY), cv2.CV_64F, 0, 1, ksize=5)
""" abs_sobelx = np.absolute(sobelx)
边缘检测操作 abs_sobely = np.absolute(sobely)
""" sobel_combined = cv2.bitwise_or(np.uint8(abs_sobelx), np.uint8(abs_sobely))
global src, EdgeWin, edge sobel_combined = cv2.cvtColor(sobel_combined, cv2.COLOR_GRAY2RGB)
# 判断是否已经选取图片 # 更新 edge 变量
if src is None: edge = Image.fromarray(sobel_combined)
messagebox.showerror("错误", "没有选择图片!")
return # 创建 Toplevel 窗口
try:
# 使用 Sobel 算子进行边缘检测 EdgeWin.destroy()
sobelx = cv2.Sobel(cv2.cvtColor(src, cv2.COLOR_RGB2GRAY), cv2.CV_64F, 1, 0, ksize=5) except Exception:
sobely = cv2.Sobel(cv2.cvtColor(src, cv2.COLOR_RGB2GRAY), cv2.CV_64F, 0, 1, ksize=5) print("NVM")
abs_sobelx = np.absolute(sobelx) finally:
abs_sobely = np.absolute(sobely) EdgeWin = Toplevel(root)
sobel_combined = cv2.bitwise_or(np.uint8(abs_sobelx), np.uint8(abs_sobely)) EdgeWin.attributes('-topmost', True)
sobel_combined = cv2.cvtColor(sobel_combined, cv2.COLOR_GRAY2RGB) EdgeWin.geometry("360x300")
EdgeWin.resizable(True, True) # 可缩放
# 更新 edge 变量 EdgeWin.title("边缘检测结果")
edge = Image.fromarray(sobel_combined)
# 显示图像
# 创建 Toplevel 窗口 LabelPic = tk.Label(EdgeWin, text="IMG", width=360, height=240)
try: image = ImageTk.PhotoImage(Image.fromarray(sobel_combined))
EdgeWin.destroy() LabelPic.image = image
except Exception: LabelPic['image'] = image
print("NVM")
finally: LabelPic.bind('<Configure>', lambda event: changeSize(event, sobel_combined, LabelPic))
EdgeWin = Toplevel(root) LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
EdgeWin.attributes('-topmost', True)
EdgeWin.geometry("360x300") # 添加保存按钮
EdgeWin.resizable(True, True) # 可缩放 btn_save = tk.Button(EdgeWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
EdgeWin.title("边缘检测结果") btn_save.pack(pady=10)
# 显示图像 return
LabelPic = tk.Label(EdgeWin, text="IMG", width=360, height=240)
image = ImageTk.PhotoImage(Image.fromarray(sobel_combined))
LabelPic.image = image
LabelPic['image'] = image
LabelPic.bind('<Configure>', lambda event: changeSize(event, sobel_combined, LabelPic))
LabelPic.pack(fill=tk.BOTH, expand=tk.YES)
# 添加保存按钮
btn_save = tk.Button(EdgeWin, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20, command=savefile)
btn_save.pack(pady=10)
return

Loading…
Cancel
Save