import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image # 创建窗口 window = tk.Tk() window.title("宝石预测") window.geometry("400x400") # 加载模型参数 para_state_dict = paddle.load("MyCNN") model = MyCNN() model.set_state_dict(para_state_dict) model.eval() # 加载标签字典 label_dict = train_parameters['label_dict'] # 创建预测函数 def predict(): # 获取待预测图片路径 img_path = filedialog.askopenfilename() img = Image.open(img_path) # 预处理图片 img = img.resize((224, 224), Image.BILINEAR) img = np.array(img).astype('float32') img = img.transpose((2, 0, 1)) img = img / 255 img = np.array([img]) # 进行预测 img = paddle.to_tensor(img) out = model(img) label = np.argmax(out.numpy()) result = label_dict[str(label)] # 显示预测结果 result_label.config(text="预测结果:{}".format(result)) # 显示待预测图片 img = ImageTk.PhotoImage(Image.open(img_path).resize((200, 200))) img_label.config(image=img) img_label.image = img # 创建选择图片按钮 select_button = tk.Button(window, text="选择图片", command=predict) select_button.pack(pady=20) # 创建待预测图片区域 img_label = tk.Label(window) img_label.pack() # 创建预测结果区域 result_label = tk.Label(window, font=("Helvetica", 16)) result_label.pack(pady=20) # 进入消息循环 window.mainloop()在这段代码的功能中加入使用cv2对选择的图片进行降噪,之后再对上传图片进行识别
时间: 2024-01-01 09:04:37 浏览: 168
好的,你可以使用 OpenCV 库对选择的图片进行降噪,然后将处理后的图片传给预测函数进行识别。下面是修改后的代码:
```
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
import cv2
import numpy as np
# 创建窗口
window = tk.Tk()
window.title("宝石预测")
window.geometry("400x400")
# 加载模型参数
para_state_dict = paddle.load("MyCNN")
model = MyCNN()
model.set_state_dict(para_state_dict)
model.eval()
# 加载标签字典
label_dict = train_parameters['label_dict']
# 创建预测函数
def predict():
# 获取待预测图片路径
img_path = filedialog.askopenfilename()
# 降噪处理
img = cv2.imread(img_path)
img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
# 预处理图片
img = cv2.resize(img, (224, 224))
img = img.transpose((2, 0, 1))
img = img / 255
img = np.array([img])
# 进行预测
img = paddle.to_tensor(img)
out = model(img)
label = np.argmax(out.numpy())
result = label_dict[str(label)]
# 显示预测结果
result_label.config(text="预测结果:{}".format(result))
# 显示待预测图片
img = ImageTk.PhotoImage(Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)).resize((200, 200)))
img_label.config(image=img)
img_label.image = img
# 创建选择图片按钮
select_button = tk.Button(window, text="选择图片", command=predict)
select_button.pack(pady=20)
# 创建待预测图片区域
img_label = tk.Label(window)
img_label.pack()
# 创建预测结果区域
result_label = tk.Label(window, font=("Helvetica", 16))
result_label.pack(pady=20)
# 进入消息循环
window.mainloop()
```
阅读全文