2017-09-02 50 views
0

我想將圖像轉換爲一個numpy數組,當我這樣做時,它給了我在我的標題中提到的錯誤。 回溯錯誤來自行:ValueError:沒有足夠的值來解壓縮(預計2,got1)

nx,ny = np.shape(matrix) 

我的代碼的其餘部分如下。我能否提出一些解決此問題的建議?

#change the quoted part to change directory and 
#file type 
filelist = glob.glob('Desktop/*.png') 

#set Matrix as the numpy array. 
#change the second half were np 
#is used to make the program 
#use a different set of data 

matrix = np.array([np.array(Image.open(fname)) for fname in filelist]) 


#numpy array 
nx,ny = np.shape(matrix) 
CXY = np.zeros([ny, nx]) 
for i in range(ny): 
    for j in range(nx): 
     CXY[i,j] = np.max(matrix[j,i,:]) 

#Binary data 
np.save('/home/l/Desktop/maximums.npy', CXY) 
#Human readable data 
np.savetxt('/home/l/Desktop/maximums.txt', CXY) 
+1

一個建議是包含你的FULL回溯,所以我們知道你在哪裏得到錯誤。 –

+1

'nx,ny = np.shape(矩陣)'如果矩陣只有一個維度,這將是您的錯誤來源。 –

+1

你可以包含錯誤追溯? –

回答

0

當你像這樣構造一個數組時,確保你明白你得到了什麼。特別要驗證形狀和dtype。

matrix = np.array([np.array(Image.open(fname)) for fname in filelist]) 

nx,ny = np.shape(matrix) 

開箱像這隻有當matrix爲2d,也就是,它的形狀是2元組元素,對於每個2個變量中的一個元件。

此索引matrix[j,i,:]表示您期望matrix爲3d。這會產生拆包錯誤,expected 2, got 3

CXY = np.zeros([ny, nx]) 
for i in range(ny): 
    for j in range(nx): 
     CXY[i,j] = np.max(matrix[j,i,:]) 

但是實際的錯誤告訴我們matrix是1d。我懷疑它也是object dtype。這是一個1d陣列數組。

我猜想了一下matrix創建過程中發生了什麼。 Image.open(fname) - 這是做什麼的?打開一個文件?讀它以及?爲什麼是np.array()包裝。但讓我們假設它加載一個2D或3D圖像數組。所有圖像的尺寸是否相同?如果它們不同,則外部的np.array不能將它們組裝成更高維的陣列。相反,它要求製作一個1d對象數組 - 一個數組數組。

總之,請確保您瞭解如何構建matrix以及它產生了什麼。

nx, ny = ...可以得心應手,但它是無情的。如果尺寸錯誤,則會在沒有太多信息的情況下產生錯誤。

相關問題