在这两个处理查找二进制图像中对象之间的距离的帖子之后,我怎样才能只输出/计算特定对象与其余对象之间的最短距离(例如,{1->3}、{2->5 }、{3->1}、{4->7)?
脚本:
clc;
clear all;
I = rgb2gray(imread('E:/NCircles.png'));
imshow(I);
BW = imbinarize(I,'adaptive');
BW = imfill(BW, 'holes');
BW = bwlabel(BW);
s = regionprops(BW,'Area', 'BoundingBox', 'Eccentricity', 'MajorAxisLength', 'MinorAxisLength', 'Orientation', 'Perimeter','Centroid');
imshow(BW)
hold on
for k = 1:numel(s)
c = s(k).Centroid;
text(c(1), c(2), sprintf('%d', k), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
boundaries = bwboundaries(BW);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), 'r', 'LineWidth', 3);
end
hold off;
% Define object boundaries
numberOfBoundaries = size(boundaries, 1)
for b1 = 1 : numberOfBoundaries
for b2 = 1 : numberOfBoundaries
if b1 == b2
% Can't find distance between the region and itself
continue;
end
boundary1 = boundaries{b1};
boundary2 = boundaries{b2};
boundary1x = boundary1(:, 2);
boundary1y = boundary1(:, 1);
x1=1;
y1=1;
x2=1;
y2=1;
overallMinDistance = inf; % Initialize.
% For every point in boundary 2, find the distance to every point in boundary 1.
for k = 1 : size(boundary2, 1)
% Pick the next point on boundary 2.
boundary2x = boundary2(k, 2);
boundary2y = boundary2(k, 1);
% For this point, compute distances from it to all points in boundary 1.
allDistances = sqrt((boundary1x - boundary2x).^2 + (boundary1y - boundary2y).^2);
% Find closest point, min distance.
[minDistance(k), indexOfMin] = min(allDistances);
if minDistance(k) < overallMinDistance
x1 = boundary1x(indexOfMin);
y1 = boundary1y(indexOfMin);
x2 = boundary2x;
y2 = boundary2y;
overallMinDistance = minDistance(k);
end
end
% Find the overall min distance
minDistance = min(minDistance);
% Report to command window.
fprintf('The minimum distance from region %d to region %d is %.3f pixels\n', b1, b2, minDistance);
% Draw a line between point 1 and 2
line([x1, x2], [y1, y2], 'Color', 'y', 'LineWidth', 3);
end
end