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

Time:09-18

I was trying gray level slicing.

This is my whole code, I am trying to convert the image into gray scale without disturbing the background:

def without_background(img_path, save_path):
    image = Image.open(img_path)
    img_array = np.array(image,dtype=np.uint8)
    img_shape=(image.width,image.height)
    display(image)
    
    for i in range(img_shape[1]):
        for j in range(img_shape[0]):
            v = img_array[i][j]
            if(v>=0 and v<=50):
                print(img_array[i][j]
                img_array[i][j]=255
            else:
                img_array[i][j]=0

    resultImage = Image.fromarray(img_array)
    resultImage.save(save_path)
    display(resultImage)

This is error:

ValueError                                Traceback (most recent call last)
<ipython-input-23-a6d36de00a06> in <module>()
      2         for j in range(img_shape[0]):
      3             v = img_array[i][j]
----> 4             if(v>=0 and v<=50):
      5               print(img_array[i][j])

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

CodePudding user response:

Images have three dimensions. see this example you know where you are wrong. if you want check v you need iterate over v like below:

from PIL import Image

image = Image.open('1.png')
img_array = np.array(image,dtype=np.uint8)
print(img_array.shape) # (820, 892, 4)


img_shape=(image.width,image.height)
for i in range(img_shape[1]):
    for j in range(img_shape[0]):
        v = img_array[i][j]
        print(type(v.shape)) # <class 'tuple'>
        for k in v: # add this line
            if (k>=0 and k<=50):
                print(img_array[i][j])
                img_array[i][j]=255
            else:
                img_array[i][j]=0

CodePudding user response:

In your example img_array[i][j] returns an np.array (and not just a single value), because it returns the RGB values of the pixel.

If your image is already grayscale and all 3 values are identical, you can just take e.g. the first one (red) like this:

v = img_array[i][j][0]

If your image is not yet grayscale you probably want to take the average for each value:

v = img_array[i][j].mean()

... or potentially do some more complex math on it.

What the error actually means

Let's take this little example:

>>> arr = np.array(range(4))
>>> arr
array([0, 1, 2, 3])
>>> arr > 1
array([False, False, True,  True])

What we get back from this comparison is not just a single boolean value, but an entirely new np.array filled with the result of each single comparison. Basically expanded like this:

[0 > 1, 1 > 1, 2 > 1, 3 > 1]

When you now try to convert this np.array into a single boolean value...

>>> if arr > 1: # which basically does: bool(arr > 1)
...   pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

... you get exactly this error.

You have two options, which the error message kindly provides you:

  1. Use (arr > 1).all() which is true if all values are greater than 1.
  2. Use (arr > 1).any() which is true if any value is greater than 1.
  • Related