2016-08-05 37 views
0

我有上面列出的錯誤,但一直無法找到它的含義。我是numpy和它的{.frombuffer()}命令的新手。其中該錯誤觸發的代碼是:numpy.frombuffer ValueError:緩衝區小於請求的大小

ARRAY_1=400000004 
fid=open(fn,'rb') 
fid.seek(w+x+y+z) #w+x+y+z= 
if(condition==0): 
    b=fid.read(struct.calcsize(fmt+str(ARRAY_1)+'b')) 
    myClass.y = numpy.frombuffer(b,'b',struct.calcsize(fmt+str(ARRAY_1)+'b')) 
else: 
    b=fid.read(struct.calcsize(fmt+str(ARRAY_1)+'h')) 
    myClass.y = numpy.frombuffer(b,'h',struct.calcsize(fmt+str(ARRAY_1)+'h')) #error this line 

其中FMT是 '>',其中條件== 0和 '<',其中條件!= 0。這正在改變二進制文件的讀取方式,大端或小端。 fid是一個已經打開的二進制文件。

調試到這一點,條件= 1,所以我有一種感覺,如果條件的最後一個語句也有錯誤,我現在只是看不到它。

正如我之前所說,我試圖找出錯誤的含義,但沒有任何運氣。如果有人知道它爲什麼會出現在我身上,我真的很喜歡這個幫助。

+0

你可以發佈更多的代碼嗎?如果我們知道二進制文件如何存儲到'fid',以及設置了「ARRAY_1」,那麼我認爲這會有所幫助。 – Frangipanes

+0

@Frangipanes我按照你的要求添加了更多的代碼,但我不確定它會有多大的幫助。 – SanticL

+0

您是否也可以包含您的進口產品,以便我們也瞭解您使用的模塊? – Frangipanes

回答

0

calcsize給出了緩衝區給出格式的字節數。

In [421]: struct.calcsize('>100h') 
Out[421]: 200 
In [422]: struct.calcsize('>100b') 
Out[422]: 100 

h需要每項目2個字節,所以對於100個項目,它給200個字節。

對於frombuffer,第三個參數是

count : int, optional 
Number of items to read. ``-1`` means all data in the buffer. 

所以我應該給它100,不200

讀一個簡單的字節串(在PY 3):

In [429]: np.frombuffer(b'one two three ','b',14) 
Out[429]: array([111, 110, 101, 32, 116, 119, 111, 32, 116, 104, 114, 101, 101, 32], dtype=int8) 

In [430]: np.frombuffer(b'one two three ','h',14) 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-430-30077e924a4c> in <module>() 
----> 1 np.frombuffer(b'one two three ','h',14) 

ValueError: buffer is smaller than requested size 

In [431]: np.frombuffer(b'one two three ','h',7) 
Out[431]: array([28271, 8293, 30580, 8303, 26740, 25970, 8293], dtype=int16) 

要與h我需要給它b讀的一半計數閱讀。

+0

我明白了,所以我問的太多了?當我使用'h'時,我需要縮小一半所需的尺寸。 我可以使用-1嗎?或者這會讓它不夠優化? – SanticL