IsaacLevon
IsaacLevon

Reputation: 2570

How to stack multiple numpy 2d arrays into one 3d array?

Here's my code:

img = imread("lena.jpg")
for channel in range(3):
    res = filter(img[:,:,channel], filter)
    # todo: stack to 3d here

As you can see, I'm applying some filter for every channel in the picture. How do I stack them back to a 3d array? (= the original image shape)

Thanks

Upvotes: 2

Views: 1612

Answers (2)

SpghttCd
SpghttCd

Reputation: 10860

I'd initialize a variable with the needed shape before:

img = imread("lena.jpg")
res = np.zeros_like(img)     # or simply np.copy(img)
for channel in range(3):
    res[:, :, channel] = filter(img[:,:,channel], filter)

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use np.dstack:

import numpy as np

image = np.random.randint(100, size=(100, 100, 3))

r, g, b = image[:, :, 0], image[:, :, 1], image[:, :, 2]

result = np.dstack((r, g, b))

print("image shape", image.shape)
print("result shape", result.shape)

Output

image shape (100, 100, 3)
result shape (100, 100, 3)

Upvotes: 1

Related Questions