0

i have a 92x92x1 array in numpy, and for every value in this array, if the value is greater than 122, than it should be converted to 255, otherwise it should be converted to 0. Previously i have tried;

new_array=[]
for i in arr:
    column=[]
    for j in i:
        if j>122:
            temp=255
        else:
             temp=0
        column.append(j)
    new_array.append(column)
new_array=np.resize(np.array(new_array),(92,92,1))

but there must be a quicker, more elegant, and more pythonic way to do this! IS there any other method for mapping these types of functions to 3D arrays?

1 Answer 1

3

NumPy supports vectorized operations so you do not need a for-loop. You can use boolean indexing and it will apply to all dimensions.

import numpy as np

arr = np.random.randint(0, 255, (92, 92, 1))

arr[arr >= 122] = 255

arr[arr < 122] = 0
Sign up to request clarification or add additional context in comments.

2 Comments

thanks @Nicolas Gervais, although i didn't need to initialise the array with random values, lines 3 and 4 answer the question anyway
It's so other people can easily reproduce the code and verify that it works in a second.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.