Given that the blobs you're trying to split are very obvious cases where the median value of a blob should help to remove the zones that are non-zero but have very low values between the blobs, we can use a different approach. Specifically, we can use the median value of each blob to create a more robust mask and then apply a watershed algorithm to split the blobs.
Here's an updated version of your function that incorporates this approach:
import numpy as np
from skimage import measure, morphology, filters
from skimage.feature import peak_local_max
from scipy import ndimage as ndi
from skimage.segmentation import watershed
def amplify_signal(image, amplification):
return image * (1 + amplification / 10.0)
def threshold_otsu(image):
return filters.threshold_otsu(image)
def binary_opening(binary, selem):
return morphology.opening(binary, selem)
def strictly_non_overlapping_segmentation(image, max_amplification=30, step=2, min_area=10):
"""
Segment light spots in an image using the median value to split obvious blobs,
allowing spots to grow to maximum size with increasing amplification while
strictly preventing any overlap between different spots.
Parameters:
-----------
image : ndarray
Input grayscale image
max_amplification : int
Maximum amplification factor to apply
step : int
Step size for amplification increment
min_area : int
Minimum area for a region to be considered valid
Returns:
--------
final_mask : ndarray
Boolean mask with all segmented polygons
polygons : list
List of polygon coordinates for each detected region
amplification_levels : list
Corresponding amplification level for each polygon
"""
# Initialize tracking variables
final_regions = {} # Will store {region_id: {mask, contour, amp, centroid}}
next_id = 0 # For assigning unique IDs to regions
# Process each amplification level
for amp in range(0, max_amplification + 1, step):
# Amplify signal and get binary mask
image_amplified = amplify_signal(image, amp)
threshold = threshold_otsu(image_amplified)
binary = image_amplified > threshold
binary = binary_opening(binary, morphology.disk(1))
# Get connected regions
labeled_image, num_regions = measure.label(binary, return_num=True, connectivity=2)
if num_regions == 0:
continue
regions = measure.regionprops(labeled_image)
# First, identify and process all regions at this amplification level
current_regions = {} # Temporary storage for this amplification level
for region in regions:
if region.area < min_area:
continue
region_mask = labeled_image == region.label
centroid = region.centroid
# Extract contour
contours = measure.find_contours(region_mask, 0.5)
if not contours:
continue
contour = max(contours, key=len)
# Use the median value to create a more robust mask
median_value = np.median(image_amplified[region_mask])
robust_mask = image_amplified > median_value
robust_mask = robust_mask & region_mask
# Apply watershed to potentially split merged regions
distance = ndi.distance_transform_edt(robust_mask)
coords = peak_local_max(distance, footprint=np.ones((3, 3)), labels=robust_mask)
mask = np.zeros(distance.shape, dtype=bool)
mask[tuple(coords.T)] = True
markers, _ = ndi.label(mask)
ws_labels = watershed(-distance, markers, mask=robust_mask)
# Process each watershed-separated region
for ws_label in np.unique(ws_labels):
if ws_label == 0: # Skip background
continue
ws_mask = ws_labels == ws_label
ws_region = measure.regionprops(ws_mask.astype(int))[0]
centroid = ws_region.centroid
# Extract contour
contours = measure.find_contours(ws_mask, 0.5)
if not contours:
continue
contour = max(contours, key=len)
# Store in current regions dictionary with a unique label
current_label = f"{region.label}_{ws_label}"
current_regions[current_label] = {
'mask': ws_mask,
'contour': contour,
'centroid': centroid,
'area': ws_region.area,
'amp': amp
}
# Match current regions with existing ones based on centroid proximity
matched_pairs = [] # [(current_label, existing_id), ...]
for curr_label, curr_data in current_regions.items():
curr_centroid = curr_data['centroid']
# Find the closest existing region
best_match = None
min_distance = float('inf')
for existing_id, existing_data in final_regions.items():
exist_centroid = existing_data['centroid']
# Calculate distance between centroids
distance = np.sqrt(
(curr_centroid[0] - exist_centroid[0])**2 +
(curr_centroid[1] - exist_centroid[1])**2
)
# Check if this could be the same region (based on distance)
if distance < 20: # Adjust threshold as needed
# Check for meaningful overlap
overlap = np.logical_and(curr_data['mask'], existing_data['mask'])
union = np.logical_or(curr_data['mask'], existing_data['mask'])
overlap_ratio = np.sum(overlap) / np.sum(union)
if overlap_ratio > 0.2 and distance < min_distance:
best_match = existing_id
min_distance = distance
if best_match is not None:
matched_pairs.append((curr_label, best_match))
# CRITICAL SECTION: Update regions while strictly enforcing no overlap
# Create a working copy of the final mask that we'll update
working_mask = np.zeros_like(image, dtype=bool)
# First, add all existing regions to the working mask
for existing_id, data in final_regions.items():
working_mask = np.logical_or(working_mask, data['mask'])
# Process matched regions first (trying to grow existing regions)
for curr_label, existing_id in matched_pairs:
curr_data = current_regions[curr_label]
exist_data = final_regions[existing_id]
# Remove the existing region from the working mask
working_mask = np.logical_and(working_mask, ~exist_data['mask'])
# Check if the updated version would overlap with anything else
would_overlap = np.any(np.logical_and(curr_data['mask'], working_mask))
if not would_overlap:
# No overlap - update the region
final_regions[existing_id] = curr_data
# Add the updated region to working mask
working_mask = np.logical_or(working_mask, curr_data['mask'])
else:
# Would overlap - keep the old version
working_mask = np.logical_or(working_mask, exist_data['mask'])
# Now process unmatched regions (new regions)
matched_current_labels = [pair[0] for pair in matched_pairs]
for curr_label, curr_data in current_regions.items():
if curr_label in matched_current_labels:
continue # Skip already processed regions
# Check if this new region would overlap with anything
would_overlap = np.any(np.logical_and(curr_data['mask'], working_mask))
if not would_overlap:
# No overlap - add as a new region
region_id = next_id
next_id += 1
final_regions[region_id] = curr_data
# Add to working mask
working_mask = np.logical_or(working_mask, curr_data['mask'])
# Prepare final output
final_mask = np.zeros_like(image, dtype=bool)
polygons = []
amplification_levels = []
for region_id, data in final_regions.items():
final_mask = np.logical_or(final_mask, data['mask'])
polygons.append(data['contour'])
amplification_levels.append(data['amp'])
return final_mask, polygons, amplification_levels
Key Changes:
- Median Value Masking: For each region, the median value of the amplified image within the region is used to create a more robust mask. This helps in removing low-value zones between blobs.
- Watershed Segmentation: The watershed algorithm is applied to the robust mask to split merged blobs.
- Contour Extraction: Contours are extracted for each watershed-separated region.
This approach should help in splitting obvious cases where the median value of a blob can help in removing low-value zones between blobs. You may need to adjust parameters like the distance threshold for matching regions (currently 20 pixels) or the overlap ratio threshold (currently 0.2) based on your specific images.