numpy数组在pyglet中显示不正确

5 投票
4 回答
3939 浏览
提问于 2025-04-17 11:13

我在用pyglet显示numpy数组时遇到了问题。我找到一个很相似的话题(如何用pyglet显示numpy数组?),并参考了它。我想把数组以灰度显示,但pyglet却显示成了彩色,看看这个图片:https://i.stack.imgur.com/pL6Yr.jpg

def create(self, X,Y):

    IMG = random((X,Y)) * 255
    self.IMG = dstack((IMG,IMG,IMG))

    return self.IMG

def image(self):

    self.img_data = self.create(X,Y).data.__str__()
    self.image = pyglet.image.ImageData(X,Y, 'RGB', self.img_data, pitch = -X*3)

    return self.image

如果我先保存数组再加载,它就能正常显示(不过速度慢得可怕):

def image(self):

    self.im_save=scipy.misc.toimage(self.create(X,Y),cmin=0, cmax=255)
    self.im_save.save('outfile.png')
    self.image = pyglet.image.load('outfile.png')

    return self.image

这样我就得到了我想要的效果:

i.stack.imgur.com/FCY1v.jpg

我找不到第一个代码示例中的错误 :(

编辑:

非常感谢大家的回答。在Bago的提示下,我把这个代码搞定了 :) 而且nfirvine的建议也很合理,因为我只想以灰度显示这个矩阵。

def create(self, X,Y):

        self.IMG = (random((X,Y)) * 255).astype('uint8')

        return self.IMG


def image(self):

        self.img_data = self.create(X,Y).data.__str__()
        self.image = pyglet.image.ImageData(X,Y, 'L', self.img_data)

        return self.image

4 个回答

2

我一直在尝试让numpy数组动态显示。@Rebs的回答有效,但当我想在每一帧更新图像时,效率就变得很低。经过分析,我发现使用ctypes进行值转换是瓶颈,速度可以通过使用ctype类型对象的from_buffer方法来提高,这样可以在numpy数组和GLubyte数组之间共享内存中的底层数据。

下面是一个类,它可以在二维numpy数组和pyglet图像之间进行映射,并使用matplotlib的颜色映射来实现。如果你有一个numpy数组,可以在它周围创建一个ArrayView包装,然后在窗口的on_draw方法中更新并绘制它:

my_arr = np.random.random((nx, ny))
arr_img = ArrayImage(my_arr)

@window.event
def on_draw():
    arr_img.update()
    arr_img.image.blit(x, y)

完整的类实现:

import numpy as np
import matplotlib.cm as cmaps
from matplotlib.colors import Normalize
import pyglet
import pyglet.gl

class ArrayImage:
    """Dynamic pyglet image of a 2d numpy array using matplotlib colormaps."""
    def __init__(self, array, cmap=cmaps.viridis, norm=None, rescale=True):
        self.array = array
        self.cmap = cmap
        if norm is None:
            norm = Normalize()
        self.norm = norm
        self.rescale = rescale

        self._array_normed = np.zeros(array.shape+(4,), dtype=np.uint8)
        # this line below was the bottleneck...
        # we have removed it by setting the _tex_data array to share the buffer
        # of the normalised data _array_normed
        # self._tex_data = (pyglet.gl.GLubyte * self._array_normed_data.size)( *self._array_normed_data )
        self._tex_data = (pyglet.gl.GLubyte * self._array_normed.size).from_buffer(self._array_normed)
        self._update_array()

        format_size = 4
        bytes_per_channel = 1
        self.pitch = array.shape[1] * format_size * bytes_per_channel
        self.image = pyglet.image.ImageData(array.shape[0], array.shape[1], "RGBA", self._tex_data)
        self._update_image()

    def set_array(self, data):
        self.array = data
        self.update()

    def _update_array(self):
        if self.rescale:
            self.norm.autoscale(self.array)
        self._array_normed[:] = self.cmap(self.norm(self.array), bytes=True)
        # don't need the below any more as _tex_data points to _array_normed memory
        # self._tex_data[:] = self._array_normed

    def _update_image(self):
        self.image.set_data("RGBA", self.pitch, self._tex_data)

    def update(self):
        self._update_array()
        self._update_image()

6

我花了一周的时间在用NumPy生成随机纹理上。看到了一篇帖子,尝试了里面的推荐答案。

我可以确认,之前被接受的答案是不正确的。

看起来这个答案是对的,因为你使用的是灰度图像。但如果你用的是彩色图像(比如RGBA格式),并把绿色、蓝色和透明度的通道都设为零,你就会发现问题,因为你的纹理中仍然会出现绿色和蓝色。

通过使用__str__(),你实际上是在发送一些无用的东西,而不是你真正想要的值。

我会用我的代码来演示这一点。

import numpy
import pyglet
from pyglet.gl import *

# the size of our texture
dimensions = (16, 16)

# we need RGBA textures
# which has 4 channels
format_size = 4
bytes_per_channel = 1

# populate our array with some random data
data = numpy.random.random_integers(
    low = 0,
    high = 1,
    size = (dimensions[ 0 ] * dimensions[ 1 ], format_size)
    )

# convert any 1's to 255
data *= 255
        
# set the GB channels (from RGBA) to 0
data[ :, 1:-1 ] = 0
        
# ensure alpha is always 255
data[ :, 3 ] = 255

# we need to flatten the array
data.shape = -1

按照上面的答案,你会这样做:

不要这样做!

tex_data = data.astype('uint8').__str__()

如果你试试这段代码,你会得到所有颜色,而不仅仅是红色!

改用这个!

正确的方法是转换为ctype GLubytes。

# convert to GLubytes
tex_data = (GLubyte * data.size)( *data.astype('uint8') )

然后你可以把这个传入你的纹理中。

# create an image
# pitch is 'texture width * number of channels per element * per channel size in bytes'
return pyglet.image.ImageData(
    dimensions[ 0 ],
    dimensions[ 1 ],
    "RGBA",
    tex_data,
    pitch = dimensions[ 1 ] * format_size * bytes_per_channel
    )
1

我觉得pyglet这个库是需要一个无符号8位整数(uint8),你试过吗?

IMG = ( random((X,Y)) * 255 ).astype('uint8')

撰写回答