简体   繁体   中英

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

error is..

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].

Your conv2D kernel [filter_height, filter_width, in_channels, out_channels] expects that the input image has 3 channels and it's a 4D tensor with shape [batch, in_height, in_width, in_channels] whereas you have load the input image in grayscale format. Therefore you need to load the color image having 3 channels:

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

Hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM