[英]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: 所以我使用了一个python代码,该代码取自其他stackoverflow帖子:
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. 文件“ pixelated.py”,第11行,peak_spacing = np.diff([如果v>均值* 2,[i表示枚举(im3)中的i,v])ValueError:具有多个元素的数组的真值是暧昧。 Use a.any() or a.all() 使用a.any()或a.all()
How can i fix this? 我怎样才能解决这个问题? I'm newbie in Python, please give me any idea or help. 我是Python的新手,请给我任何想法或帮助。
The problem is v > mean*2
which results in an array of boolean values. 问题是v > mean*2
导致布尔值数组。
The boolean value of such array is ambiguous for if
. 这种数组的布尔值对于if
是不明确的。 As the error text advises, you need to tell Python, whether all of values are expected to be True
: 正如错误文本所建议的那样,您需要告诉Python是否所有值都应为True
:
(v > mean * 2).all()
or if any of them is enough: 或者其中任何一个就足够了:
(v > mean * 2).any()
It looks like v
is a numpy array. 看起来v
是一个numpy数组。 When you're comparing a numpy array with something, a new array of booleans is generated. 当您将numpy数组与某些内容进行比较时,将生成一个新的布尔数组。 This means that v > m*2
generates an array (for example [True, False, False, ... True]
). 这意味着v > m*2
生成一个数组(例如[True, False, False, ... True]
)。 It is impossible to get single boolean value from such a list and use it in the if
expression. 从这样的列表中获取单个布尔值并在if
表达式中使用它是不可能的。 So, try to use np.any(v > m*2)
or np.all(v > m*2)
depending on your code logic. 因此,根据您的代码逻辑,尝试使用np.any(v > m*2)
或np.all(v > m*2)
。
Also it seems that this code works well with grayscale images. 同样,该代码似乎也可以用于灰度图像。 But fails in the following way with RGB. 但是使用RGB不能以下列方式失败。 So, try to convert the image to grayscale 因此,尝试将图像转换为灰度
im = im.convert("L")
just after the image initialization 在图像初始化之后
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.