写一个python代码,制作一个GUI界面,使用已经存在的MyCNN模型进行宝石图片预测
时间: 2024-01-22 22:20:26 浏览: 32
以下是一个简单的Python程序,使用Tkinter模块制作GUI界面,加载预先训练好的MyCNN模型,并使用该模型对用户选择的宝石图片进行预测。
```python
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
import numpy as np
import tensorflow as tf
# 加载预训练的模型
model = tf.keras.models.load_model('my_cnn_model.h5')
# 宝石标签列表
labels = ['Amber', 'Diamond', 'Emerald', 'Ruby', 'Sapphire']
def predict_gemstone(image_path):
# 加载图像文件并将其大小调整为模型期望的大小
img = Image.open(image_path).resize((200, 200))
# 将图像转换为numpy数组
img_array = np.array(img)
# 将图像转换为模型期望的格式
img_input = np.expand_dims(img_array, axis=0) / 255.0
# 使用模型进行预测
predictions = model.predict(img_input)
# 返回预测结果
return labels[np.argmax(predictions)]
def select_image():
# 弹出文件对话框以选择图像文件
file_path = filedialog.askopenfilename()
# 如果用户选择了一个文件,则在标签上显示它,并使用模型进行预测
if file_path:
image = Image.open(file_path).resize((200, 200))
photo = ImageTk.PhotoImage(image)
image_label.configure(image=photo)
image_label.image = photo
predicted_label.configure(text='Predicted gemstone: ' + predict_gemstone(file_path))
# 创建主窗口
root = tk.Tk()
root.title('Gemstone Predictor')
# 创建按钮和标签
select_button = tk.Button(root, text='Select Image', command=select_image)
image_label = tk.Label(root)
predicted_label = tk.Label(root)
# 将按钮和标签添加到主窗口中
select_button.pack()
image_label.pack()
predicted_label.pack()
# 运行主循环
root.mainloop()
```
注意:这个程序假定MyCNN模型已经被训练并保存在一个名为`my_cnn_model.h5`的文件中。在实践中,你需要先训练你自己的模型或者使用别人已经训练好的模型。