Some exercises#

import numpy as np
import matplotlib.pyplot as plt

Array manipulations#

Picture manipulation: Framing a Face#

Let’s do some manipulations on NumPy arrays by starting with an image of a raccoon. scipy provides a 2D array of this image with the scipy.datasets.face function:

import scipy as sp
face = sp.datasets.face(gray=True)  # 2D grayscale image

Here are a few images we will be able to obtain with our manipulations: use different colormaps, crop the image, change some parts of the image.

Let’s use the imshow function of matplotlib to display the image.

import matplotlib.pyplot as plt
face = sp.datasets.face(gray=True)
plt.imshow(face)
<matplotlib.image.AxesImage at 0x7f20d14e3ce0>
../../_images/9e59b1a8210c3a8be45d57e56e72a7ac145573a5cc3434f952d14431a61029cf.png

The face is displayed in false colors. A colormap must be specified for it to be displayed in grey.

plt.imshow(face, cmap=plt.cm.gray)
<matplotlib.image.AxesImage at 0x7f20d0edad50>
../../_images/846edd5042e5b2a3795805ab6bd0d03ff698825834e6be306ce3df1af05b40bf.png

Narrow centering#

Create an array of the image with a narrower centering; remove 100 pixels from all the borders of the image. To check the result, display this new array with imshow.

crop_face = face[100:-100, 100:-100]

Frame face#

We will now frame the face with a black locket. For this, we need to create a mask corresponding to the pixels we want to be black. The center of the face is around (660, 330), so we defined the mask by this condition `(y-300)**2

  • (x-660)**2`

sy, sx = face.shape
y, x = np.ogrid[0:sy, 0:sx] # x and y indices of pixels
y.shape, x.shape
((768, 1), (1, 1024))
centerx, centery = (660, 300) # center of the image
mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle

then we assign the value 0 to the pixels of the image corresponding to the mask. The syntax is extremely simple and intuitive:

face[mask] = 0
plt.imshow(face)
<matplotlib.image.AxesImage at 0x7f20ccd30380>
../../_images/6a190c1be98980339b1a7096ee532902d27dcab1488d6c5cdfb28a9865b4c694.png

Follow-up:

  • copy all instructions of this exercise in a script called : face_locket.py then execute this script in IPython with %run face_locket.py.

  • Change the circle to an ellipsoid.

Data statistics#

The data in populations.txt describes the populations of hares and lynxes (and carrots) in northern Canada during 20 years:

data = np.loadtxt('data/populations.txt')
year, hares, lynxes, carrots = data.T  # trick: columns to variables
import matplotlib.pyplot as plt

plt.axes([0.2, 0.1, 0.5, 0.8])
plt.plot(year, hares, year, lynxes, year, carrots)
plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5))
<matplotlib.legend.Legend at 0x7f20d0f40a10>
../../_images/81ac15f71c951915ab811ed2195e2078b5a68f76dd04c8731021f1cdef3e787d.png

Crude integral approximations#

Mandelbrot set#

Markov chain#