Python PIL Image.tostring()
我是 Python 和 PIL 新手。我正在尝试遵循代码示例,了解如何通过 PIL 将图像加载到 Python,然后使用 openGL 绘制其像素。以下是一些代码行:
from Image import *
im = open("gloves200.bmp")
pBits = im.convert('RGBA').tostring()
.....
glDrawPixels(200, 200, GL_RGBA, GL_UNSIGNED_BYTE, pBits)
这将在画布上绘制 200 x 200 的像素块。然而,它不是预期的图像——它看起来像是从随机存储器中绘制像素。即使我尝试绘制完全不同的图像,我也会得到相同的图案,这一事实支持了随机记忆假设。有人可以帮助我吗?我在 Windows XP 上使用 Python 2.7 以及 2.7 版本的 pyopenGL 和 PIL。
I'm new to Python and PIL. I am trying to follow code samples on how to load an image into to Python through PIL and then draw its pixels using openGL. Here are some line of the 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 patch of pixels on the canvas. However, it is not the intended image-- it looks like it is drawing pixels from random memory. The random memory hypothesis is supported by the fact that I get the same pattern even when I attempt to draw entirely different images.Can someone help me? I'm using Python 2.7 and the 2.7 version of pyopenGL and PIL on Windows XP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想你很接近。尝试:
首先必须将图像转换为 RGBA 模式,以便 RGBA rawmode 打包程序可用(请参阅 Pack.c 在 libimaging 中)。您可以检查
len(pBits) == im.size[0]*im.size[1]*4
,对于您的 glove200 图像,它是 200x200x4 = 160,000 字节。I think you were close. Try:
The image first has to be converted to RGBA mode in order for the RGBA rawmode packer to be 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.您是否尝试过直接使用 tostring 函数内部的转换?
或者使用兼容版本:
Have you tried using the conversion inside the tostring function directly?
Alternatively use compatibility version:
谢谢你的帮助。感谢 mikebabcock 更新了 Web 上的示例代码。感谢 eryksun 提供的代码片段——我在我的代码中使用了它。
我确实发现了我的错误,这是Python新手的错误。哎哟。我在模块中任何函数的范围之外声明了一些变量,并天真地认为我正在函数内修改它们的值。当然,这是行不通的,所以我的 glDrawPixels 调用实际上是在绘制随机内存。
Thank you for the help. Thanks to mikebabcock for updating the sample code on the Web. Thanks to eryksun for the code snippet-- I used it in my code.
I did find my error and it was Python newb mistake. Ouch. I declared some variables outside the scope of any function in the module and naively thought I was modifying their values inside a function. Of course, that doesn't work and so my glDrawPixels call was in fact drawing random memory.