用tkinter写一个预测图片的小程序

使用Tkinter实现图像加载与TensorFlow模型预测的小程序
部署运行你感兴趣的模型镜像

hello,这次用tkinter写一个预测图片的小程序

首先要调用数据库

import tkinter as tk
from tkinter import filedialog
import tensorflow as tf
from PIL import Image, ImageTk
import numpy as np

然后,我们要调用训练好的模型

# 指定模型文件路径
model_path = 'model/16_model.h5'

# 加载模型
model = tf.keras.models.load_model(model_path)

接下来就是程序的主题了,接下来我就分段讲解代码的含义。

class ImageLoaderApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Image Loader")

        self.load_button = tk.Button(root, text="Load Image", command=self.load_image)
        self.load_button.pack(pady=10)

        self.image_label = tk.Label(root)
        self.image_label.pack()

        self.title_label = tk.Label(root, text="")
        self.title_label.pack()

    def load_image(self):
        file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.png;*.jpg;*.jpeg")])
        if file_path:
            self.image = tf.io.read_file(file_path)
            self.show_image = Image.open(file_path)
            self.preprocess_image_predict()
            self.display_image()

    def preprocess_image_predict(self):
        image = tf.image.decode_image(self.image, channels=3, expand_animations=False)
        target_size = (224, 224)  # 替换为模型所需的大小
        image = tf.image.resize(image, target_size)
        image = tf.expand_dims(image, axis=0)
        predictions = model.predict(image)
        if (np.argmax(predictions) < 10):
            self.title = class_names[np.argmax(predictions)]
        else:
            self.title = "I don't know"

    def display_image(self):
        img = ImageTk.PhotoImage(self.show_image)
        self.image_label.config(image=img)
        self.image_label.image = img

        title_text = self.title  # 你可以替换成你想要的标题
        self.title_label.config(text=title_text)

首先是第一段代码,这部分代码是展示应用界面的主体部分,这部分包括应用的标题,按键和其功能,图片展示,图片的标题。

class ImageLoaderApp:
    def __init__(self, root):
        #设置应用的标题
        self.root = root
        self.root.title("Image Loader")
        
        #设置应用的按键,命令为读取图片
        self.load_button = tk.Button(root, text="Load Image", command=self.load_image)
        self.load_button.pack(pady=10)
        
        #设指图片展示
        self.image_label = tk.Label(root)
        self.image_label.pack()

        #设置图片的标题
        self.title_label = tk.Label(root, text="")
        self.title_label.pack()

接下来的代码是读取图片的代码,分为两个部分,第一部分是读取图片的路径,这个作为展示使用。另一个部分也是读取图片的路径,用来给tensorflow预测。

    def load_image(self):
        file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.png;*.jpg;*.jpeg")])
        if file_path:
            #读取图片(展示)
            self.image = tf.io.read_file(file_path)
            #读取图片(tensorflow)
            self.show_image = Image.open(file_path)
            self.preprocess_image_predict()
            self.display_image()

这个部分的代码是用来预测图片的,这个部分就不详细解释了,是固定的(大概吧)。

    def preprocess_image_predict(self):
        image = tf.image.decode_image(self.image, channels=3, expand_animations=False)
        target_size = (224, 224)  # 替换为模型所需的大小
        image = tf.image.resize(image, target_size)
        image = tf.expand_dims(image, axis=0)
        predictions = model.predict(image)
        if (np.argmax(predictions) < 10):
            self.title = class_names[np.argmax(predictions)]
        else:
            self.title = "I don't know"

最后是展示图片,包括图片和预测名。

    def display_image(self):
        img = ImageTk.PhotoImage(self.show_image)
        self.image_label.config(image=img)
        self.image_label.image = img

        title_text = self.title  # 你可以替换成你想要的标题
        self.title_label.config(text=title_text)

最后的最后,我们只要展示tkinter就可以了

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry('500x500')
    app = ImageLoaderApp(root)
    root.mainloop()

让我们看看结果吧

虽然很简陋,但是看结果是成功了,预测结果十分甚至九分的准。

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

### 手数字识别程序的设计 为了实现基于 Python 的手数字识别系统,可以采用 KNN 算法作为核心分类器,并利用 `tkinter` 创建图形用户界面 (GUI),以便于用户交互。以下是该系统的具体设计思路和技术细节。 #### 1. 数据准备与预处理 在构建手数字识别系统之前,需要准备好训练数据集和测试数据集。通常会使用 MNIST 数据集来完成这一任务。MNIST 是一个广泛使用的手数字数据库,包含大量已标注的手数字图像[^1]。 如果希望支持自定义输入(如通过摄像头拍摄或上传图片),则需对这些图像进行预处理,包括灰度化、二值化以及尺寸调整到固定大小(通常是 28x28 像素)。这一步可以通过 OpenCV 或 PIL 库轻松实现。 ```python import cv2 from PIL import Image def preprocess_image(image_path): img = Image.open(image_path).convert('L') # 转为灰度图 img_resized = img.resize((28, 28)) # 尺寸调整至 28x28 img_array = np.array(img_resized) # 转换为 NumPy 数组 _, binary_img = cv2.threshold(img_array, 127, 255, cv2.THRESH_BINARY_INV) # 二值化 return binary_img.flatten() # 展平成一维数组用于后续计算 ``` #### 2. 实现 KNN 算法 KNN 算法是一种简单有效的监督学习方法,在模式识别领域应用广泛。其实现逻辑如下:对于给定的新样本点,找到与其最近的 k 个邻居,并根据多数投票原则决定其类别归属。下面是一个简单的 KNN 函数实现: ```python import numpy as np from collections import Counter class KNearestNeighbors: def __init__(self, k=3): self.k = k def fit(self, X_train, y_train): self.X_train = X_train self.y_train = y_train def predict(self, X_test): predictions = [] for test_sample in X_test: distances = [np.linalg.norm(test_sample - train_sample) for train_sample in self.X_train] nearest_indices = np.argsort(distances)[:self.k] nearest_labels = [self.y_train[i] for i in nearest_indices] most_common_label = Counter(nearest_labels).most_common(1)[0][0] predictions.append(most_common_label) return predictions ``` #### 3. 使用 Tkinter 构建 GUI Tkinter 是 Python 自带的一个轻量级 GUI 工具包,适合快速搭建桌面应用程序。以下代码展示了如何创建一个窗口允许用户加载图片并显示预测结果: ```python import tkinter as tk from tkinter import filedialog from tkinter import messagebox root = tk.Tk() root.title("Handwritten Digit Recognition") canvas = tk.Canvas(root, width=300, height=300) canvas.pack() label = tk.Label(root, text="Upload an image to recognize", font=('Arial', 14)) label.pack(pady=20) def upload_and_predict(): filepath = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Image files", "*.jpg *.png"), ("All Files", "*.*"))) if not filepath: return try: preprocessed_data = preprocess_image(filepath) prediction = knn.predict([preprocessed_data]) label.config(text=f"Predicted digit: {prediction[0]}") except Exception as e: messagebox.showerror("Error", str(e)) button = tk.Button(root, text="Upload and Predict", command=upload_and_predict) button.pack(pady=10) # 初始化模型 X_train, y_train = load_mnist_dataset() # 加载 MNIST 训练数据 knn = KNearestNeighbors(k=5) knn.fit(X_train, y_train) root.mainloop() ``` 以上代码片段中包含了几个重要部分: - **Canvas 和 Label**:分别用来绘制背景画布和展示文字提示。 - **Button 组件绑定事件处理器**:当点击按钮时触发文件对话框让用户选择要识别的图片。 - **异常捕获机制**:防止因非法路径或其他错误导致程序崩溃。 #### 总结 综上所述,借助 Python 中强大的库生态系统——尤其是 NumPy 提供的强大数值运算能力、OpenCV/PIL 对图像的操作便利性以及 Tkinter 易用性的优势,完全可以高效地开发出手数字识别软件[^1]^。此项目不仅锻炼了开发者关于机器学习基础知识的理解程度,同时也加深了对其它计算机科学分支学科的认识水平[^2]^。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值