2011-08-18 57 views
4

我使用PyOpenGL绘制2D图像。然后,我想使用Python成像库(PIL)将此映像存储到磁盘。我使用GLUT来显示完美的图像。但是当我使用PIL来存储图像时,它会提取错误的裁剪。它有错误的大小。来自PyOpengl缓冲区的PIL Image.fromstring具有错误的大小

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

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 这是它的外观INT过剩窗口,它是如何应该看起来像

and this is how the saved image looks like ,这是保存图像看起来像

回答

1

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

首先我尝试以下解决方案,它也可能帮助人们与相关的问题: solution1

但后来,经过广泛的试验和错误,我发现,解决的办法是要简单得多。

我只是不得不从交换两行:

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

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

显然有大小的窗口之前设置

0

你应该考虑在OpenGL的坐标系在不同于PIL的地方开始。看看this

+0

感谢酸的帮助。但他不是问题。我找到了解决方案,但无法将其作为答案发布,因为我没有足够的声誉。我将编辑该问题。 – dedan

+1

这是一个光辉的例子,为什么答案不应该依赖链接来解释。注意死链接。这是一个耻辱,因为这个问题(和潜在的答案)仍然相关。 – ephsmith