Users sometimes ask how to display a photograph in VPython. This is
possible with the new beta version. The little program shown below,
available in the contributed section of vpython.org, does this by using
the Python Imaging Library (PIL) to read an image file (in this case,
jpeg, but PIL handles many image formats), optionally crop the image,
and resize the image to have width and height that are powers of 2. The
rgb pixel data are extracted into a Numeric array, and the y position
values flipped to put the location (0,0) at the bottom left of a VPython
texture. The texture is applied to a thin box and the image mounted on a
photo tray.
Bruce Sherwood
-----------------------------------------------------------------------------
from visual import *
import Image # from the Python Imaging Library (PIL);
www.pythonware.com/products/pil
im = Image.open("flower.jpg") # read a jpeg file named flower.jpg
#print im.size # to see the width and height of the image
# optionally crop image with rectangle (x1,y1,x2,y2), where (0,0) is
upper left corner:
#im = im.crop((0,20,300,320))
#im.show() # optionally display the cropped image
im = im.resize((256,256)) # resize so that length and width are powers of 2
# getdata() returns a special sequence, which must be made into a list
# before being made into an array:
data = array(list(im.getdata()),UnsignedInt8) # read pixel data into
flat Numeric array
data = reshape(data, (256,256,3)) # reshape for rgb texture
# texture (0,0) is lower left corner, so flip the y values:
im = data[::-1].copy() # copy() is necessary to make array contiguous in
memory
photo = texture(data=im, type="rgb")
box(size=(10,10,0.01), texture=photo, shininess=0)
box(pos=(0,-5.5,0), size=(12,1,2), color=color.cyan)
|