2016-03-06 83 views
0

我想要一个彩色图像并将其转换为二进制图像,其中接近黑色或白色返回False,并且所有中间值返回True。Python - 使用中间值转换为二进制彩色图像

以下两个条件同时施加的正确语法是什么?

binary = color.rgb2gray(img) > 0.05 
binary = color.rgb2gray(img) < 0.95 

如果我用这个:

%matplotlib inline 
import numpy as np 
import matplotlib.pyplot as plt 
from skimage import color 
import requests 
from PIL import Image 
from StringIO import StringIO 

url = 'https://mycarta.files.wordpress.com/2014/03/spectrogram_jet.png' 
r = requests.get(url) 
img = np.asarray(Image.open(StringIO(r.content)).convert('RGB')) 

然后:

binary = color.rgb2gray(img) < 0.95 

我会得到,我可以绘制一个合适的二进制图像:

fig = plt.figure(figsize=(10,10)) 
ax = fig.add_subplot(111) 
plt.imshow(binary, cmap='gray') 
ax.xaxis.set_ticks([]) 
ax.yaxis.set_ticks([]) 
plt.show() 

同样与此:

color.rgb2gray(img) < 0.95 

但是,如果我想他们这样在一起:

binary = color.rgb2gray(img) > 0.05 and color.rgb2gray(img) < 0.95 

我得到这个消息:

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

+0

你跑什么代码“一起尝试”? –

+0

与@ caenyon的回答建议一样:binary = color.rgb2gray(img)> 0.05 and color.rgb2gray(img)<0.95 – MyCarta

+0

什么是img变量?一个完整的例子会更容易(导入等) – Felix

回答

2

由于skimage.colorrgb2gray方法返回数组,因此您的代码不起作用。 skimage模块利用拒绝在阵列上执行布尔比较的numpy模块。这是您的ValueError从何而来。

在阵列上使用像and这样的比较运算符时,numpy将不符合。相反,您应该使用np.logical_and或二元运算符&

+0

你的建议奏效了,谢谢你的解释 – MyCarta

-1

你可以使用 '和' 这两个条件结合起来

binary = color.rgb2gray(img) > 0.05 and color.rgb2gray(img) < 0.95 

或者你可以把它们写成一个条件

binary = 0.05 < color.rgb2gray(img) < 0.95 
+0

当我尝试这两个选项,你建议,在这两种情况下(第一个是我之前尝试过),我得到错误消息 – MyCarta

+0

color.rgb2gray函数返回什么?你确定这是一个数字而不是一个列表吗? – Felix

+0

你的程序的其余部分是怎样的?我假设问题是在别的地方... – Felix

相关问题