Hi,
I've written a functions; save_opengl(). It will draw an image and
save it to file, without opening any windows. It's useful when you
want to script something or maybe do some regression testing. I've
attached the code below.
Is there a better way to do this? Is this guaranteed to work across
platforms?
Any feedback is appreciated.
/ Oscar
#!/usr/bin/env python
# Saving an image from pyglet without displaying any window
# based on pyglet version of NeHe's OpenGL lesson03 (Philip Bober
pdb...@gmail.com)
# based on the pygame+PyOpenGL conversion by Paul Furber 2001 -
m...@verick.co.za
from
pyglet.gl import *
from pyglet import window
def save_opengl(draw_function, width, height, filename):
win = window.Window(width, height, visible=False)
draw_function(width, height)
pyglet.image.get_buffer_manager().get_color_buffer().save
(filename)
win.close()
def opengl_array(draw_function, width, height, format='RGB'):
import numpy
win = window.Window(width, height, visible=False)
draw_function(width, height)
cb = pyglet.image.get_buffer_manager().get_color_buffer()
id = cb.get_image_data()
a = numpy.fromstring(id.get_data(format, -width*len(format)),
'uint8')
win.close()
return a.reshape(height, width, -1)
def draw(width, height):
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45/2, 1.0*width/height, 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glClearColor(0.4, 0.5, 0.9, 1.0)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
glTranslatef(0.0, 0.0, -6.0)
glBegin(GL_TRIANGLES)
glColor3f(1.0, 0.0, 0.0)
glVertex3f(0.0, 1.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVertex3f(-1.0, -1.0, 0)
glColor3f(0.0, 0.0, 1.0)
glVertex3f(1.0, -1.0, 0)
glEnd()
def main():
save_opengl(draw, 640, 480, 'screenshot.png')
#print opengl_array(draw, 20, 10, format='I') # Intensity
if __name__ == '__main__':
main()