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

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

lena = scipy.misc.lena()
xmax = lena.shape[0]
ymax = lena.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(lena[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 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(lena[np.ix_(xindices, yindices)])
  3. What we obtain is a totally scrambled Lena:
主站蜘蛛池模板: 新绛县| 城市| 凤山市| 林甸县| 平和县| 农安县| 奉新县| 张家港市| 浠水县| 陆河县| 建宁县| 莆田市| 隆德县| 大安市| 温宿县| 阿拉善盟| 黑水县| 额尔古纳市| 五大连池市| 乳山市| 冕宁县| 青川县| 保山市| 绥江县| 平顶山市| 乳山市| 肇州县| 游戏| 阿坝县| 洮南市| 错那县| 诸暨市| 广汉市| 平潭县| 巴塘县| 扬州市| 合川市| 五峰| 扬中市| 仁布县| 阿克|