In this tutorial, we will apply fancy indexing to set the diagonal values of the Lena image to 0
. This will draw black lines along the diagonals, crossing it through, not because there is something wrong with the image, but just as an exercise.
Fancy indexing is indexing that does not involve integers or slices, which is normal indexing.
We will start with the first diagonal:
0
.To set the diagonal values to 0
, we need to define two different ranges for the x and y values:
lena[range(xmax), range(ymax)] = 0
0
.To set the values of the other diagonal, we require a different set of ranges, but the principles stay the same:
lena[range(xmax-1,-1,-1), range(ymax)] = 0
At the end, we get this image with the diagonals crossed off, as shown in the following screenshot:
The following is the complete code for this recipe:
import scipy.misc import matplotlib.pyplot # This script demonstrates fancy indexing by setting values # on the diagonals to 0. # Load the Lena array lena = scipy.misc.lena() xmax = lena.shape[0] ymax = lena.shape[1] # Fancy indexing # Set values on diagonal to 0 # x 0-xmax # y 0-ymax lena[range(xmax), range(ymax)] = 0 # Set values on other diagonal to 0 # x xmax-0 # y 0-ymax lena[range(xmax-1,-1,-1), range(ymax)] = 0 # Plot Lena with diagonal lines set to 0 matplotlib.pyplot.imshow(lena) matplotlib.pyplot.show()
We defined separate ranges for the x values and y values. These ranges were used to index the Lena array. Fancy indexing is performed based on an internal NumPy iterator object. The following three steps are performed: