如何使用 pyglet 显示 numpy 数组?
我有一个尺寸为 (100*100) 的标签矩阵,存储为 numpy 数组,我想用 pyglet 显示该矩阵。
我最初的想法是使用这个矩阵通过函数 pyglet.image.ImageData() 形成一个新的 pyglet 图像。它需要图像数据的缓冲区作为输入,但是我不知道如何从 numpy 数组中获取正确格式的缓冲区。
有人有任何想法吗?
附:我当前的解决方案:
3d_label = numpy.empty([100,100,3])
3d_label[:,:,0] = label * 255 # value range of label is [0,1]
3d_label[:,:,1] = label * 255
3d_label[:,:,2] = label * 255
image_data = ctypes.string_at(id(3d_label.tostring())+20, 100*100*3)
image = pyglet.image.ImageData(100, 100, 'RGB', image_data, -100*3)
有没有更好的方法用 numpy 从 3 [100*100] 矩阵构建 [100*100*3] 矩阵?
I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet.
My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). It requres a buffer of the imagedata as an input, however I have no idea how to get a right formated buffer from the numpy array.
Any one have any idea?
ps. my current solution:
3d_label = numpy.empty([100,100,3])
3d_label[:,:,0] = label * 255 # value range of label is [0,1]
3d_label[:,:,1] = label * 255
3d_label[:,:,2] = label * 255
image_data = ctypes.string_at(id(3d_label.tostring())+20, 100*100*3)
image = pyglet.image.ImageData(100, 100, 'RGB', image_data, -100*3)
Any better way to construct a [100*100*3] matrix from 3 [100*100] matrix with numpy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您正在寻找的是
np.dstack
(或者更一般地说,np.concatenate
):这表明
dstack
生成相同的数组(label3
)作为您的label_3d
构造:PS。我不确定,但是您是否尝试过使用
label3.data
而不是ctypes.string_at(id(label3.tostring())+20, 100*100*3)
?I think what you are looking for is
np.dstack
(or more generally,np.concatenate
):This shows
dstack
produces the same array (label3
) as your construction forlabel_3d
:PS. I'm not sure, but have you tried using
label3.data
instead ofctypes.string_at(id(label3.tostring())+20, 100*100*3)
?您可以使用 3d_label.tostring() 获取数组的内存表示形式。
tostring()
方法允许您更改元素的内存顺序:PS:~unutbu 的
3d_label.data
需要更少的内存,因为没有构建字符串。但是,它不允许您更改元素的输出顺序。You can get the memory representation of your array with
3d_label.tostring()
.The
tostring()
method allows you to change the memory ordering of the elements:PS: The
3d_label.data
of ~unutbu requires less memory, since no string is constructed. However, it does not allow you to change the order in which the elements are output.