4

Say that I have a RGB image:

from skimage import data
img = data.astronaut()
print(img.shape)  # (512, 512, 3)

Is there a succinct numpy command to unpack it along the color channels:

R, G, B = np.unpack(img, 2)  # ?

What I am doing is using comprehension:

R, G, B = (img[:, :, i] for i in range(3))

But is there no simpler command?

3 Answers 3

4

Alternatively you can use np.rollaxis -

R,G,B = np.rollaxis(img,2)
Sign up to request clarification or add additional context in comments.

Comments

1

You can transpose the length-3 dimension to the front and then unpack it:

R, G, B = img.transpose((2, 0, 1))

1 Comment

I will give some time for anyone else to throw a suggestion, but that is pretty clever. :)
1

Alternatively, you can use np.split:

R, G, B = np.split(img, img.shape[-1], axis=-1)

If your array is of shape (height, width, channel), you can use np.dsplit to split along the depth dimension:

R, G, B = np.dsplit(img, img.shape[-1])

Comments

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.