insides_o = np.zeros_like(original_image)
thresholded_eroded = cv2.erode(thresholded, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(12,12)))
for i in range(thresholded.shape[2]):
body_mask = (thresholded_eroded[:,:,i] == 255).astype(np.uint8)
dum = np.where(body_mask == 1, original_image[:,:,i], 0)
dum = np.where(dum > -2000 , dum, 0)
dum = np.where(dum < -200 , dum, 0)
thresholds = threshold_multiotsu(dum, classes=3)
regions = np.digitize(dum, bins=thresholds)
insides_o[:,:,i] = regions
insides_o2 = np.zeros_like(original_image)
for i in range(thresholded.shape[2]):
dum = np.where(insides_o[:,:,i] == 0, original_image[:,:,i], 2)
dum = cv2.morphologyEx(dum, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)))
dum = cv2.morphologyEx(dum, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)))
if i <=35:
dum = initial_bowel_air_heuristic_clean(dum)
code
dum_bin = dum < np.max(dum)
filled_mask = binary_fill_holes(dum_bin)
dum = cv2.morphologyEx(filled_mask.astype(np.float32), cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)))
insides_o2[:,:,i] = dum
insides_o3 = np.zeros_like(original_image)
for i in range(thresholded.shape[2]):
dum = insides_o2[:,:,i].copy()
# perform segmentation
For sequence of images perform segmentation. There should be 3 segments (left, right lung and trachea) When differentiating lungs you might do something like this:
centroid_1_x = centroids[largest_labels[0], 0]
centroid_2_x = centroids[largest_labels[1], 0]
Just make sure that left lung has assigned value of 2 and right 3
Assistant
To perform segmentation of a sequence of images into three segments—left lung, right lung, and trachea—while ensuring that the left lung is assigned a value of 2 and the right lung a value of 3, you can extend your existing code by incorporating connected component analysis and centroid-based labeling. Below is a comprehensive approach to achieve this:
Connected Component Labeling: Identify distinct regions in each image slice.
Centroid Calculation: Compute the centroids of these regions to determine their positions.
Left and Right Lung Assignment: Based on the x-coordinates of the centroids, assign labels to the left and right lungs.
Trachea Identification: Optionally, identify the trachea based on its central position or other distinguishing features.
Here's how you can implement this:
python
import numpy as np
import cv2
from skimage.filters import threshold_multiotsu
from skimage.measure import label, regionprops
from scipy.ndimage import binary_fill_holes
# Assuming original_image and thresholded are already defined as per your existing code
insides_o = np.zeros_like(original_image)
thresholded_eroded = cv2.erode(thresholded, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (12, 12)))
for i in range(thresholded.shape[2]):
body_mask = (thresholded_eroded[:, :, i] == 255).astype(np.uint8)
dum = np.where(body_mask == 1, original_image[:, :, i], 0)
dum = np.where(dum > -2000, dum, 0)
dum = np.where(dum < -200, dum, 0)
# Apply multi-Otsu thresholding
thresholds = threshold_multiotsu(dum, classes=3)
regions = np.digitize(dum, bins=thresholds)
insides_o[:, :, i] = regions
insides_o2 = np.zeros_like(original_image)
for i in range(thresholded.shape[2]):
dum = np.where(insides_o[:, :, i] == 0, original_image[:, :, i], 2)
dum = cv2.morphologyEx(dum, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
dum = cv2.morphologyEx(dum, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
if i <= 35:
dum = initial_bowel_air_heuristic_clean(dum) # Ensure this function is defined elsewhere
dum_bin = dum < np.max(dum)
filled_mask = binary_fill_holes(dum_bin)
dum = cv2.morphologyEx(filled_mask.astype(np.float32), cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
insides_o2[:, :, i] = dum
insides_o3 = np.zeros_like(original_image)
for i in range(thresholded.shape[2]):
dum = insides_o2[:, :, i].copy()
# Perform Connected Component Labeling
labeled_img = label(dum, connectivity=2)
regions = regionprops(labeled_img)
if len(regions) < 2:
# Handle cases with less than two regions (e.g., assign all to one lung)
# You may choose to skip or assign default labels
insides_o3[:, :, i] = labeled_img
continue
# Assume the two largest regions correspond to the lungs
regions = sorted(regions, key=lambda x: x.area, reverse=True)
largest_labels = [region.label for region in regions[:2]]
centroids = [region.centroid for region in regions[:2]] # (row, col)
# Extract x-coordinates (columns) of the centroids
centroid_1_x = centroids[0][1]
centroid_2_x = centroids[1][1]
# Determine left and right lungs based on x-coordinate
if centroid_1_x < centroid_2_x:
left_lung_label = largest_labels[0]
right_lung_label = largest_labels[1]
else:
left_lung_label = largest_labels[1]
right_lung_label = largest_labels[0]
# Create a segmentation map for the current slice
lung_segment = np.zeros_like(labeled_img, dtype=np.uint8)
lung_segment[labeled_img == left_lung_label] = 2 # Left lung
lung_segment[labeled_img == right_lung_label] = 3 # Right lung
# (Optional) Identify and assign the trachea
# This step requires additional logic based on expected trachea location or characteristics
# For example, you might look for a smaller region centrally located above the lungs
# Here's a simplistic approach assuming the trachea is the third largest region
if len(regions) >= 3:
trachea_label = regions[2].label
lung_segment[labeled_img == trachea_label] = 1 # Trachea assigned label 1
insides_o3[:, :, i] = lung_segment
# insides_o3 now contains segmented labels:
# 0: Background
# 1: Trachea
# 2: Left Lung
# 3: Right Lung
Explanation of the Code:
Preprocessing:
Erosion: The thresholded image is eroded to remove noise using an elliptical structuring element.
Thresholding: Applied multi-Otsu thresholding to segment the image into regions.
Morphological Operations:
Opening and Closing: These operations help in removing small objects and closing small holes within the segmented regions.
Hole Filling: Ensures that the segmented regions are solid without internal holes.
Connected Component Labeling and Region Properties:
Labeling: Each connected region in the binary image is labeled uniquely.
Region Properties: For each labeled region, properties like area and centroid are computed using regionprops.
Centroid-Based Label Assignment:
Sorting: Regions are sorted based on their area to assume that the two largest regions correspond to the lungs.
Left vs. Right Lung Determination: By comparing the x-coordinates (column indices) of the centroids, the code determines which lung is on the left and which is on the right.
Label Assignment:
Left Lung: Assigned a value of 2.
Right Lung: Assigned a value of 3.
Trachea (Optional): If a third region exists, it's assigned a value of 1.
Handling Edge Cases:
If fewer than two regions are detected, the code assigns the available regions to the lungs or handles them as needed.
You might want to enhance the trachea identification logic based on specific anatomical features or incorporate more sophisticated criteria.
Additional Considerations:
Trachea Identification:
The trachea is centrally located and typically smaller than the lungs. You can enhance its detection by:
Checking the vertical position relative to the lungs.
Ensuring it's centrally located between the left and right lungs.
Verifying its size to differentiate it from other structures.
Validation:
It's essential to validate the segmentation results visually or by using ground truth data to ensure accuracy.
Fine-tune the morphological operations and thresholding parameters based on the specific characteristics of your image dataset.
Performance Optimization:
For large datasets or higher-dimensional images, consider optimizing the code for performance, possibly by leveraging parallel processing or using optimized libraries.
Example Visualization (Optional)
To visualize the segmentation results for a particular slice, you can use matplotlib:
This visualization can help in verifying whether the segmentation is performing as expected.
By following the above approach, you should be able to segment the lungs and trachea effectively across your sequence of images, ensuring consistent labeling for the left and right lungs.