我正在构建一个图像处理分类器,这个代码是一个API,用于预测图像的类别。整个代码都在运行,除了这行(pred = model.predict_classes(test_image))。这个API是用Django框架构建的,我使用的是Python 2.7。
这里要指出的是,如果我像平常一样运行这个代码(不制作API),它运行得非常完美。
def classify_image(request):
if request.method == 'POST' and request.FILES['test_image']:
fs = FileSystemStorage()
fs.save(request.FILES['test_image'].name, request.FILES['test_image'])
test_image = cv2.imread('media/'+request.FILES['test_image'].name)
if test_image is not None:
test_image = cv2.resize(test_image, (128, 128))
test_image = np.array(test_image)
test_image = test_image.astype('float32')
test_image /= 255
print(test_image.shape)
else:
print('image didnt load')
test_image = np.expand_dims(test_image, axis=0)
print(test_image)
print(test_image.shape)
pred = model.predict_classes(test_image)
print(pred)
return JsonResponse(pred, safe=False)
回答:
你的test_image和TensorFlow模型的输入不匹配。
# 你的图像形状是(, , 3)
test_image = cv2.imread('media/'+request.FILES['test_image'].name)
if test_image is not None:
test_image = cv2.resize(test_image, (128, 128))
test_image = np.array(test_image)
test_image = test_image.astype('float32')
test_image /= 255
print(test_image.shape)
else:
print('image didnt load')
# 你的图像形状是(, , 4)
test_image = np.expand_dims(test_image, axis=0)
print(test_image)
print(test_image.shape)
pred = model.predict_classes(test_image)
以上只是假设。如果你想调试,我建议你打印出你的图像大小,并与模型定义的第一层布局进行比较。检查尺寸(宽度、高度、深度)是否匹配。