I have a problem where I am struggling to make a purely binary mask of the lungs, where the pixel value is one inside of the lung and is a 1 outside of the lungs. I used a kmeans and otsu and a few other methods to segment the lungs. I will attach a few example pictures.
Second example, same patient/CT. I have no idea why this one has a circle around it
Here is a link for a 3d numpy array. It is of all the slices, so you will want to just maybe try out one slice.
https://drive.google.com/file/d/1nktGBYZGz1iJDR_-yarzlRs-c4xOp__9/view?usp=sharing
As you can see, the lung is segmented well. (It is white in the middle of the pictures). Is there any way for me to identify that middle white blob (the lung) and make every pixel outside of it black (0?) I'd appreciate the help very much if someone could guide me.
Here is the code I used to segment the lung (making a binary mask):
def HUValueSegmentation(image, fill_lung_structures=True):
# not actually binary, but 1 and 2.
# 0 is treated as background, which we do not want
binary_image = np.array(image > -320, dtype=np.int8)+1
labels = measure.label(binary_image)
# Pick the pixel in the very corner to determine which label is air.
# Improvement: Pick multiple background labels from around the patient
# More resistant to "trays" on which the patient lays cutting the air
# around the person in half
background_label = labels[0,0,0]
#Fill the air around the person
binary_image[background_label == labels] = 2
# Method of filling the lung structures (that is superior to something like
# morphological closing)
if fill_lung_structures:
# For every slice we determine the largest solid structure
for i, axial_slice in enumerate(binary_image):
axial_slice = axial_slice - 1
labeling = measure.label(axial_slice)
l_max = largest_label_volume(labeling, bg=0)
if l_max is not None: #This slice contains some lung
binary_image[i][labeling != l_max] = 1
binary_image -= 1 #Make the image actual binary
binary_image = 1-binary_image # Invert it, lungs are now 1
# Remove other air pockets insided body
labels = measure.label(binary_image, background=0)
l_max = largest_label_volume(labels, bg=0)
if l_max is not None: # There are air pockets
binary_image[labels != l_max] = 0
return binary_image