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:
output: