Loading images with Python

We will import mahotas using the mh abbreviation, which we will use throughout the whole tutorial.

In [ ]:
import mahotas as mh

Similarly, numpy is imported as np and matplotlib.pyplot as plt:

In [ ]:
import numpy as np
from matplotlib import pyplot as plt

Commands starting with the percentage sign (%) are special internal commands to ipython (as opposed to Python code to be run). In this case, we set the matplotlib environment to display images results inline (i.e., the images will be shown inside the notebook):

In [ ]:
%matplotlib inline

If you like working like this, you can also set this option globally in your configuration file.

We will also set the colormap to be greyscale (see below):

In [ ]:
plt.gray()

Now, we load the image into memory with mahotas.imread

In [ ]:
im = mh.imread('jordan.jpeg')

im is a numpy array with format Height x Width x Channels (where channels is red/green/blue):

In [ ]:
print type(im)
print im.dtype
print im.shape

plt.imshow(im)

Images are just numpy arrays

This means that we can use numpy functionality to manipulate the image. For example, we compute the mean across axis=2 (the third, channel, axis) to compute a grey-scale version:

In [ ]:
im = im.mean(axis=2)
plt.imshow(im)

Note that there are other methods to convert to greyscale. Often the green channel is more heavily weighted as humans are more sensitive to variations of intensity in that wavelength.

Playing with colourmaps

Above we set the colourmap to gray, but there are other options.

You can read matplotlib's colormap documentation for a full list of the ones supported. Besides the purely aesthetical aspect, different colormaps make sense in different contexts.

In [ ]:
plt.pink()
plt.imshow(im)

Other operations such as thresholding can also be performed using only numpy operations:

In [ ]:
thresholded = (im > 100)
plt.imshow(thresholded)

Because many other packages also use the numpy format, you can use functionality from other packages such as scikit-image or OpenCV, SimpleCV very easily, mixing and matching functions from different packages in the same analysis.

A few more things you should know about

  • imsave: opposite of imread, saves images to files