为什么我们将灰度图像重塑为 (x,y,1)?

why do we reshape grayscale image to (x,y,1)?

我在用灰度图像训练 CNN 时注意到了这一点。图像的尺寸被重塑为 (x,y,1)。我认为这不是必需的,但是当我尝试使用形状 (x,y) 时。我收到一个错误

ValueError: Input 0 of layer conv2d is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [None, 28, 28]

据我了解,我们这样做的唯一原因是因为 keras 以这种方式实现。还是有其他原因?

keras中第Conv2D层的输入形状为:batch_size + (rows, cols, channels)。因此,该层期望通道数作为最终输入形状,对于灰度图像为 1。对于 RGB 图像,这将是 3.