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

Indexing with a list of locations

Let's apply the ix_() function to shuffle the Lena photo. The following is the code for this example without comments. The finished code for the recipe can be found in ix.py in this book's code bundle:

import scipy.misc 
import matplotlib.pyplot as plt 
import numpy as np 
 
face = scipy.misc.face() 
xmax = face.shape[0] 
ymax = face.shape[1] 
 
def shuffle_indices(size): 
   arr = np.arange(size) 
   np.random.shuffle(arr) 
 
   return arr 
 
xindices = shuffle_indices(xmax) 
np.testing.assert_equal(len(xindices), xmax) 
yindices = shuffle_indices(ymax) 
np.testing.assert_equal(len(yindices), ymax) 
plt.imshow(face[np.ix_(xindices, yindices)]) 
plt.show() 

This function produces a mesh from multiple sequences. We hand in parameters as one-dimensional sequences and the function gives back a tuple of NumPy arrays, for instance, as follows:

In : ix_([0,1], [2,3]) 
Out: 
(array([[0],[1]]), array([[2, 3]])) 

To index the NumPy array with a list of locations, execute the following steps:

  1. Shuffle the array indices.

    Make an array with random index numbers with the shuffle() function of the numpy.random subpackage. The function modifies the array in place:

              def shuffle_indices(size): 
                 arr = np.arange(size) 
                 np.random.shuffle(arr) 
     
              return arr 
    
  2. Plot the shuffled indices, as shown in the following code:
            plt.imshow(face[np.ix_(xindices, yindices)]) 
    

What we obtain is a totally scrambled Lena:

主站蜘蛛池模板: 紫阳县| 曲阳县| 张家川| 三门峡市| 伊宁县| 依安县| 蚌埠市| 辛集市| 调兵山市| 阜新市| 墨竹工卡县| 永胜县| 巴彦县| 饶河县| 秦安县| 广州市| 三河市| 汶上县| 刚察县| 黄山市| 石河子市| 永修县| 黄石市| 莱西市| 阿克苏市| 阜南县| 沙田区| 三都| 陇川县| 青神县| 新河县| 天等县| 内黄县| 泌阳县| 刚察县| 阳江市| 南充市| 子洲县| 修文县| 会泽县| 郯城县|