Django 深度学习模型图片预测 - 完整代码示例
下面是一个使用 Django 连接深度学习模型的示例代码,该模型可以对上传的图片进行预测,并输出预测的具体类别。
-
首先,确保已经安装了 Django 和 TensorFlow 等相关库。
-
创建一个 Django 项目,并在项目的根目录中创建一个名为 'predict' 的应用。
-
在 'predict' 应用的目录下创建一个名为 'models' 的文件夹,并将深度学习模型文件(如 '.h5'、'.pb' 等)放入该文件夹。
-
在 'predict' 应用的目录下创建一个名为 'utils.py' 的文件,用于加载模型和进行预测。
# utils.py
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing import image
# 加载模型
def load_model():
model = tf.keras.models.load_model('predict/models/model.h5')
return model
# 预测图片类别
def predict_image(img_path, model):
img = image.load_img(img_path, target_size=(224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img /= 255.
pred = model.predict(img)
class_index = np.argmax(pred)
return class_index
- 在 'predict' 应用的目录下创建一个名为 'views.py' 的文件,用于处理 HTTP 请求和返回预测结果。
# views.py
from django.shortcuts import render
from django.http import JsonResponse
from .utils import load_model, predict_image
# 加载模型
model = load_model()
# 处理上传图片并返回预测结果
def predict(request):
if request.method == 'POST':
img = request.FILES['image']
img_path = 'predict/static/images/' + img.name
with open(img_path, 'wb+') as destination:
for chunk in img.chunks():
destination.write(chunk)
class_index = predict_image(img_path, model)
class_labels = ['类别1', '类别2', '类别3', '类别4', '类别5', '类别6', '类别7', '类别8', '类别9', '类别10']
prediction = class_labels[class_index]
return JsonResponse({'prediction': prediction})
return render(request, 'predict/predict.html')
- 在 'predict' 应用的目录下创建一个名为 'predict.html' 的文件,用于展示上传图片的界面。
<!-- predict.html -->
<!DOCTYPE html>
<html>
<head>
<title>Image Prediction</title>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
{% csrf_token %}
<input type='file' name='image' accept='image/*' />
<button type='submit'>Predict</button>
</form>
</body>
</html>
- 在项目的根目录中的 'urls.py' 文件中添加路由配置。
# urls.py
from django.urls import path
from predict.views import predict
urlpatterns = [
path('predict/', predict, name='predict'),
]
- 运行 Django 项目,并通过浏览器访问 'http://localhost:8000/predict/',即可上传图片并获取预测结果。
这是一个简单的示例,你需要根据你的实际情况进行相应的调整和优化。
原文地址: https://www.cveoy.top/t/topic/pdYd 著作权归作者所有。请勿转载和采集!