[英]How can I find groups in an array?
I have a binary 3d array that has small groups of 1
and large groups of 1
.我有一个二进制 3d 数组,它有小组
1
和大组1
。 I want to search the array and when a 1
is found I want to search the surrounding values in the x,y,z
directions and count how many 1
are connected.我想搜索数组,当找到
1
时,我想在x,y,z
方向搜索周围的值并计算连接了多少个1
。 If there are less than x
amount of 1
I want to set that group to 0. The entire 3d array consists of 1
and 0
.如果少于
x
数量1
我想将该组设置为 0。整个 3d 数组由1
和0
。
Array Example:数组示例:
img = np.array([[[0,0,0,1,0],
[0,0,0,1,1]],
[[0,0,0,1,0],
[0,0,0,0,0]]])
There is a group of 1
directly next to each other in the x,y,z directions.有一组
1
在 x,y,z 方向上彼此直接相邻。 In my code for this scenario the group is num_group = 4
.在我针对此场景的代码中,该组为
num_group = 4
。 Since that group is smaller than 10 I want to make that group 0
.由于该组小于 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]]])
There are 1-2 very large and distinct groups in my arrays.我的阵列中有 1-2 个非常大且不同的组。 I want to only have those large groups in my final array.
我只想在我的最终数组中包含那些大组。
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
You can use skimage for this:您可以为此使用 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
output:输出:
[[[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.