brainer
brainer

Reputation: 115

I am creating a CNN function with TensorFlow, but I get a Shape related error

I tried Convolution Neural Network with Tensorflow.

However, Shape causes an error.

First is part of the main function.

while True:
        with mss.mss() as sct:
                Game_Scr = np.array(sct.grab(Game_Scr_pos))[:,:,:3]

                cv2.imshow('Game_Src', Game_Scr)
                cv2.waitKey(0)

                Game_Scr = cv2.resize(Game_Scr, dsize=(960, 540), interpolation=cv2.INTER_AREA)
                print(Game_Scr.shape)

                print(Convolution(Game_Scr))

Second is my called function.

def Convolution(img):
        kernel = tf.Variable(tf.truncated_normal(shape=[4], stddev=0.1))
        sess = tf.Session()
        with tf.Session() as sess:
                img = img.astype('float32')
                Bias1 = tf.Variable(tf.truncated_normal(shape=[4],stddev=0.1))
                conv2d = tf.nn.conv2d(img, kernel, strides=[1, 1, 1, 1], padding='SAME')# + Bias1
                conv2d = sess.run(conv2d)
        return conv2d

ValueError: Shape must be rank 4 but is rank 3 for 'Conv2D' (op: 'Conv2D') with input shapes: [540,960,3], [4].

I tried changing the shape many times, but I get the same error.

Upvotes: 0

Views: 84

Answers (2)

KrisR89
KrisR89

Reputation: 1541

Try replacing

img = img.astype('float32')

with

img = tf.expand_dims(img.astype('float32'), 0)

The dimention of tf.nn.conv2d input shoul be 4, (batch_size, image_hight, image_with, image_channels). You where missing the batch_size, tf.expand_dims just add that dimention (with a batch_size of 1 since you only have one image).

Upvotes: 1

Anubhav Singh
Anubhav Singh

Reputation: 8719

As per the official documentation here, input tensor should be of shape [batch, in_height, in_width, in_channels] and a filter / kernel tensor should be of shape [filter_height, filter_width, in_channels, out_channels].

Try by changing your Convolution function to something like this:

def Convolution(img):
        kernel = tf.Variable(tf.truncated_normal(shape=[200, 200, 3, 3], stddev=0.1))
        sess = tf.Session()
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            img = img.astype('float32')
            conv2d = tf.nn.conv2d(np.expand_dims(img, 0), kernel, strides=[1, 1, 1, 1], padding='SAME')# + Bias1
            conv2d = sess.run(conv2d)
        return conv2d

Upvotes: 0

Related Questions