2

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

2
  • 1
    Collect the res in a list. np.stack(alist, axis=2) can be used to join them into an array on a last channel axis. Commented Dec 21, 2018 at 19:14
  • 2
    You have filter both as a function and variable, beware of that. Also what kind of filter are you using? I don't see your filter variable is changing by the channel, so why not do a 3D filter and avoid the loop? Commented Dec 21, 2018 at 19:31

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

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.