How to merge local maxima based on distance apart
3 views (last 30 days)
Show older comments
I have detected a number of local maxima in an image (inplane resolution 0.5 x 0.5 mm).
I would like to merge local maxima that are less then a certian distance (say 5 mm) apart.
0 Comments
Answers (1)
Ayush
on 4 Jun 2024
Hi,
To merge local maxima that are less than a certain distance apart in an image, you can use the "pdist" function to compute pairwise distances between local maxima and then merge those within a specified distance threshold. Refer to the example below for a better understanding:
% Create a simple image with local maxima
imageSize = [100, 100]; % Image size in pixels
image = zeros(imageSize);
% Add local maxima
localMaxima = [20, 30; 25, 35; 60, 80; 65, 85]; % Example coordinates of local maxima
for i = 1:size(localMaxima, 1)
image(localMaxima(i,1), localMaxima(i,2)) = 255;
end
% Plot original image with local maxima
subplot(1,2,1);
imshow(image, []);
hold on;
plot(localMaxima(:,2), localMaxima(:,1), 'ro', 'MarkerSize', 10);
title('Before Merging');
% Convert coordinates to millimeters (assuming 0.5x0.5 mm resolution)
localMaxima_mm = localMaxima * 0.5;
% Compute pairwise distances
D = pdist(localMaxima_mm, 'euclidean');
D_matrix = squareform(D); % Convert to square form
% Threshold for merging (in mm)
threshold = 5;
% Find indices of points to merge
[row, col] = find(D_matrix > 0 & D_matrix < threshold);
% Merge points by averaging their positions
mergedMaxima_mm = localMaxima_mm;
for i = 1:length(row)
if row(i) < col(i) % Handle each pair once
mergedMaxima_mm(row(i), :) = mean([localMaxima_mm(row(i), :); localMaxima_mm(col(i), :)], 1);
mergedMaxima_mm(col(i), :) = [NaN, NaN]; % Mark for removal
end
end
% Remove points marked for removal
mergedMaxima_mm(any(isnan(mergedMaxima_mm), 2), :) = [];
% Convert merged points back to pixel coordinates for plotting
mergedMaxima_px = mergedMaxima_mm * 2;
% Plot image after merging local maxima
subplot(1,2,2);
imshow(image, []);
hold on;
plot(mergedMaxima_px(:,2), mergedMaxima_px(:,1), 'go', 'MarkerSize', 5);
title('After Merging');
% Display original and merged points
fprintf('Original Points (mm):\n');
disp(localMaxima_mm);
fprintf('Merged Points (mm):\n');
disp(mergedMaxima_mm);
The above example generates a plot before and after merging the local maxima. The red circles in the first subplot highlight the initial local maxima, while the green circles in the second subplot represent the new points after merging the local maxima. The merging takes place using the mean (average) of the positions of the two points.
For more information on the "pdist" function, refer to the below documentation:
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!