gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:08:45 26 4
gpt4 key购买 nike

我想要做的是裁剪一个卷以删除所有不相关的数据。例如,假设我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com