我想用 TensorFlow 识别图像。我收到形状错误,但我该怎么办?

I want to recognize an image with TensorFlow. I'm getting a shape error, but what do I do?

GmdMiss_Folder = os.path.join(os.getcwd(), '..', 'Photo', 'GMD Miss')
GmdMiss_List = os.listdir(GmdMiss_Folder)
for i in range(0, len(GmdMiss_List)):
    Img = os.path.join(os.getcwd(), GmdMiss_Folder, GmdMiss_List[i])
    Img = cv2.imread(Img, cv2.IMREAD_GRAYSCALE)
    Img = np.array(Img)
    Img = cv2.resize(Img, dsize=(1920, 1080), interpolation=cv2.INTER_AREA)
    Img_Miss_List.append(Img)
i=0

while True:
    Img = Img_Miss_List[i]
    with tf.Session() as sess:
        graph = tf.Graph()
        with graph.as_default():
            with tf.name_scope("Convolution"):
                Img = Convolution(Img)
i += 1

...
The codes below are omitted
...
def Convolution(img):
    kernel = tf.Variable(tf.truncated_normal(shape=[180, 180, 3, 3], stddev=0.1))
    img = img.astype('float32')
    img = tf.nn.conv2d(np.expand_dims(img, 0), kernel, strides=[ 1, 15, 15, 1], padding='VALID')
    return img

错误是..

ValueError: Shape must be rank 4 but is rank 3 for 'Convolution/Conv2D' (op: 'Conv2D') with input shapes: [1,1080,1920], [180,180,3,3].

你的 conv2D 内核 [filter_height, filter_width, in_channels, out_channels] 期望输入图像有 3 个通道,它是一个形状为 [batch, in_height, in_width, in_channels] 的 4D 张量,而你已经加载了灰度格式的输入图像。因此,您需要加载具有 3 个通道的彩色图像:

Img = cv2.imread(Img)  # By default cv2 load image in BGR format
Img = cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)  # convert BGR to RGB format

希望对您有所帮助。