来自PyOpengl缓冲区的PIL Image.fromstring的大小错误

时间:2011-08-18 12:51:44

标签: python python-imaging-library glut pyopengl

我使用PyOpenGL绘制2D图像。然后我想使用Python Imaging Library(PIL)将此映像存储到磁盘。我使用GLUT来显示完美的图像。但是当我使用PIL存储图像时,它会提取错误的剪辑。它的大小不对。

这是一个重现效果的最小例子,我还附加了输出,使其更清晰,无需运行某些代码。

from OpenGL.GL import *
from OpenGL.GLUT import *
from PIL import Image

width, height = 640, 480

def DrawStuff():
    poly1 = [(0,0), (640,0), (0,480)]
    color = (0.5, 0.4, 0.3, 0.8)
    glClear(GL_COLOR_BUFFER_BIT)
    glPushMatrix()
    glLineWidth(5.0)

    glColor4f(*color)
    glBegin(GL_POLYGON)
    glVertex2f(poly1[0][0], poly1[0][1])
    glVertex2f(poly1[1][0], poly1[1][1])
    glVertex2f(poly1[2][0], poly1[2][1])    
    glVertex2f(poly1[0][0], poly1[0][1])
    glEnd() # GL_POLYGON

    glPopMatrix()
    glPixelStorei(GL_PACK_ALIGNMENT, 1)
    data = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE)
    image = Image.fromstring("RGBA", (width, height), data)
    image.show()
    image.save('out.png', 'PNG')
    glutSwapBuffers()


# glut initialization
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
glutCreateWindow("Draw Polygons")
glutInitWindowSize(width, height)

# set the function to draw
glutDisplayFunc(DrawStuff)

# enable the alpha blending
glEnable(GL_BLEND)
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

# prepare for 2D drawing
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, height, 0, 0, 1)
glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_MODELVIEW)

# start the mainloop
glutMainLoop ()

this is how it looks int the GLUT window and how it is supposed to look like 这就是它在GLUT窗口中的外观以及它应该如何看起来像

and this is how the saved image looks like 这就是保存的图像的样子

2 个答案:

答案 0 :(得分:1)

我设法解决了自己的问题。

首先,我尝试了以下解决方案,这可能也会帮助有相关问题的人: solution1

然而,通过广泛的试验和错误,我发现解决方案更简单。

我只需交换两行:

glutCreateWindow("Draw Polygons")
glutInitWindowSize(width, height)

glutInitWindowSize(width, height)
glutCreateWindow("Draw Polygons")

显然必须在窗口之前设置大小

答案 1 :(得分:0)

您应该考虑在OpenGL中,坐标系统的起点与PIL不同。请看this