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

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:

主站蜘蛛池模板: 临西县| 武冈市| 禹城市| 视频| 乐东| 峨眉山市| 瑞金市| 神木县| 尤溪县| 三台县| 葵青区| 永定县| 凯里市| 庆安县| 泰安市| 丹阳市| 辽中县| 班戈县| 文昌市| 阳信县| 兴城市| 定南县| 莱阳市| 普兰店市| 慈利县| 汉阴县| 广灵县| 广德县| 鹤山市| 万盛区| 耒阳市| 海伦市| 凤台县| 杭锦旗| 永州市| 曲阜市| 新野县| 无棣县| 西城区| 固原市| 涞源县|