Download PDF, 1 page per side - Scipy lecture notes

Transcript
Scipy lecture notes, Edition 2015.2
• 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 object at 0x...>
• Create an array of the image with a narrower centering [for example,] 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]
• 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 object at 0x...>
• 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.
3.5.3 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])
<matplotlib.axes...Axes object at ...>
>>> plt.plot(year, hares, year, lynxes, year, carrots)
[<matplotlib.lines.Line2D object at ...>, ...]
>>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5))
<matplotlib.legend.Legend object at ...>
3.5. Some exercises
78