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

时间:2019-11-03 06:44:30

标签: arrays python-3.x tensorflow python-3.6 reshape

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:形状必须为4级,但形状为3级   输入形状为[1,1080,1920]的“卷积/ Conv2D”(操作:“ Conv2D”),   [180,180,3,3]。

1 个答案:

答案 0 :(得分:0)

您的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

希望这会有所帮助。