这是一个使用 Django 连接深度学习模型的示例代码,该模型预测图片属于十个类别之一,并输出预测值。

首先,确保已安装 Django 和 TensorFlow。然后,创建一个 Django 项目并创建一个 app。

  1. 在 Django 项目的'settings.py'文件中添加 app 和模型文件的路径:
INSTALLED_APPS = [
    ...
    'your_app',
    ...
]

# 设置深度学习模型文件路径
MODEL_PATH = 'your_model_path'
  1. 在 app 中的'views.py'文件中添加以下代码:
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import tensorflow as tf
import numpy as np
import os
from PIL import Image

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

# 图片预处理函数
def preprocess_image(image):
    img = image.convert('RGB')
    img = img.resize((224, 224))
    img_array = np.array(img)
    img_array = img_array / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    return img_array

# 类别名称
class_names = ['class1', 'class2', 'class3', 'class4', 'class5', 'class6', 'class7', 'class8', 'class9', 'class10']

# 处理上传的图片
def predict_image(request):
    if request.method == 'POST' and request.FILES['image']:
        # 保存上传的图片
        image = request.FILES['image']
        fs = FileSystemStorage()
        filename = fs.save(image.name, image)
        uploaded_file_url = fs.url(filename)

        # 预测图片类别
        img = Image.open(os.path.join(settings.MEDIA_ROOT, filename))
        img_array = preprocess_image(img)
        predictions = model.predict(img_array)
        predicted_class = np.argmax(predictions[0])
        predicted_class_name = class_names[predicted_class]

        return render(request, 'result.html', {'uploaded_file_url': uploaded_file_url, 'predicted_class': predicted_class_name})
    return render(request, 'index.html')
  1. 在 app 中的'urls.py'文件中添加以下代码:
from django.urls import path
from . import views

urlpatterns = [
    path('', views.predict_image, name='predict_image'),
]
  1. 在 app 中创建两个 HTML 模板文件:'index.html' 和 'result.html'。

index.html 内容:

<!DOCTYPE html>
<html>
<head>
    <title>Image Classification</title>
</head>
<body>
    <h2>Upload an image for prediction</h2>
    <form method='post' enctype='multipart/form-data'>
        {% csrf_token %}
        <input type='file' name='image'>
        <button type='submit'>Upload</button>
    </form>
</body>
</html>

result.html 内容:

<!DOCTYPE html>
<html>
<head>
    <title>Image Classification Result</title>
</head>
<body>
    <h2>Uploaded Image</h2>
    <img src='{{ uploaded_file_url }}' alt='uploaded image' width='300px'>

    <h2>Prediction</h2>
    <p>Predicted class: {{ predicted_class }}</p>
</body>
</html>

以上代码实现了一个简单的 Django 应用,允许用户上传图片并使用深度学习模型进行预测。预测结果将显示在另一个页面上。记得替换'your_app' 和 'your_model_path' 为正确的应用和模型文件路径。

Django 深度学习图片分类:使用预训练模型识别十类图片

原文地址: https://www.cveoy.top/t/topic/peRl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录