简体   繁体   中英

The truth value of an array with more than one element is ambiguous Python error

I need to detect if image is pizelized or not. So i use a python code, that was taken from other stackoverflow post:

import numpy as np
from PIL import Image, ImageChops

im = Image.open('img/low2.jpg')    
im2 = im.transform(im.size, Image.AFFINE, (1,0,1,0,1,1))
im3 = ImageChops.subtract(im, im2)
im3 = np.asarray(im3)
im3 = np.sum(im3,axis=0)[:-1]
mean = np.mean(im3)

peak_spacing = np.diff([i for i,v in enumerate(im3) if v > mean*2])

mean_spacing = np.mean(peak_spacing)
std_spacing = np.std(peak_spacing)

I'm getting this error:

File "pixelated.py", line 11, in peak_spacing = np.diff([i for i,v in enumerate(im3) if v > mean*2]) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How can i fix this? I'm newbie in Python, please give me any idea or help.

The problem is v > mean*2 which results in an array of boolean values.

The boolean value of such array is ambiguous for if . As the error text advises, you need to tell Python, whether all of values are expected to be True :

(v > mean * 2).all()

or if any of them is enough:

(v > mean * 2).any()

It looks like v is a numpy array. When you're comparing a numpy array with something, a new array of booleans is generated. This means that v > m*2 generates an array (for example [True, False, False, ... True] ). It is impossible to get single boolean value from such a list and use it in the if expression. So, try to use np.any(v > m*2) or np.all(v > m*2) depending on your code logic.

Also it seems that this code works well with grayscale images. But fails in the following way with RGB. So, try to convert the image to grayscale

im = im.convert("L")  

just after the image initialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM