我已经建立了CNN模型,并且能够很好地进行分类。但是我想尝试使用Django在URL中传递图像时对图像的类进行分类。这是我尝试过的几件事。我的apps.py中的预测功能
def prediction(image_loc):
image_path = 'D:/Discern/'
image = cv2.imread(os.path.join(image_path,image_loc))
print("image in matrix is ", image)
output = image.copy()
# Pre-Process the image for classification
image = cv2.resize(image, (96, 96))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
# Load the trained convolutional neural network and the label binarizer
print("[INFO] Loading Model...")
model_RP = load_model(os.path.join(os.getcwd(), "model\cnn_model_RP.hdf5"))
lb_path = os.path.join(os.getcwd(),"model\labelbin_RP")
lb_RP = pickle.loads(open(lb_path, "rb").read())
print("[INFO] Model Loading Complete.")
# Classify the input image
print("[INFO] classifying image...")
proba = model_RP.predict(image)[0]
idx = np.argmax(proba)
label = lb_RP.classes_[idx]
#we will mark our prediction as "correct" of the input image filename contains the predicted label text
#(obviously this makes the assumption that you have named your testing image files this way)
filename = image_loc[image_loc.rfind(os.path.sep) + 1:]
correct = "correct" if filename.rfind(label) != -1 else "incorrect"
# Build the label and draw the label on the image
label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
output = imutils.resize(output, width=400)
cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
# show the output image
print("[INFO] {}".format(label))
#plt.imshow(output)
#plt.show()
#return(plt.show())
return(label) #- WORKING
#return HttpResponse(output, content_type = 'image/png')
#resp = HttpResponse("", content_type = 'image/png')
#resp.write('output')
#return resp
label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
return (label)
2.a这是问题所在。我正在尝试返回带有标签的图像。我不成功。
label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
output = imutils.resize(output, width=400)
cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
return HttpResponse(output, content_type = 'image/png')
2.b,这是第二种返回图像的方法,不幸的是失败了。
label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
output = imutils.resize(output, width=400)
cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
resp = HttpResponse("", content_type = 'image/png')
resp.write('output')
return resp
@api_view(['GET']) # Decorator
def call_model(request):
#if request.method == 'GET':
# sentence is the query we want to get the prediction for
params = request.GET.get('image_loc')
# predict method used to get the prediction
resp = prediction(image_loc = params)
# returning JSON response
return Response(resp)
曾尝试查看类似的帖子,但它们与文本有关,因此无法解决我的问题。
[有人可以帮忙。
resp
似乎是一个HttpResponse
对象(不能告诉更多,您没有提供prediction
的代码)。
您必须在Response()
构造函数中创建可序列化的JSON(通常是字典或列表,仅包含字符串/ int /布尔值)。
((顺便说一下,DRF的@api_view
装饰器已过时,@action
在上一个版本中更受欢迎)