Skip to content
Advertisement

Remove white borders from segmented images

I am trying to segment lung CT images using Kmeans by using code below:

JavaScript

The problem is the segmented lung still contains white borderers like this:

Segmented lung (output):

segmented lung

Unsegmented lung (input):

unsegmented lung

The full code can be found in Google Colab Notebook. code.

And sample of the dataset is here.

Advertisement

Answer

For this problem, I don’t recommend using Kmeans color quantization since this technique is usually reserved for a situation where there are various colors and you want to segment them into dominant color blocks. Take a look at this previous answer for a typical use case. Since your CT scan images are grayscale, Kmeans would not perform very well. Here’s a potential solution using simple image processing with OpenCV:

  1. Obtain binary image. Load input image, convert to grayscale, Otsu’s threshold, and find contours.

  2. Create a blank mask to extract desired objects. We can use np.zeros() to create a empty mask with the same size as the input image.

  3. Filter contours using contour area and aspect ratio. We search for the lung objects by ensuring that contours are within a specified area threshold as well as aspect ratio. We use cv2.contourArea(), cv2.arcLength(), and cv2.approxPolyDP() for contour perimeter and contour shape approximation. If we have have found our lung object, we utilize cv2.drawContours() to fill in our mask with white to represent the objects that we want to extract.

  4. Bitwise-and mask with original image. Finally we convert the mask to grayscale and bitwise-and with cv2.bitwise_and() to obtain our result.


Here is our image processing pipeline visualized step-by-step:

Grayscale -> Otsu’s threshold

Detected objects to extract highlighted in green -> Filled mask

Bitwise-and to get our result -> Optional result with white background instead

Code

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement