使用 Django 和深度学习模型进行图像分类预测
以下是一个使用 Django 和深度学习模型 (例如,使用 TensorFlow 和 Keras 训练的模型) 连接的示例代码。该代码可以上传图片到网页上,并使用深度学习模型进行预测,输出图片所属的类别及其预测值。
首先,确保已在 Django 项目中安装了 TensorFlow 和 Keras 库。
在 Django 项目的视图 (views.py) 中,可以编写以下代码:
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
# 加载训练好的深度学习模型
model = load_model('path_to_model.h5')
# 定义类别标签
class_labels = ['class1', 'class2', 'class3', 'class4', 'class5', 'class6', 'class7', 'class8', 'class9', 'class10']
def predict_image(request):
if request.method == 'POST' and request.FILES['image']:
# 从POST请求中获取上传的图片
uploaded_image = request.FILES['image']
fs = FileSystemStorage()
# 将图片保存到服务器上
image_path = fs.save(uploaded_image.name, uploaded_image)
# 获取保存图片的路径
image_path = fs.url(image_path)
# 读取上传的图片并进行预处理
img = image.load_img(image_path, target_size=(224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img = img/255.0 # 归一化
# 使用模型进行预测
prediction = model.predict(img)
predicted_class = np.argmax(prediction)
predicted_label = class_labels[predicted_class]
predicted_value = prediction[0][predicted_class]
# 返回预测结果到网页
return render(request, 'result.html', {'predicted_label': predicted_label, 'predicted_value': predicted_value, 'image_path': image_path})
return render(request, 'upload.html')
在 Django 项目的模板 (templates) 文件夹中,可以创建以下两个模板文件。
upload.html 模板文件内容:
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
{% csrf_token %}
<input type='file' name='image'>
<input type='submit' value='Upload'>
</form>
</body>
</html>
result.html 模板文件内容:
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<body>
<h1>Prediction Result:</h1>
<p>Uploaded Image: <img src='{{ image_path }}'></p>
<p>Predicted Label: {{ predicted_label }}</p>
<p>Predicted Value: {{ predicted_value }}</p>
</body>
</html>
确保在 Django 项目的 urls.py 文件中添加以下 URL 配置:
from django.urls import path
from . import views
urlpatterns = [
path('predict/', views.predict_image, name='predict_image'),
]
现在,当您访问 http://localhost:8000/predict/ 时,您将看到一个网页,您可以在其中上传图片,并查看预测结果。
请注意,此代码仅为示例,您可能需要根据您的实际需求进行修改。
原文地址: https://www.cveoy.top/t/topic/peiw 著作权归作者所有。请勿转载和采集!