Python PIL Image.tostring ()

I am new to Python and PIL. I am trying to follow code samples on how to load an image in Python via PIL and then draw its pixels using openGL. Here are a few lines of code:

from Image import * im = open("gloves200.bmp") pBits = im.convert('RGBA').tostring() 

.....

 glDrawPixels(200, 200, GL_RGBA, GL_UNSIGNED_BYTE, pBits) 

This will draw a 200 x 200 pixel spot on the canvas. However, this is not a supposed image - it looks like it draws pixels from random memory. The random memory hypothesis is confirmed by the fact that I get the same pattern even when I try to make completely different images. Can anybody help me? I am using Python 2.7 and 2.7 version of pyopenGL and PIL for Windows XP.

screen shot

+4
source share
3 answers

I think you were close. Try:

 pBits = im.convert("RGBA").tostring("raw", "RGBA") 

First, the image must be converted to RGBA mode so that the RGBA rawmode package is available (see Pack.c in libimaging), you can check that len(pBits) == im.size[0]*im.size[1]*4 , which is 200x200x4 = 160,000 bytes for your gloves200 image.

+8
source

Have you tried using the conversion directly inside the tostring function?

 im = open("test.bmp") imdata = im.tostring("raw", "RGBA", 0, -1) w, h = im.size[0], im.size[1] glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, imdata) 

Use the compatibility version as an alternative:

  try: data = im.tostring("raw", "BGRA") except SystemError: # workaround for earlier versions r, g, b, a = im.split() im = Image.merge("RGBA", (b, g, r, a)) 
+1
source

Thanks for the help. Thanks to mikebabcock for updating sample code on the web. Thanks eryksun for the code snippet - I used it in my code.

I found my error, and it was a Python newb error. Uch. I declared some variables outside the scope of any function of the module and naively thought that I would change their values ​​inside the function. Of course, this does not work, and so my call to glDrawPixels actually causes random memory.

0
source

All Articles