Numpy分裂阵列以质心为中心

时间:2018-02-08 21:03:50

标签: python arrays numpy split

我想将尺寸为(101,151,101)的3D数组拆分为大小相同的子阵列(21,21,21)。 (尺寸不固定,但为了方便,奇数)。唯一的要求是,分裂应该从中间完成。因此,原始矩阵的中点应位于子阵列的中间,以便块在原始矩阵上均匀分布。

非常感谢你。

1 个答案:

答案 0 :(得分:0)

我创建了一个代码,可以为2D矩阵做到这一点,可以很容易地适应3D矩阵。我想这可以修改使它更有效率。

image_size = (15, 19)
mid_point = (7, 9)
block_size = (3, 3)

## Identification of the starting point of mid points. 
d0_point = mid_point[0]
while (d0_point - (block_size[0]-1)/2) > -1:
    d0_point = d0_point - block_size[0]
d0_point = d0_point + block_size[0]

d1_point = mid_point[1]
while (d1_point - (block_size[1]-1)/2) > -1:
    d1_point = d1_point - block_size[1]
d1_point = d1_point + block_size[1]

i_points = (d0_point, d1_point)

## Calculating number of blocks in the matrix
block_array = numpy.zeros(image_size, dtype=int)
n0 = int((image_size[0] - (d0_point - (block_size[0]-1)/2)*2)/block_size[0] )
n1 = int((image_size[1] - (d1_point - (block_size[1]-1)/2)*2)/block_size[1] )

block_count = (n0, n1)

## List of mid-points of blocks
eye_list = []
for ni in range(n0):
    for nj in range(n1):
        eye_list.append((ni*block_size[0]+d0_point, nj*block_size[1]+d1_point))

## Marking blocks.             
block_number = 1
for eye in eye_list:
    block_array[int(eye[0]-(block_size[0]-1)/2):int(eye[0]-(block_size[0]-1)/2)+block_size[0], 
            int(eye[1]-(block_size[1]-1)/2):int(eye[1]-(block_size[1]-1)/2)+block_size[1]] = block_number
    block_number += 1