[英]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.