Milan
Milan

Reputation: 356

How to change shape with tf.strided_slice() in TensorFlow?

As an example: We have two RGB images of the size 2x2x3 pixels. Each of the four pixels is represented by 3 interges. The interges are available as a 2D array. The first 4 interges represent the red values, the next 4 interges the green values and the last 4 interges the blue values of the 4 pixels.

Image 1:

[11, 12, 13, 14, 15, 16, 17, 18, 19, 191, 192, 193]

Image 2:

[21, 22, 23, 24, 25, 26, 27, 28, 29, 291, 292, 293]

In TensorFlow this two images are stored in a Tensor

img_tensor = tf.constant([[11, 12, 13, 14, 15, 16, 17, 18, 19, 191, 192, 193],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 291, 292, 293]])
# Tensor("Const_10:0", shape=(2, 12), dtype=int32)

After using tf.strided_slice() i want the follwing format:

[[[[11, 15, 19],
[12, 16, 191]],
[[13, 17, 192],
[14, 18, 193]]],
[[[21, 25, 29],
[22, 26, 291]],
[[23, 27, 292],
[24, 28, 293]]]]
# Goal is: Tensor("...", shape=(2, 2, 2, 3), dtype=int32)

What I have tried so far:

new_img_tensor = tf.strided_slice(img_tensor, [0, 0], [3, -1], [1, 4])

But the result is incomplete:

[[11 15 19]
 [21 25 29]]
# Tensor("StridedSlice_2:0", shape=(2, 3), dtype=int32)

Is there a way to change the dimension from 2D to 4-D, using tf.strided_slice()

Upvotes: 0

Views: 612

Answers (1)

akuiper
akuiper

Reputation: 214957

Seems you need reshape + transpose instead of strided_slice:

tf.InteractiveSession()
tf.transpose(tf.reshape(img_tensor, (2, 3, 2, 2)), (0, 2, 3, 1)).eval()

#array([[[[ 11,  15,  19],
#         [ 12,  16, 191]],

#        [[ 13,  17, 192],
#         [ 14,  18, 193]]],


#       [[[ 21,  25,  29],
#         [ 22,  26, 291]],

#        [[ 23,  27, 292],
#         [ 24,  28, 293]]]])

Upvotes: 1

Related Questions