层 "sequential_3" 的输入 0 与层不兼容: expected shape=(None, 256, 256, 3), found shape=(None, 324, 500, 3)

Input 0 of layer "sequential_3" is incompatible with the layer: expected shape=(None, 256, 256, 3), found shape=(None, 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)

这是我的模型,效果很好,但是当我 post 任何尺寸的图像不同于 postman

的 256,256 时
@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)

这就是我的禁食apireturns->

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

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

什么是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)

您需要在使用前调整图片大小:

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.resize(img, (256,256,3)

相反,您只需提及像素大小 img = cv2.resize(img, dsize = (256, 256))