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 0x10d4b5970>
../../_images/119c67a6e9d7fffee132c3e47f4c8a970eeecfbce542358933a1dd00bd18f3d4.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 0x10f3ae3c0>
../../_images/92dd923c201c78f4214d9908f7405f98cf2800dbb24c035a96cfb31518605e1b.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 0x10f58d0a0>
../../_images/23614fbee3b3536e578bb8344f80a8fbca978f5827f1a3c4f5f89eff872fbf16.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 0x10f2b7920>
../../_images/5c1204a4a9ad95ab029a63f7a6a97ab82492febffed0a902dadd921103a9ac8b.png

Crude integral approximations#

Mandelbrot set#

Markov chain#