4

I have an array containing the RGB values of all pixels in an image. Supposing a 4x4 image, the array is of size 48, where the first 16 values are the red values, the next 16 are the green and the last 16 are the blue:

[r0, r1, ..., r15, g0, g1, ..., g15, b0, b1, ..., b14, b15]

Now I want to convert that array to a 4x4 matrix with depth 3 in this form:

[[[r0, g0, b0], ..., [r3, g3, b3]],
  ...
 [[r12, g12, b12], ..., [r15, g15, b15]]]

To do so, I am doing a reshape + transpose + reshape:

import matplotlib.pyplot as plt

N = 4
numpy.random.seed(0)
rrggbb = numpy.random.randint(0, 255, size=N*N*3, dtype='uint8')
imgmatrix = rrggbb.reshape((3, -1)).transpose().reshape((N, N, 3))

plt.imshow(imgmatrix)
plt.show()

enter image description here

Is there a more efficient/short way to do that? (i.e.: with less reshaping/transposing)

1 Answer 1

2

Here is an option with one step less:

rrggbb.reshape((3, N, N)).transpose((1,2,0))
​
(rrggbb.reshape((3, N, N)).transpose((1,2,0)) == imgmatrix).all()
# True

Or you can use np.moveaxis to move axis 0 to the last axis:

np.moveaxis(rrggbb.reshape((3, N, N)), 0, -1)

(np.moveaxis(rrggbb.reshape((3, N, N)), 0, -1) == imgmatrix).all()
#True
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, my mind was telling me there was something not very efficient in there... ^^
Hmm. Not an expert, but I guess your approach should be as efficient, since reshape is almost costless, which just Gives a new shape to an array without changing its data., the transpose is moving data around.
Well, less efficient as it is 3 operations vs 2, but even CPU-time-wise, your implementation seems to be faster (about 30% for small images, which is my use case actually).
Interesting. Thanks for sharing the timing result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.