如何用pyglet显示一个numpy数组? [英] how to display a numpy array with pyglet?
问题描述
我有一个尺寸为(100 * 100)的标签矩阵,存储为一个numpy数组,我想用pyglet显示该矩阵.
I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet.
我的最初想法是使用此矩阵通过函数pyglet.image.ImageData()来形成新的pyglet图像.它需要将imagedata的缓冲区作为输入,但是我不知道如何从numpy数组中获取正确格式的缓冲区.
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.
有人知道吗?
ps.我当前的解决方案:
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)
从numpy的3 [100 * 100]矩阵构造[100 * 100 * 3]矩阵的更好方法吗?
Any better way to construct a [100*100*3] matrix from 3 [100*100] matrix with numpy?
推荐答案
我认为您正在寻找的是np.dstack
(或更常见的是np.concatenate
):
I think what you are looking for is np.dstack
(or more generally, np.concatenate
):
label255=label*255
label3=numpy.dstack((label255,label255,label255))
这表明dstack
会生成与label_3d
相同的数组(label3
):
This shows dstack
produces the same array (label3
) as your construction for label_3d
:
import numpy as np
label=np.random.random((100,100))
label255=label*255
label3=np.dstack((label255,label255,label255))
label_3d = np.empty([100,100,3])
label_3d[:,:,0] = label * 255 # value range of label is [0,1]
label_3d[:,:,1] = label * 255
label_3d[:,:,2] = label * 255
print(np.all(label3==label_3d))
# True
PS.我不确定,但是您尝试使用label3.data
代替ctypes.string_at(id(label3.tostring())+20, 100*100*3)
吗?
PS. I'm not sure, but have you tried using label3.data
instead of ctypes.string_at(id(label3.tostring())+20, 100*100*3)
?
这篇关于如何用pyglet显示一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!