【问题标题】:numpy.frombuffer ValueError: buffer is smaller than requested sizenumpy.frombuffer ValueError:缓冲区小于请求的大小
【发布时间】:2016-08-05 13:44:35
【问题描述】:

我有上面列出的错误,但一直无法找到它的含义。我是 numpy 及其 {.frombuffer()} 命令的新手。触发此错误的代码是:

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 是 '>' where condition==0 和 '二进制文件的读取方式,大端或小端。 fid 是已经打开的二进制文件。

调试到这一步,condition=1,所以感觉if条件的最后一条语句也有错误,只是现在没看到。

正如我之前所说,我试图找出错误的含义,但没有任何运气。如果有人知道为什么我会出错,我真的很想得到帮助。

【问题讨论】:

  • 你能发布更多你的代码吗?我认为如果我们知道二进制文件是如何存储到fid,以及ARRAY_1 的设置位置会有所帮助。
  • @Frangipanes 我按照你的要求添加了更多代码,但我不确定它会有多大帮助。
  • 能否也包括您的导入,以便我们也知道您正在使用的模块?
  • 对于初学者来说,使用frombuffer 读取文件听起来相当高级。我用的不多。对于'h' dtype,它每项读取 2 个字节,而'b' 仅使用一个。因此,对于相同大小的缓冲区,您需要不同的计数计算。你比较过calcsize 的结果吗?

标签: python numpy buffer


【解决方案1】:

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

读取一个简单的字节串(在 Py3 中):

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 读取的一半。

【讨论】:

  • 我明白了,所以我要求太多了?当我使用“h”时,我需要缩小一半。我也可以使用-1吗?还是会降低优化程度?
猜你喜欢
  • 2011-02-08
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 2014-06-10
  • 2015-06-05
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多