图层 "sequential_3" 的输入 0 与图层不兼容:预期形状=(无,256,256,3),找到形状=(无,324,500,3)



我有问题,如果有人能帮忙,请评论

input_shape=(BATCH_SIZE,256,256,3)
model=models.Sequential([
resize_and_rescale,
data_augmentation,
layers.Conv2D(32,(3,3), activation="relu", input_shape=input_shape),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64,kernel_size=(3,3), activation="relu"),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64,kernel_size=(3,3), activation="relu"),
layers.MaxPooling2D((2,2)),

layers.Conv2D(64,(3,3), activation="relu"),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64,(3,3), activation="relu"),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64,(3,3), activation="relu"),
layers.MaxPooling2D((2,2)),
layers.Flatten(),
layers.Dense(64,activation="relu"),
layers.Dense(n_classes, activation="softmax")
])
model.build(input_shape=input_shape)

这是我的模型,它运行得很好,但当我从邮递员发布256256以外的任何大小的图像时

@app.post("/predict")
async def predict(
file: UploadFile = File(...)
):
image = read_file_as_image(await file.read())
img_batch = np.expand_dims(image, 0)
predictions = MODEL.predict(img_batch)
predicted_class = CLASS_NAMES[np.argmax(predictions[0])]
confidence = np.max(predictions[0])
return {
'class': predicted_class,
'confidence': float(confidence)
}
if __name__ == "__main__":
uvicorn.run(app, host='localhost', port=8000)

这就是我的快速api返回的内容->

"层"的输入0;序列3";与层不兼容:预期形状=(无,256256,3(,发现形状=(没有,324500,3(

我试着从Pillow调整图像大小,但没有成功,我对fastapi不太了解,所以如果有人知道如何解决这个错误请评论。

在使用之前,您需要调整图像大小

import cv2
...
image = read_file_as_image(await file.read())
image = cv2.resize(image, (256,256,3))
img_batch = np.expand_dims(image, 0) 
# OR
img_batch = image[None,...]
...

更多说明:

>>> import numpy as np
>>> a = np.array([[1,2],[2,3]])
>>> a.shape
(2, 2)
>>> a[None, ...].shape
(1, 2, 2)
>>> np.expand_dims(a, 0).shape
(1, 2, 2)

小更正,下面的代码不正确img=cv2.调整大小(img,(256256,3(

相反,你只需要提到像素大小img=cv2.resize(img,dsize=(256256((

什么是read_file_as_image(await file.read(((,它是您编写的函数吗?试试这个

import matplotlib.pyplot as plt
import cv2
img_path= define the full path to the image here
img=plt.imread(img_path)
img=cv2.resize(img, (256,256,3)
img=np.expand_dims(img, axis=0)
print (img.shape)

相关内容

最新更新