Skip to content

Instantly share code, notes, and snippets.

@jawa0
Created November 2, 2012 17:39
Show Gist options
  • Save jawa0/4003034 to your computer and use it in GitHub Desktop.
Save jawa0/4003034 to your computer and use it in GitHub Desktop.
Use the Python Imaging Library (PIL), and NumPy to read an image into an OpenGL texture
from OpenGL.GL import *
import Image
import numpy
imname = 'uv-grey.jpg'
# glTexImage2D expects the first element of the image data to be the bottom-left corner of the image.
# Subsequent elements go left to right, with subsequent lines going from bottom to top.
#
# However, the image data was created with PIL Image tostring and numpy's fromstring, which means we
# have to do a bit of reorganization. The first element in the data output by tostring() will be the
# top-left corner of the image, with following values going left-to-right and lines going top-to-bottom.
# So, we need to flip the vertical coordinate (y).
im = Image.open(imname).transpose( Image.FLIP_TOP_BOTTOM );
imdata = numpy.fromstring(im.tostring(), numpy.uint8)
glEnable( GL_TEXTURE_2D )
texname = glGenTextures(1)
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glBindTexture(GL_TEXTURE_2D, texname)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 10.0)
#glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, im.size[0], im.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, imdata)
# According to the OpenGL docs, we're not supposed to do this anymore in OpenGL 3+, and use glGenerateMipmap instead. Oh well, still works.
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, im.size[0], im.size[1], GL_RGB, GL_UNSIGNED_BYTE, imdata)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment