Verych
Verych

Reputation: 441

How to convert 4D array to another 4D with switched dimentions in Python

I'm trying to get Image data from convolution layer in TensorFlow. I have an array like:

data = [N, Width, Height, Channel]

where N is the image number, Width and Height are image dimensions and Channel in the index of channel.

What do I need is another 4D array like:

[N, Channel, Width, Height]

The reason is go in cycle by N and Channel and get 2D array of bytes for the ech channel for the each of image.

img = Image.fromarray(data[N][Channel], 'L')
img.save('my.png')

Upvotes: 0

Views: 508

Answers (2)

chasep255
chasep255

Reputation: 12175

Use the transpose function to reorder the dimensions.

https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#transpose

You would do something like this in the tensorflow code.

image = tf.transpose(image, perm = [0, 3, 1, 2])

In the perm parameter you specify the new order of dimensions you want. In this case you move the channels dimension (3) into the second position.

If you want to do it before inputting it into the tensorflow model you can use np.transpose in the same way.

Upvotes: 1

Olivier Moindrot
Olivier Moindrot

Reputation: 28198

Just use np.transpose:

x = np.zeros((32, 10, 10, 3))  # image with 3 channels, size 10x10
res = np.tranpose(x, (0, 3, 1, 2))
print res.shape  # prints (32, 3, 10, 10)

Upvotes: 1

Related Questions