Flipping Lena

We will be flipping the SciPy Lena image—all in the name of science, of course, or at least as a demo. In addition to flipping the image, we will slice it and apply a mask to it.

How to do it...

The steps to follow are listed below:

  1. Plot the flipped image.

    Flip the Lena array around the vertical axis using the following code:

    matplotlib.pyplot.imshow(lena[:,::-1])
  2. Plot a slice of the image.

    Take a slice out of the image and plot it. In this step, we will have a look at the shape of the Lena array. The shape is a tuple representing the dimensions of the array. The following code effectively selects the left-upper quadrant of the Playboy picture.

    matplotlib.pyplot.imshow(lena[:lena.shape[0]/2,:lena.shape[1]/2])
  3. Apply a mask to the image.

    Apply a mask to the image by finding all the values in the Lena array that are even (this is just arbitrary for demo purposes). Copy the array and change the even values to 0. This has the effect of putting lots of blue dots (dark spots if you are looking at a black and white image) on the image:

    mask = lena % 2 == 0
    masked_lena = lena.copy()
    masked_lena[mask] = 0

All these efforts result in a 2 by 2 image grid, as shown in the following screenshot:

How to do it...

The following is the complete code for this recipe:

import scipy.misc
import matplotlib.pyplot

# Load the Lena array
lena = scipy.misc.lena()

# Plot the Lena array
matplotlib.pyplot.subplot(221)
matplotlib.pyplot.imshow(lena)

#Plot the flipped array
matplotlib.pyplot.subplot(222)
matplotlib.pyplot.imshow(lena[:,::-1])

#Plot a slice array
matplotlib.pyplot.subplot(223)
matplotlib.pyplot.imshow(lena[:lena.shape[0]/2,:lena.shape[1]/2])
# Apply a mask
mask = lena % 2 == 0
masked_lena = lena.copy()
masked_lena[mask] = 0
matplotlib.pyplot.subplot(224)
matplotlib.pyplot.imshow(masked_lena)

matplotlib.pyplot.show()

See also

  • The Installing Matplotlib recipe in Chapter 1, Winding Along with IPython
  • The Installing SciPy recipe
  • The Installing PIL recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset