2015-04-14 92 views
0

我打開圖像並將其轉換爲RGBA值的數組。這裏是我的代碼:Python - 如果語句涉及numpy數組

img = Image.open('17112013.png') 
imgarray = array(img) 
l = imgarray[:,1,1] 
m = imgarray[1,:,1] 
n = imgarray[1,1,:] 
blueCount = 0 
redCount = 0 
flag = 0 

for i in range(0,len(l)): 
    for j in range(0,len(m)): 
     if (imgarray[i,j] == [255,255,255,255]): 
      pass 
     if (imgarray[i,j] == [0,0,0,255] and flag == 0): 
      pass 
     if (imgarray[i,j] == [255,0,0,255] and flag == 0): 
      pass 
     if (imgarray[i,j] == [0,0,255,255]): 
      flag = 1 
      blueCount = blueCount + 1 
     if (imgarray[i,j] == [255,0,0,255] and flag == 1): 
      redCount = redCount + 1 
     if (imgarray[i,j] == [0,0,0,255] and flag == 1): 
      flag = 0 
     if (imgarray[i,j] == [255,255,255,255] and flag == 1): 
      flag = 0 

如果我運行它是這樣的,我收到以下內容:

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

我明白,我需要使用這些爲「如果」包含numpy的陣列報表;然而,我不確定實現這個的正確語法。可能只是愚蠢的,但任何幫助將不勝感激。

+0

針對''[numpy] ambiguous'的搜索SO對這個錯誤消息提出了許多問題。 – hpaulj

回答

0

你可能想是這樣的:

if np.all(imgarray[i,j] == [255,255,255,255]): 

如果imgarray特定片確實[255,255,255,255],那麼相等的比較將返回array([ True, True, True, True], dtype=bool)。正如您已經發現的那樣,您不能指望if直接知道如何處理此布爾數組,但如果數組x中的所有值都等於TrueFalse,函數numpy.all(x)返回True

0

正如錯誤所述,當使用if時,如果數組的邏輯值不清楚,您想要什麼。我假設你只希望如果當前imgarray[i,j]的每個部分都等於比較數組,那麼只需要true。你最好還是使用過多的括號和邏輯運算符來明確你想要的內容。這運行,

import Image 
import numpy as np 

img = Image.open('17112013.png') 
imgarray = np.array(img) 
l = imgarray[:,1,1] 
m = imgarray[1,:,1] 
n = imgarray[1,1,:] 
blueCount = 0 
redCount = 0 
flag = 0 

for i in range(0,len(l)): 
    for j in range(0,len(m)): 
     if (np.all(imgarray[i,j] == [255,255,255,255])): 
      pass 
     if (np.all(imgarray[i,j] == [0,0,0,255]) & flag == 0): 
      pass 
     if (np.all(imgarray[i,j] == [255,0,0,255]) & flag == 0): 
      pass 
     if (np.all(imgarray[i,j] == [0,0,255,255])): 
      flag = 1 
      blueCount = blueCount + 1 
     if (np.all(imgarray[i,j] == [255,0,0,255]) & flag == 1): 
      redCount = redCount + 1 
     if (np.all(imgarray[i,j] == [0,0,0,255]) & flag == 1): 
      flag = 0 
     if (np.all(imgarray[i,j] == [255,255,255,255]) & flag == 1): 
      flag = 0 

不知道這是你需要什麼?