简体   繁体   中英

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 . 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. 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 .

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. In my code for this scenario the group is num_group = 4 . Since that group is smaller than 10 I want to make that group 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. 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:

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]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM