[英]How can I find groups in an array?
我有一个二进制 3d 数组,它有小组1
和大组1
。 我想搜索数组,当找到1
时,我想在x,y,z
方向搜索周围的值并计算连接了多少个1
。 如果少于x
数量1
我想将该组设置为 0。整个 3d 数组由1
和0
。
数组示例:
img = np.array([[[0,0,0,1,0],
[0,0,0,1,1]],
[[0,0,0,1,0],
[0,0,0,0,0]]])
有一组1
在 x,y,z 方向上彼此直接相邻。 在我针对此场景的代码中,该组为num_group = 4
。 由于该组小于 10 我想将该组设为0
。
img = np.array([[[0,0,0,0,0],
[0,0,0,0,0]],
[[0,0,0,0,0],
[0,0,0,0,0]]])
我的阵列中有 1-2 个非常大且不同的组。 我只想在我的最终数组中包含那些大组。
import nibabel as nib
import numpy as np
import os, sys
x = 10
img = nib.load(\\test.nii).get_fdata()
print(img.shape)
>>>(512,512,30)
size_x, size_y, size_z = vol.shape
for z_slices in range(size_z):
for y_slices in range(size_y):
for x_slices in range(size_x):
num_group = (Find a 1 and count how many 1s are connected)
if num_group < x:
num_group = 0
您可以为此使用 skimage:
from skimage.measure import regionprops,label
sz = 10 #this is your set threshold
xyz = np.vstack([i.coords for i in regionprops(label(img)) if i.area<sz]) #finding regions and coordinates of regions smaller than threshold
img[tuple(xyz.T)]=0 #setting small regions to 0
输出:
[[[0 0 0 0 0]
[0 0 0 0 0]]
[[0 0 0 0 0]
[0 0 0 0 0]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.