2017-03-01 20 views
2

我有一個圖像表示爲一個數組(img),並且我想製作很多圖像的副本,並且在每個副本中將圖像的不同方格置零(在第一個副本0:2,0:2在下一個複製零出0:2,3:5等)。我使用np.broadcast_to來創建圖像的多個副本,但我無法通過圖像的多個副本進行索引,並且圖像中的多個位置用於將圖像中的方塊歸零。通過塊中的數組進行索引

我想我正在尋找類似skimage.util.view_as_blocks的東西,但我需要能夠寫入原始數組,而不僅僅是讀取。

背後的想法是通過神經網絡傳遞圖像的所有副本。表現最差的副本應該是我試圖在其零點位置識別的類(圖片)。

img = np.arange(10*10).reshape(10,10) 
img_copies = np.broadcast_to(img, [100, 10, 10]) 
z = np.zeros(2*2).reshape(2,2) 

感謝

+0

如何被那些'不同squares'用'不同locations'送入代碼?所有這些方塊都是相同的形狀嗎? – Divakar

+0

編輯原文更加具體。不同的方塊將從左上角開始,並以非重疊的方式覆蓋整個陣列。每個廣場的大小相同。謝謝 – Aryeh

回答

0

我想我已經破解了!下面是使用masking沿6D重整的陣列的方法 -

def block_masked_arrays(img, BSZ): 
    # Store shape params 
    m = img.shape[0]//BSZ 
    n = m**2 

    # Make copies of input array such that we replicate array along first axis. 
    # Reshape such that the block sizes are exposed by going higher dimensional. 
    img3D = np.tile(img,(n,1,1)).reshape(m,m,m,BSZ,m,BSZ)  

    # Create a square matrix with all ones except on diagonals. 
    # Reshape and broadcast it to match the "blocky" reshaped input array. 
    mask = np.eye(n,dtype=bool).reshape(m,m,m,1,m,1) 

    # Use the mask to mask out the appropriate blocks. Reshape back to 3D. 
    img3D[np.broadcast_to(mask, img3D.shape)] = 0 
    img3D.shape = (n,m*BSZ,-1) 
    return img3D 

採樣運行 -

In [339]: img 
Out[339]: 
array([[ 0, 1, 2, 3], 
     [ 4, 5, 6, 7], 
     [ 8, 9, 10, 11], 
     [12, 13, 14, 15]]) 

In [340]: block_masked_arrays(img, BSZ=2) 
Out[340]: 
array([[[ 0, 0, 2, 3], 
     [ 0, 0, 6, 7], 
     [ 8, 9, 10, 11], 
     [12, 13, 14, 15]], 

     [[ 0, 1, 0, 0], 
     [ 4, 5, 0, 0], 
     [ 8, 9, 10, 11], 
     [12, 13, 14, 15]], 

     [[ 0, 1, 2, 3], 
     [ 4, 5, 6, 7], 
     [ 0, 0, 10, 11], 
     [ 0, 0, 14, 15]], 

     [[ 0, 1, 2, 3], 
     [ 4, 5, 6, 7], 
     [ 8, 9, 0, 0], 
     [12, 13, 0, 0]]]) 
+0

這很有效,雖然我很難遵循你的代碼,特別是在維度更高的情況下。你的功能如何工作?謝謝 – Aryeh

+0

@Aryeh在那裏添加了幾條評論。 – Divakar

+0

您的功能起作用,所以我將其標記爲已回答。謝謝。我仍然不明白你如何使用附加維度,是否有你使用的方法的名稱,或者你推薦的某個網站,以便我可以詳細瞭解你所做的事情?謝謝 – Aryeh