0

So I have a 3D-array:

>>> img_data.shape
(182, 218, 182)

My idea is to replace every value equals to 0 with 255. I tried:

new_img = np.zeros(img_range)
print(new_img.shape)
for i in range(img_range[0]):
    for j in range(img_range[1]):
        for k in range(img_range[2]):
            print "%s %s %s" % (i, j, k )
            if img_data[i][j][k] == 0:
                new_img[i][j][k] = 2
            else:
                new_img[i][j][k] = img_data[i][j][k]

But this take forever, most likely because Python is dynamic and may be doing something in the backgrouns.

Any ideas on how to improve this? Thanks, Rodrigo

1 Answer 1

1

You don't need to write your own loop. You can access all the elements respecting one or more conditions using the square brackets []. Check the boolean array indexing.

Example:

import numpy as np

a = np.random.randint(0, 5, size=(10, 10, 10))
a[a == 0] = -100
Sign up to request clarification or add additional context in comments.

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.