0

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?

1
  • You are currently iterating through the img variable, which is a two dimensional list. So value is a list as well. Commented Apr 29, 2016 at 13:29

2 Answers 2

1

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

Comments

0

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)

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.