简体   繁体   English

如何使用pyglet显示numpy数组?

[英]how to display a numpy array with 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. 我有一个尺寸为(100 * 100)的标签矩阵,存储为numpy数组,我想用pyglet显示矩阵。

My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). 我最初的想法是使用这个矩阵使用函数pyglet.image.ImageData()形成一个新的pyglet图像。 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. 它需要imagedata的缓冲区作为输入,但是我不知道如何从numpy数组中获得正确的格式化缓冲区。

Any one have any idea? 任何人都有任何想法?

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)

Any better way to construct a [100*100*3] matrix from 3 [100*100] matrix with numpy? 有没有更好的方法从3 [100 * 100]矩阵构造一个[100 * 100 * 3]矩阵与numpy?

I think what you are looking for is np.dstack (or more generally, np.concatenate ): 我认为你要找的是np.dstack (或更一般地说, np.concatenate ):

label255=label*255
label3=numpy.dstack((label255,label255,label255))

This shows dstack produces the same array ( label3 ) as your construction for label_3d : 这表明dstack产生相同的阵列( label3 )作为建设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. PS。 I'm not sure, but have you tried using label3.data instead of ctypes.string_at(id(label3.tostring())+20, 100*100*3) ? 我不确定,但你尝试使用label3.data而不是ctypes.string_at(id(label3.tostring())+20, 100*100*3)

You can get the memory representation of your array with 3d_label.tostring() . 您可以使用3d_label.tostring()获取数组的内存表示。

The tostring() method allows you to change the memory ordering of the elements: tostring()方法允许您更改元素的内存排序:

Parameters
----------
order : {'C', 'F', None}, optional
    Order of the data for multidimensional arrays:
    C, Fortran, or the same as for the original array.

PS: The 3d_label.data of ~unutbu requires less memory, since no string is constructed. PS:该3d_label.data unutbu的〜需要较少的存储器,因为没有字符串构成。 However, it does not allow you to change the order in which the elements are output. 但是,它不允许您更改元素的输出顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM