2016-09-08 3 views
0

N次元配列から与えられたサイズの一部と与えられた位置を切り取る必要があります。 部品が大きい場合は、指定されたサイズになるようにゼロを埋め込む必要があります。アレイからpiceを切り取り、0で埋めてください

例は簡潔にするために2Dで示しています。

所与マトリックス:私は[2,4]の部分をカットする

[[1 8 3 3 8] 
[5 8 6 7 6] 
[8 3 5 6 5] 
[2 6 2 4 6] 
[6 5 3 7 4]] 

は、インデックス(1,2)から出発して、Iカット 部分のサイズのために十分な大きさではないので、パディングゼロを含む が必要です。 指名手配結果:

[[6 7 6 0] 
[5 6 5 0]] 

が、私はそれを行うには醜いではなくN-DIMコードを書くために管理します。

# set example numbers 
matrix = numpy.random.randint(low=1, high=9, size=(5,5)) 
matrix_size = np.array(matrix.shape) 

# size of the part we want to have in the end 
size = np.array([2, 4]) 
# starting point of the cut 
mini = [1, 2] 

#calculating max index (in the given matrix) for the part we want to cut 
maxi = np.add(size - 1 , mini) 
cut_max_ind = np.minimum(maxi, matrix_size - 1) + 1 

# copy from matrix to cut 
# ??? a way to generalize it for N-dim ??? 
cut = matrix[mini[0]:cut_max_ind[0], mini[1]:cut_max_ind[1]] 

#culculate the padding size 
padding = np.add(matrix_size - 1, maxi*-1) 
padding_size = np.minimum(np.zeros((matrix.ndim), dtype=np.uint8), padding) * -1 

for j in range(0, matrix.ndim): 

    if (padding_size[j]): 
     pad_width = size 
     pad_width[j] = padding_size[j] 
     pad_pice = np.zeros((pad_width), dtype = np.uint8) 
     cut = np.append(cut, pad_pice, axis = j) 

print "matrix" 
print matrix 
print "cut" 
print cut 

改善と一般化のアイデアはありますか?

答えて

0

あなたがゼロの配列を事前割り当てして、あなたのニーズに合わせてスライスを変更することによって、簡単にそれを解決することができます:あなたはスライスに慣れていない場合

a = numpy.array([ 
    [1, 8, 3, 3, 8], 
    [5, 8, 6, 7, 6], 
    [8, 3, 5, 6, 5], 
    [2, 6, 2, 4, 6], 
    [6, 5, 3, 7, 4], 
]) 

def extract_piece(array, in_idx): 
    # make sure number of dimensions match 
    assert array.ndim == len(in_idx) 
    # preallocate output array 
    out = numpy.zeros([i.stop - i.start for i in in_idx], dtype=array.dtype) 

    # modify reading slices to not exceed bounds 
    in_idx = [slice(i.start, min(i.stop, s), i.step) for s, i in zip(array.shape, in_idx)] 
    # modify writing slices to fit size of read data 
    out_idx = [slice(0, i.stop - i.start) for i in in_idx] 

    # Copy data 
    out[out_idx] = array[in_idx] 
    return out 

print a 
print extract_piece(a, (slice(1, 3), slice(2, 6))) 

や4Dの例では

extract_piece(
    numpy.random.rand(4, 4, 4, 4), # 4D data 
    (
     slice(0,2), # 1st dimension 
     slice(0,4), # 2nd dimension 
     slice(0,6), # 3rd dimension 
     slice(0,1), # 4th dimension 
    ) 
) 

を:

a[1:2] 

と同じです
+0

すごい素晴らしい答えです。完璧に動作します。ありがとう – Naomi

+0

は3Dに対しても完全に機能します。小さなエラー:out [out_idx] =配列[in_idx](not a) – Naomi

+0

任意の数のディメンションで動作します。 :-)ありがとう、それを修正しました。 –

関連する問題