I have CT scan image and I want to extract (segment) only lungs part from that using python or MATLAB.
-
which part are the lungs? the white part or the stuff in the white part? – Ian Chu Feb 14 '21 at 05:08
-
@lan Chu, inside part of the white surroundings is lungs. I have PNG images. – codewarrior Feb 14 '21 at 08:25
-
@Abhi25t can you please share your MATLAB code, I will try it weather it worked for me or not. – codewarrior Feb 14 '21 at 08:26
-
Hey, did the hill climbing segmentation work for you ? – Abhi25t Feb 14 '21 at 15:55
-
1If the current answer is what you want, then you should accept the answer. Otherwise, you should explain why it doesn't answer your issue so that we can make another attempt to help. – Ian Chu Feb 16 '21 at 00:35
2 Answers
The solution which worked for me in MATLAB is Hill Climbing algorithm. Here is it's MATLAB implementation. It uses an unsupervised machine learning algorithm: k-means. You will need to experiment with different number of segments depending on your requirement. See example below:
Download the above code (files HillClimbingSegment.m
and RGB2Lab.m
) from MATLAB Central and place it in your workspace. Then you can segment like this:
image_path = 'CT.jpg';
segmented_img = HillClimbingSegment(image_path,4);
where the second argument in the second line (4
) is the number of desired segments.
In my image, using just 4 segments, the abnormality in right lung is observable, but the other organ at top of right lung is merged with lung. Using 7 segments, seperates it out. Using 7-9 segments give the best view. Above 9 leads to clutter.

- 3,703
- 3
- 19
- 32
I recommend you convert the png into NIfTI file (nii) and then working with python. For the conversion, you can use it: Convert .png files to .nii (NiFti files)
After that, you can load the image use
nii = nibabel.load(path to the nifti file)
get the numpy array
np_array = nii.get_fdata()
Segment all the body from the nifti file by filter threshold between -500 to 2000. All the air inside and outside the body will be 1- body segmentation.
Then take the largest connected component and remove it from the segmentation (which is the outside air that is larger than the lungs)
air_seg = skimage.measure.label(air_seg)
largest_connected_air = air_seg == numpy.argmax(nump.bincount(air_seg.flat)[1:]) + 1
do it again to take the lungs now. This what I got:
Please reply if you need more explanation.

- 76
- 1
- 1
- 6