python - 从卷中裁剪空数组(填充)

标签 python numpy

我想要做的是裁剪一个卷以删除所有不相关的数据。例如,假设我有一个 100x100x100 的体积,其中填充了 0,但其中的 50x50x50 体积则填充了 1。 如何从原始体积中获得裁剪后的 50x50x50 体积?

这是我想出的简单方法。

import numpy as np
import tensorflow as tf

test=np.zeros((100,100,100)) # create an empty 100x100x100 volume
rand=np.random.rand(66,25,34) # create a 66x25x34 filled volume
test[10:76, 20:45, 30:64] = rand # partially fill the empty volume

# initialize the cropping coordinates
minx=miny=minz=0
maxx=maxy=maxz=0
maxx,maxy,maxz=np.subtract(test.shape,1)

# compute the optimal cropping coordinates
dimensions=test.shape
while(tf.reduce_max(test[minx,:,:]) == 0): # check for empty slices along the x axis
    minx+=1
while(tf.reduce_max(test[:,miny,:]) == 0): # check for empty slices along the y axis
    miny+=1
while(tf.reduce_max(test[:,:,minz]) == 0): # check for empty slices along the z axis
    minz+=1
while(tf.reduce_max(test[maxx,:,:]) == 0):
    maxx-=1
while(tf.reduce_max(test[:,maxy,:]) == 0):
    maxy-=1
while(tf.reduce_max(test[:,:,maxz]) == 0):
    maxz-=1

maxx,maxy,maxz=np.add((maxx,maxy,maxz),1)
crop = test[minx:maxx,miny:maxy,minz:maxz]

print(minx,miny,minz,maxx,maxy,maxz)
print(rand.shape)
print(crop.shape)

打印:

10 20 30 76 45 64
(66, 25, 34)
(66, 25, 34)

,这是正确的。然而,它花费的时间太长,而且可能不是最理想的。我正在寻找更好的方法来实现同样的目标。

注意:

  • 子体积不一定是长方体,它可以是任何形状。

  • 我想在子体积内保留间隙,仅删除要裁剪的形状“外部”的内容。

最佳答案

(编辑) 哎呀,我没看到the comment关于保持元素之间所谓的“间隙”!最后应该就是这个了

def get_nonzero_sub(arr):
    arr_slices = tuple(np.s_[curr_arr.min():curr_arr.max() + 1] for curr_arr in arr.nonzero())
    return arr[arr_slices]

关于python - 从卷中裁剪空数组(填充),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326612/

相关文章:

python - '类型错误 : Scalar value for argument 'color' is not numeric' when using opencv-python drawing a circle

python - 对于大型数组的手动元素操作,numpy 的更快替代方案?

python - 具有意外结果的正弦波的傅里叶变换

python-3.x - Numpy 计算随机 2D 或 1D 数组中的 Min Max

python - python 是否在连续的内存位置存储相似的对象?

python - pandas groupby 中的行联合

python - 为什么以下简单的并行化代码比 Python 中的简单循环慢得多?

python - 替换 numpy 数组中的元素

python - 无法安装scrapy

python - 检查当前行中的所有列值是否小于 Pandas 数据框中的前一行