利用pythongui框架用tk做动物识别代码
时间: 2023-12-17 12:02:44 浏览: 183
以下是使用Tkinter实现的简单动物识别应用程序示例代码:
```python
import tkinter as tk
import cv2
import numpy as np
from tensorflow.keras.models import load_model
from PIL import Image, ImageTk
model = load_model('animal_model.h5')
class AnimalClassifierGUI:
def __init__(self):
self.window = tk.Tk()
self.window.title("动物识别")
# 创建画布
self.canvas = tk.Canvas(self.window, width=400, height=400, bg='white')
self.canvas.pack()
# 创建按钮
self.btn = tk.Button(self.window, text='上传图像', command=self.upload_image)
self.btn.pack()
# 创建标签
self.label = tk.Label(self.window, text='请上传一张动物图片')
self.label.pack()
self.window.mainloop()
def upload_image(self):
# 弹出文件选择对话框
file_path = tk.filedialog.askopenfilename()
# 加载图像并进行预处理
img = cv2.imread(file_path)
img = cv2.resize(img, (224, 224))
img = np.expand_dims(img, axis=0)
# 进行预测
pred = model.predict(img)
class_id = np.argmax(pred[0])
# 根据类别ID显示预测结果
if class_id == 0:
self.label.configure(text='这是一张狗的图片')
elif class_id == 1:
self.label.configure(text='这是一张猫的图片')
else:
self.label.configure(text='这是一张熊猫的图片')
# 在画布上显示图像
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img_rgb)
img_tk = ImageTk.PhotoImage(img_pil)
self.canvas.create_image(200, 200, image=img_tk)
self.canvas.image = img_tk
# 启动GUI应用程序
app = AnimalClassifierGUI()
```
该示例程序使用Tkinter创建了一个简单的用户界面,用户可以通过点击“上传图像”按钮选择一张动物图片进行识别。程序使用OpenCV加载图像并进行预处理,然后使用预训练的深度学习模型进行分类预测。最终,程序在画布上显示原始图像并提供相应的预测结果。需要注意的是,该示例程序是一个简单的演示,实际应用中需要更加完善和稳定的算法和界面设计。
阅读全文
相关推荐


















