发布于 2026-01-05 2 阅读
0

如何使用 Python 创建一个 AI 照片应用程序

如何使用 Python 创建一个 AI 照片应用程序

让我们学习如何使用 Python 和 Taipy 构建一个图像识别应用程序。
我们将首先开发模型,然后使用 Taipy 构建一个图形用户界面 (GUI) 来使用它。
该应用程序允许我们上传图像,并使用我们训练好的模型来识别图像内容。

应用


什么是神经网络构建器

让我们开始吧!
第一阶段是创建一个用于图像分类的神经网络。我们将使用TensorFlow
中的神经网络构建器CIFAR-10数据集。TensorFlow 是开发和训练神经网络必不可少的人工智能库。

给 TensorFlow 仓库点赞 ⭐

该数据集包含超过 50,000 张图像,对于训练图像识别模型至关重要。
我们将能够使用 Taipy 对我们的模型进行测试,并构建一个应用程序。

星标 ⭐ Taipy 仓库

您的支持对我们意义重大🌱,真的在很多方面都对我们有所帮助,比如撰写文章!🙏


我们的模型将基于CIFAR数据集中的十个类别进行训练:

  • 飞机✈️
  • 汽车🚗
  • 鸟🦜
  • 猫🐈
  • 鹿🦌
  • 狗🐶
  • 青蛙🐸
  • 马🐴
  • 船⚓

我们的模型能够将图像分类为这十类。


创建神经网络构建器


先决条件

  • Python——您的计算机上应该安装了Python编程语言。
  • virtualenv - 一个用于创建隔离的虚拟 Python 环境的工具。我将在本项目中使用 virtualenv;但是,您可以使用您喜欢的工具,例如 venv 或 Conda,并调整您的命令。

重要提示:根据您的设置,在终端运行命令时可能需要使用 python 或 python3 命令。


设置

好了,开始构建!
运行以下命令来设置你的项目:

mkdir ml-photo-app
cd ml-photo-app
mkdir neural-network-builder
cd neural-network-builder
virtualenv venv
source venv/bin/activate
cd venv
Enter fullscreen mode Exit fullscreen mode

现在让我们安装真正的工具,两个 Python 库:TensorFlownumpy——一个用于对数组进行数学运算的库。

请使用以下命令:

pip install tensorflow numpy
Enter fullscreen mode Exit fullscreen mode

下载 CIFAR 数据集

但首先,我们需要数据!现在,让我们从这里
下载 CIFAR-10 数据集

CIFAR

我们需要的是CIFAR-10 Python 版本
下载并解压文件后,您应该会看到一个名为cifar-10-batches-py的文件夹。复制该文件夹以及我们刚刚创建的项目neural-network-builder/venv
中的所有文件


Python脚本:generate-model.py

创建一个名为generate-model.py的文件
这将是我们用于模型训练和导出的 Python 脚本。

将以下代码添加到generate-model.py文件中。

import os
import shutil
import pickle
import numpy as np
import tensorflow as tf
from tensorflow.keras import datasets, layers, models

def load_cifar10_data(data_dir):
    train_images = []
    train_labels = []

    for i in range(1, 6):
        with open(os.path.join(data_dir, f'data_batch_{i}'), 'rb') as f:
            data_dict = pickle.load(f, encoding='bytes')
            images = data_dict[b'data']
            labels = data_dict[b'labels']

            train_images.extend(images)
            train_labels.extend(labels)

    train_images = np.array(train_images).reshape(-1, 3,
                                                  32, 32).transpose(0, 2, 3, 1)
    train_labels = np.array(train_labels)

    with open(os.path.join(data_dir, 'test_batch'), 'rb') as f:
        data_dict = pickle.load(f, encoding='bytes')
        test_images = data_dict[b'data'].reshape(
            -1, 3, 32, 32).transpose(0, 2, 3, 1)
        test_labels = np.array(data_dict[b'labels'])

    return (train_images, train_labels), (test_images, test_labels)


def build_model():
    # Define the model architecture
    model = models.Sequential()
    model.add(layers.Conv2D(
        32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(64, (3, 3), activation='relu'))

    # Add dense layers on top
    model.add(layers.Flatten())
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dense(10))

    return model

def train_model(model, train_images, train_labels, test_images, test_labels):
    # Compile and train the model
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.SparseCategoricalCrossentropy(
                      from_logits=True),
                  metrics=['accuracy'])

    history = model.fit(train_images, train_labels, epochs=50,
                        validation_data=(test_images, test_labels))

    # Check if the model directory exists
    if os.path.exists('model'):
        # If it does, delete it
        shutil.rmtree('model')
    # Recreate the model directory
    os.makedirs('model')

    # Save the model
    model.save('model/cifar-10-batches-py-model.keras')

    return history

# Load and preprocess the CIFAR10 dataset
data_dir = 'C:/Users/marin/Documents/GitHub/AB/ml-photo-app/neural-network-builder/venv/cifar-10-batches-py'
(train_images, train_labels), (test_images,
                               test_labels) = load_cifar10_data(data_dir)


# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

# Build and train the model
model = build_model()
history = train_model(model, train_images, train_labels,
                      test_images, test_labels)


# Print the history dictionary
print(history.history)
Enter fullscreen mode Exit fullscreen mode

运行generate-model.py脚本

关键时刻到了!运行您的文件。
该文件将构建、训练并保存我们的模型。

根据您的计算机配置,此过程所需时间可能有所不同。

让我们关注脚本中名为 epochs 的参数,它被设置为epochs=50。

纪元

epoch 是一个重要的超参数,它代表模型遍历所有训练数据集的完整周期。
每个样本都会更新模型的参数。
这个周期并非指耗时,而是指模型遍历数据的次数。
这个关键参数会影响训练过程。事实上,epoch 越多,模型的学习率就越高。epoch

越多,训练模型所需的时间就越长。

如果训练轮数不足以让模型识别数据中的潜在模式,则可能发生欠拟合。然而,训练轮数过多则可能导致模型过拟合训练集,从而导致模型在新数据上的泛化能力较差。

要运行脚本,请使用以下命令(您可能需要使用PythonPython 3):

python3 generate-model.py
Enter fullscreen mode Exit fullscreen mode

现在,请稍等片刻!等待模型训练完成并保存到模型文件夹中。
创建 GUI 前端时,我们将复制该模型文件夹。
现在,让我们添加一个 GUI 来体验我们的模型吧!


我们使用 Taipy 构建 GUI。

设置

返回主项目文件夹 ml-photo-app,然后运行以下脚本来设置我们的界面:

mkdir frontend
cd frontend
virtualenv venv
source venv/bin/activate
cd venv
Enter fullscreen mode Exit fullscreen mode

现在,让我们安装我们将要使用的Python库:

  • 泰皮
  • TensorFlow
  • 纳皮
  • Pillow (PIL) - Python 图像处理库

运行以下命令:

pip install taipy tensorflow pillow numpy
Enter fullscreen mode Exit fullscreen mode

前端文件夹

让我们把新模型从神经网络构建器项目复制到前端文件夹。在前端文件
夹的根目录下创建两个文件

  • index.py
  • index.css

这些是我们图形用户界面将要运行的文件。


设置 CSS 首选项:index.css

将此代码添加到我们刚刚创建的 index.css 文件中:

@import url('https://fonts.googleapis.com/css2?family=Alegreya+Sans:ital,wght@0,100;0,300;0,400;0,500;0,700;0,800;0,900;1,100;1,300;1,400;1,500;1,700;1,800;1,900&display=swap');

body {
  background: rgb(36, 57, 86);

  font-family: 'Alegreya Sans', sans-serif;

  font-weight: 400;

  font-style: normal;

  font-size: 18px;
}

.container {
  margin: 0 auto;
}

.attachment,
.prediction {
  display: flex;

  flex-flow: row nowrap;

  align-items: center;
}

.attachment div {
  margin: 1rem;
}

.prediction p {
  margin-right: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

创建 index.py Python 脚本

要使用 Taipy 创建应用程序,您可以使用 Markdown、Python API 或 HTML。
在本教程中,我们将使用HTML方法,但您可以随意选择任何其他方法!

最后,将以下代码添加到index.py脚本中:

from taipy.gui import Gui
from taipy.gui import Html
from tensorflow.keras import models
from PIL import Image
import tensorflow
import numpy as np


class_names = {
    0: 'airplane',
    1: 'automobile',
    2: 'bird',
    3: 'cat',
    4: 'deer',
    5: 'dog',
    6: 'frog',
    7: 'horse',
    8: 'ship',
    9: 'truck',
}


model = models.load_model("C:/Users/marin/Documents/GitHub/AB/ml-photo-app/model/cifar-10-batches-py-model.keras")


def predict_image(model, path_to_img):
    img = Image.open(path_to_img)
    img = img.convert("RGB")
    img = img.resize((32, 32))
    data = np.asarray(img)
    data = data / 255
    logits = model.predict(np.array([data])[:1])
    probs = tensorflow.nn.softmax(logits).numpy()

    top_prob = probs.max()
    top_pred = class_names[np.argmax(probs)]

    return top_prob, top_pred


opt = tensorflow.keras.optimizers.legacy.Adam(learning_rate=0.1)


content = ""
img_path = "https://placehold.co/600?text=No+Image+Available&font=roboto"
prob = 0
pred = ""


html_page = Html("""
<div class="container">
<h1>Machine Learning Photo App</h1>
<p>There is a prediction indication that ranges from 0 to 100. The greater the value, the more certain the machine model is that the prediction is true. This all depends on the Neural Network Builder model that we generated. The longer you train the model, the smarter it will get. If it does not have enough training time, it will make incorrect predictions.</p>
<div class="attachment">
<div><taipy:file_selector extensions=".png">{content}</taipy:file_selector></div>
<div><p>Choose an image from your computer to upload</p></div>
</div>
<div>
<taipy:image>{img_path}</taipy:image>
<taipy:indicator min="0" max="100" width="25vw" height="25vh" orientation="vertical" value="{prob}">{prob}</taipy:indicator>
</div>
<div class="prediction">
<p>Prediction:</p><div><taipy:text>{pred}</taipy:text></div>
</div>
</div>
""")

def on_change(state, var_name, var_val):
    if var_name == "content":
        top_prob, top_pred = predict_image(model, var_val)
        state.prob = round(top_prob * 100)
        state.pred = "Its a " + top_pred
        state.img_path = var_val


app = Gui(page=html_page)

if __name__ == "__main__":
    app.run(use_reloader=True, port=8000)
Enter fullscreen mode Exit fullscreen mode

我们的应用程序将在这里的 8000 端口上运行,但您可以随意更改它。


运行应用程序

app.run(use_reloader=True, port=8000)
Enter fullscreen mode Exit fullscreen mode

将use_realorder设置为 *True”后,如果您对 GUI 代码进行任何更改,则无需重新运行所有内容;只需刷新应用程序页面即可。

要运行我们的应用程序,请使用以下命令:

taipy run index.py
Enter fullscreen mode Exit fullscreen mode

如何使用该应用程序?

上传任何.png 图片,最好是属于以下十个类别的图片!

  • 飞机
  • 汽车
  • 鹿
  • 青蛙

尽情体验你的应用程序如何对图像进行分类吧!


最后想说的话

我们的项目完成了!

我们使用 Python 创建了一个图像分类器模型,可以直接通过 Taipy 的图形用户界面 (GUI) 使用它。如果您想开发更全面的应用程序,请务必查阅 TensorFlow 和 Taipy 的文档。

欢迎提出反馈意见!

文章来源:https://dev.to/taipy/how-to-create-an-ai-photo-app-with-python-23g8