To effectively fill the internal pockets within your lung segmentation without merging adjacent lungs, you can use hole-filling techniques. These methods are designed to fill in the background-like regions (holes) inside your segmented lungs while preserving the distinctness of each lung. Here's a step-by-step approach to achieve this:
1. Use binary_fill_holes from scipy.ndimage
The binary_fill_holes function is a straightforward way to fill holes in binary images. It works by identifying background regions that are completely enclosed by foreground (your lung regions) and filling them.
Implementation:
import numpy as np
import cv2
from scipy.ndimage import binary_fill_holes
from skimage.filters import threshold_multiotsu
# Assuming original_image and thresholded are already defined as in your code
insides_filled = np.zeros_like(original_image, dtype=np.uint8)
for i in range(thresholded.shape[2]):
# Apply erosion
body_mask = (cv2.erode(thresholded[:, :, i], cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (12, 12))) == 255).astype(np.uint8)
# Mask the original image
dum = np.where(body_mask == 1, original_image[:, :, i], 0)
dum = np.where((dum > -2000) & (dum < -200), dum, 0)
# Multi-Otsu thresholding
thresholds = threshold_multiotsu(dum, classes=3)
regions = np.digitize(dum, bins=thresholds)
insides_o = regions
# Create a binary mask for the lungs
lung_mask = insides_o > 0 # Adjust the condition based on your specific thresholding
# Fill holes within the lung mask
filled_mask = binary_fill_holes(lung_mask)
# Convert to uint8
insides_filled[:, :, i] = filled_mask.astype(np.uint8) * 255
# Now, insides_filled contains the lungs with filled internal pockets
2. Alternative: Use OpenCV’s Flood Fill
If you prefer using OpenCV, you can implement a flood-fill approach to fill the holes. This method involves:
- Flood filling the background from the borders.
- Inverting the flood-filled image to get the holes.
- Combining the original mask with the inverted flood-filled image to fill the holes.
Implementation:
import numpy as np
import cv2
from skimage.filters import threshold_multiotsu
insides_filled_cv2 = np.zeros_like(original_image, dtype=np.uint8)
for i in range(thresholded.shape[2]):
# Apply erosion
body_mask = (cv2.erode(thresholded[:, :, i], cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (12, 12))) == 255).astype(np.uint8)
# Mask the original image
dum = np.where(body_mask == 1, original_image[:, :, i], 0)
dum = np.where((dum > -2000) & (dum < -200), dum, 0)
# Multi-Otsu thresholding
thresholds = threshold_multiotsu(dum, classes=3)
regions = np.digitize(dum, bins=thresholds)
insides_o = regions
# Create a binary mask for the lungs
lung_mask = (insides_o > 0).astype(np.uint8) * 255
# Flood fill from the border
flood_mask = np.zeros((lung_mask.shape[0] + 2, lung_mask.shape[1] + 2), np.uint8)
cv2.floodFill(lung_mask.copy(), flood_mask, (0, 0), 255)
# Invert flood filled image
flood_inv = cv2.bitwise_not(lung_mask)
# Combine with original mask to get the holes
filled_mask = lung_mask | flood_inv
filled_mask = cv2.bitwise_not(filled_mask)
filled_mask = lung_mask | filled_mask
insides_filled_cv2[:, :, i] = filled_mask
# Now, insides_filled_cv2 contains the lungs with filled internal pockets
3. Considerations for 3D Consistency
If your data represents a 3D volume (e.g., a CT scan), it's beneficial to ensure consistency across slices. You can leverage 3D hole-filling techniques or perform connected component analysis in 3D to maintain continuity between adjacent slices. Libraries such as scipy.ndimage and scikit-image offer functions that can handle 3D data effectively.
Example with 3D binary_fill_holes:
from scipy.ndimage import binary_fill_holes
# Create a 3D mask
lung_mask_3d = insides_filled > 0
# Fill holes in 3D
filled_mask_3d = binary_fill_holes(lung_mask_3d)
# Convert back to uint8
insides_filled_3d = filled_mask_3d.astype(np.uint8) * 255
4. Final Integration and Cleanup
After filling the holes, you might want to perform additional cleanup to remove any unwanted artifacts or small regions that do not correspond to the lungs. This can be done using connected component analysis to keep only the largest connected components (assuming they represent the lungs):
import scipy.ndimage as ndi
for i in range(insides_filled.shape[2]):
# Label connected components
labeled, num_features = ndi.label(insides_filled[:, :, i])
# Find the largest connected component
sizes = ndi.sum_labels(labeled, labeled, range(1, num_features + 1))
if sizes.size > 0:
largest_cc = (labeled == (np.argmax(sizes) + 1))
insides_filled[:, :, i] = largest_cc.astype(np.uint8) * 255
5. Visual Verification
Always visualize a few slices before and after the hole-filling process to ensure that the lungs are correctly segmented without merging adjacent structures.
import matplotlib.pyplot as plt
slice_idx = 50 # Example slice index
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title('Original Segmentation')
plt.imshow(insides_o[:, :, slice_idx], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('After Hole Filling')
plt.imshow(insides_filled[:, :, slice_idx], cmap='gray')
plt.show()
Summary
By incorporating hole-filling techniques, either through binary_fill_holes or OpenCV's flood-fill, you can effectively eliminate internal background-like pockets within your lung segmentation masks. Additionally, ensuring 3D consistency and performing connected component analysis can further enhance the accuracy of your segmentation, maintaining the integrity of each lung without merging them unintentionally.
Feel free to adjust the parameters and conditions based on the specific characteristics of your dataset to achieve optimal results.