简体   繁体   English

如何在2D numpy数组中居中非零值?

[英]How to center the nonzero values within 2D numpy array?

I'd like to locate all the nonzero values within a 2D numpy array and move them so that the image is centered. 我想在2D numpy数组中定位所有非零值,然后将它们移动以使图像居中。 I do not want to pad the array because I need to keep it the same shape. 我不想填充数组,因为我需要保持相同的形状。 For example: 例如:

my_array = np.array([[1, 1, 0, 0], [0, 0, 2, 4], [0, 0, 0, 0], [0, 0, 0, 0]])
# center...

>>> [[0 0 0 0]
     [0 1 1 0]
     [0 2 4 0]
     [0 0 0 0]]

But in reality the arrays I need to center are much larger (like 200x200, 403x403, etc, and they are all square). 但实际上,我需要居中的阵列要大得多(例如200x200、403x403等,它们都是正方形的)。 I think np.nonzero and np.roll might come in handy, but am not sure of the best way to use these for my large arrays. 我认为np.nonzeronp.roll可能会派上用场,但不确定将它们用于我的大型阵列的最佳方法。

The combination of nonzero and roll can be used for this purpose. nonzeroroll的组合可用于此目的。 For example, if k=0 in the loop shown below, then np.any will identify the rows that are not identically zero. 例如,如果在下面所示的循环中k=0 ,则np.any将标识不完全相同的零行。 The first and last such rows are noted, and the shift along the axis is computed so that after the shift, (first+last)/2 will move to the middle row of the array. 记录这样的第一行和最后一行,并计算沿轴的偏移,以便在偏移之后, (first+last)/2将移动到数组的中间行。 Then the same is done for columns. 然后对列执行相同的操作。

import numpy as np
my_array = np.array([[1, 1, 0, 0], [2, 4, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
print(my_array)   # before
for k in range(2):
    nonempty = np.nonzero(np.any(my_array, axis=1-k))[0]
    first, last = nonempty.min(), nonempty.max()
    shift = (my_array.shape[k] - first - last)//2
    my_array = np.roll(my_array, shift, axis=k)
print(my_array)   # after

Before: 之前:

[[1 1 0 0]
 [2 4 0 0]
 [0 0 0 0]
 [0 0 0 0]]

After: 后:

[[0 0 0 0]
 [0 1 1 0]
 [0 2 4 0]
 [0 0 0 0]]

Alternative: np.count_nonzeros can be used in place of np.any , which allows to potentially set some threshold for the number of nonzero pixels that are deemed "enough" to qualify a row as a part of the image. 替代: np.count_nonzeros可以代替使用np.any ,这允许潜在地设置该被视为“足够的”有资格的行作为图像的一部分非零像素数某个阈值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM