简体   繁体   中英

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM