user3062459
user3062459

Reputation: 1631

Change values inside array based on logic - Python

I have an array (called 'img') that I want to modify.

img
array([[[244, 244, 244],
    [248, 248, 248],
    [249, 249, 249],

I want to change the values in the array to 0 if they are below 200 and convert to 255 if they are above or equal to 200:

for value in img:
    if value < 200:
         value = 0
    else:
         value = 255

However, I am getting this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How can I get this code to work?

Upvotes: 0

Views: 1009

Answers (2)

user3062459
user3062459

Reputation: 1631

Simple solution using Numpy where method. Pass Logic as first argument, if True (second argument), if False (third argument).

img = np.where(img<200.0, 0.0, 255.0)

Upvotes: 0

user2285236
user2285236

Reputation:

You can use a boolean array in np.where:

np.where(img<200, 0, 255)

For the example you provided all values are above 200 so it will return 255 all the time but for 245:

np.where(img<245, 0, 255)
Out[4]: 
array([[[  0,   0,   0],
        [255, 255, 255],
        [255, 255, 255]]])

Upvotes: 1

Related Questions