我的设想是想要把训练好的cifar10数据集的模型并预测好的代码部署在django上,想通过前端上传图片然后传到后端进行预测,然后再返回前端
问题相关代码,请勿粘贴截图
前端代码
<!-- 主体内容 -->
<div class="row">
<br>
<!-- 图片上传 -->
<div class="col-md-6">
<img id="photoIn" src="{% static 'img/sample.jpg' %}" class="img-responsive">
<input type="file" id="photo" name="photo" />
</div>
<!-- 运行结果 -->
<div class="col-md-6">
<div class="col-md-12">
<textarea id="output" disabled class="form-control" rows="5"
style="text-align: left;font: 150px 宋体;border: 0">
</textarea>
</div>
<br>
<div class="col-md-12">
<p class="text-center h4">识别结果</p>
</div>
</div>
</div>
<br>
<div class="row">
<div class="text-center">
<button type="button" id="recognition" class="btn btn-primary">识别</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
$('#photo').on('change', function () {
var r = new FileReader();
f = document.getElementById('photo').files[0];
r.readAsDataURL(f);
r.onload = function (e) {
document.getElementById('photoIn').src = this.result;
};
});
});
</script>
<!-- 图像发送至后台服务器进行识别 -->
<script>
$('#recognition').click(function () {
formdata = new FormData();
var file = $("#photo")[0].files[0];
formdata.append("image", file);
$.ajax({
url: '/productapp/imgdetect/', // 调用Django服务器计算函数
type: 'POST', // 请求类型
data: formdata,
dataType: 'json', // 期望获得的响应类型为json
processData: false,
contentType: false,
success: ShowResult // 在请求成功之后调用该回调函数输出结果
})
})
</script>
<!-- 返回结果显示 -->
<script>
function ShowResult(data) {
output.value = data['output'];
}
</script>
<script>
document.getElementById("output").style.width="400px";
document.getElementById("output").style.height="350px";
</script>
后端代码
from django.shortcuts import render
# Create your views here.
def product(request):
return render(request, 'product.html',{'active_menu': 'about','sub_menu': 'product1',})
def system(request):
return render(request, 'system.html',{'active_menu': 'about','sub_menu': 'product2',})
# 人脸识别
import numpy as np # 矩阵运算
import urllib # url解析
import json # json字符串使用
import cv2 # opencv包
import os # 执行操作系统命令
from django.views.decorators.csrf import csrf_exempt # 跨站点验证
from django.http import JsonResponse # json字符串响应
from PIL import Image
import keras.models
import numpy as np
import tensorflow as tf
from keras.preprocessing import image
def read_image(stream=None):
if stream is not None:
data_temp = stream.read()
img = np.asarray(bytearray(data_temp), dtype="uint8")
img = cv2.imdecode(img, cv2.IMREAD_COLOR)
return img
face_detector_path = "productapp\\haarcascade_frontalface_default.xml"
face_detector = cv2.CascadeClassifier(face_detector_path) # 生成人脸检测器
@csrf_exempt # 用于规避跨站点请求攻击
def facedetect(request):
result = {}
if request.method == "POST": # 规定客户端使用POST上传图片
if request.FILES.get("image", None) is not None: # 读取图像
img = read_image(stream=request.FILES["image"])
else:
result.update({
"#faceNum": -1,
})
return JsonResponse(result)
if img.shape[2] == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 彩色图像转灰度图像
#进行人脸检测
values = face_detector.detectMultiScale(img,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
# 将检测得到的人脸检测关键点坐标封装
values = [(int(a), int(b), int(a + c), int(b + d))
for (a, b, c, d) in values]
result.update({
"#faceNum": len(values),
"faces": values,
})
return JsonResponse(result)
import base64
@csrf_exempt
def facedetectDemo(request):
result = {}
if request.method == "POST":
if request.FILES.get('image') is not None: #
img = read_image(stream=request.FILES["image"])
else:
result.update({ "#faceNum" : -1,})
return JsonResponse(result)
if img.shape[2] == 3:
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 彩色图像转灰度图像
else:
imgGray = img
#进行人脸检测
values = face_detector.detectMultiScale(img,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
#将检测得到的人脸检测关键点坐标封装
values = [(int(a), int(b), int(a + c), int(b + d))
for (a, b, c, d) in values]
# 将检测框显示在原图上
for (w, x, y, z) in values:
cv2.rectangle(img, (w, x), (y, z), (0, 255, 0), 2)
retval, buffer_img = cv2.imencode('.jpg', img) # 在内存中编码为jpg格式
img64 = base64.b64encode(buffer_img) # base64编码用于网络传输
img64 = str(img64, encoding='utf-8') # bytes转换为str类型
result["img64"] = img64 # json封装
return JsonResponse(result)
@csrf_exempt # 用于规避跨站点请求攻击
def imgdetect(request):
result = {"code":None}
if request.method == "POST": # 规定客户端使用POST上传图片
if request.FILES.get("image", None) is not None: # 读取图像
img = read_image(stream=request.FILES["image"])
model = keras.models.load_model("E:\demo1\productapp\model.h5")
classes = ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# img=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
img=image.load_img(img,target_size=(224,224,))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
test_img = img_data / 255 # 此处还需要将0-255转化为0-1
# test_img = np.expand_dims(test_img, 0) # 将三维输入图像拓展成四维张量
pred = model.predict(test_img) # 预测
print('预测结果:', end='')
code=classes[pred.argmax()]
result.update({"output":code})
return JsonResponse(result)
运行结果及报错内容
当我点识别的时候
出现了这个错误
请问这个要怎么解决呀害