Search code examples
pythonarraysnumpypyglet

numpy array is shown incorrect with pyglet


I have problems with displaying a numpy array with pyglet. I have found a very similar topic (how to display a numpy array with pyglet?) that I used. I want to display the array in greyscale, but pyglet displays it with colours see the image: https://i.sstatic.net/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

If I save and load the array instead it works (but it is horrobly slower):

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

And I get what I wanted:

https://i.sstatic.net/FCY1v.jpg

I can't find the mistake in the first code example :(

EDIT:

Many thanks for your answers. With the hint from Bago I got this to code to work :) And indeed nfirvine suggestion is reasonable, since I only want to display the matrix in greyscale.

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

Solution

  • I think pyglet is expecting uint8, have you tried?

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