官术网_书友最值得收藏!

Fancy indexing

Fancy indexing is indexing that does not involve integers or slices, which is conventional indexing. In this tutorial, we will practice fancy indexing to set the diagonal values of the Lena photo to 0. This will draw black lines along the diagonals, crossing through them.

The following is the code for this example:

import scipy.misc 
import matplotlib.pyplot as plt 
 
face = scipy.misc.face() 
xmax = face.shape[0] 
ymax = face.shape[1] 
face=face[:min(xmax,ymax),:min(xmax,ymax)] 
xmax = face.shape[0] 
ymax = face.shape[1] 
face[range(xmax), range(ymax)] = 0 
face[range(xmax-1,-1,-1), range(ymax)] = 0 
plt.imshow(face) 
plt.show() 

The following is a brief explanation of the preceding code:

  1. Set the values of the first diagonal to 0.

    To set the diagonal values to 0, we need to specify two different ranges for the x and y values (coordinates in a Cartesian coordinate system):

            face[range(xmax), range(ymax)] = 0 
    
  2. Set the values of the other diagonal to 0.

    To set the values of the other diagonal, we need a different set of ranges, but the rules remain the same:

              face[range(xmax-1,-1,-1), range(ymax)] = 0 
    

    At the final stage, we produce the following picture with the diagonals crossed out:

We specified different ranges for the x values and y values. These ranges were used to index the Lena array. Fancy indexing is done based on an internal NumPy iterator object. The following three steps are performed:

  1. The iterator object is created.
  2. The iterator object gets bound to the array.
  3. Array elements are accessed via the iterator.
主站蜘蛛池模板: 连江县| 永兴县| 马公市| 鹿邑县| 瑞丽市| 泸水县| 盐池县| 蓬莱市| 白水县| 满洲里市| 肇东市| 霍邱县| 淳化县| 新丰县| 门源| 无为县| 卢氏县| 高清| 竹山县| 电白县| 大渡口区| 邹平县| 洞头县| 临潭县| 亚东县| 喜德县| 荣成市| 祥云县| 酉阳| 无锡市| 同江市| 吐鲁番市| 延安市| 岳池县| 驻马店市| 南江县| 珠海市| 尚志市| 鹤山市| 永胜县| 新巴尔虎右旗|