层“sequential_3”的输入 0 与层不兼容:预期形状=(None, 256, 256, 3),找到形状=(None, 324, 500, 3)
tensorflow 277
原文标题 :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)
这是我的模型,它工作得很好,但是当我从邮递员发布不同于 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)
这是我的快速 api 返回的内容->
层“sequential_3”的输入 0 与层不兼容:预期形状=(None, 256, 256, 3),找到形状=(None, 324, 500, 3)
我尝试从 Pillow 调整图像大小,但没有成功,我对 fastapi 了解不多,所以如果有人知道如何解决此错误,请发表评论。
回复
我来回复-
Gerry P 评论
什么是 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)
2年前 -
I'mahdi 评论
在使用此之前,您需要调整图像大小:
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)
2年前