2016-03-06 82 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

相關問題