Database Reference
In-Depth Information
Using SciPy with Image Data
What is the resolution of your laptop? The ubiquity of laptops, smartphones, and tab-
lets have pushed screen-resolution specs into the public consciousness, and conversa-
tions about the width and height in pixels of the latest device are not uncommon.
The images produced on your flat screen monitors are really just collections of pix-
els arranged in a rectangle. Therefore the properties of these pixels (such as the hue,
brightness, etc.) can be naturally expressed in a multidimensional array indexed by the
location of the pixel. Because SciPy uses NumPy's underlying multidimensional array
data type, it's both fun and easy to convert your image data into a format that can be
manipulated using methods in the SciPy ndimage package.
The example in Listing 12.3 illustrates how to use Python's urllib and PIL classes to
download an image from the Web, pull the raw representation of the information into
a NumPy array, and then apply a Gaussian blur using the SciPy ndimage package.
Listing 12.3 SciPy for image data
from scipy import ndimage, misc
from urllib import urlopen
from PIL import Image
from StringIO import StringIO
# Retrieve the Python logo from the Web
url = 'http://www.python.org/community/logos/python-powered-w-200x80.png'
python_logo = Image.open(StringIO(urlopen(url).read()))
# Convert image to a NumPy array
image_array = misc.fromimage(python_logo)
# Apply a Gaussian blur to the image
blurred = ndimage.gaussian_filter(image_array, sigma=4)
# Save the image to local disk
misc.imsave('blurred_image.png', blurred)
The blurred image result is saved as a new local file. It's also possible to use SciPy's
image methods on a succession of video stills. There are a lot of possibilities for digital
image processing and analysis, and many transformations can be done in just a few
lines of code. Using SciPy to manipulate images programmatically is a great way to
learn about how digital effects are implemented.
The Pandas Data Analysis Library
NumPy and SciPy are powerful tools in their own right, and can form the basis of
some of the same types of data analysis that one can do with R. However, these tools
still leave a gap in the type of applications that can be built, as practical use cases bring
 
 
Search WWH ::




Custom Search