Calculate the distance between two objects automatically using matlab.

hi there!
i am currently doing project on image processing in matlab, in which I'm assigned to calculate the Euclidean distance between two object automatically.here is the image link https://imageshack.com/i/pcUJ9tQgj i first converted the image to binary using 'im2bw', then i applied 'canny' edge detection method and obtained the edges, and by using 'find' function i got the corresponding pixel values. And i am not able to processed further, problem is i have to get array of pixel coordinates for object A and object B separately. and the code has to find which pixel coordinates is nearer between both objects and calculate the nearer distance. I'd very much appreciate your input.
Sincrely, lakshya

 Accepted Answer

You forgot to attach your image, which people usually do when they want image processing advice. So I don't know if edge detection is what you want to do or not. Perhaps it is if you have something like phase contrast or DIC microscopy images, but if you have objects of one intensity on a background of a different intensity then you can probably use thresholding. That method is explained in my Image Segmentation Tutorial http://www.mathworks.com/matlabcentral/fileexchange/?term=authorid%3A31862 I find the blobs' centroids. From that you can find the distances between the centroids.
You didn't really explain your definition of distance clearly. I think you mean Euclidean /Pythagorean distance, but there's a chance you mean the Hausdorf distance. See this page to understand the Hausdorf distance: http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/98/normand/main.html, though chances are you've never heard of it.
In my File Exchange there are also color segmentation methods. How you do your task really depends on what your images look like.

24 Comments

@image analyst, thank you for the quick reply,as said i have made appropriate changes in my question.
sincrely, lakshya
Like I thought, you can simply convert to grayscale and use thresholding. Just follow my Image Segmentation Tutuorial. It's really really easy. Just replace the demo image filename with yours.
@ image analyst
as you said i tried but i am not able to find distance between those two objects in image, plz tell me which function or what code should i use to get the nearest coordinates of object A and Object B, once i find the nearest coordinates between the two object ,i can calculate the distance by using distance formula. plz help
While searching i got this code, which i have attached.i am able to get the distance with only those images present in the folder, with my image i am not able to get any distance, Whats the reason?
Define distance. The distance between the centroids? The distance between the two points that are closest to each other (one point on each object)? The Hausdorf distance?
like in this image need to find distance between points a and b.
The ipdm function is great for finding distances between lots of points.
I'd just get your binary image, then call bwboundaries(). Then calculate the distance between each coordinate of one boundary with every other coordinate of the other boundary in a nested for loop. Should be very fast. Something like this (untested):
% Define object boundaries
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
boundary1 = boundaries{1};
boundary2 = boundaries{2};
boundary1x = boundary1(:, 2);
boundary1y = boundary1(:, 1);
for k = 1 : length(boundary2x)
boundary2x = boundary2(k, 2);
boundary2y = boundary2(k, 1);
% For this blob, compute distances from boundaries to edge.
allDistances = sqrt((boundary1x - boundary2x).^2 + (boundary1y - boundary2y).^2);
% Find closest point, min distance.
[minDistance(k), indexOfMin] = min(allDistances);
end
% Find the overall min distance
minDistance = min(minDistance);
% Report to command window.
minDistance
Exercise for you to complete (not hard). Save the indexes (which will give the x,y coordinates) of the overall min distance. This means you save the k and indexOfMin at the minimum distance. You can do it. I have confidence in you!
@ image analyst
Actually i am not getting x,y coordinates after edge detection.And newly i am learning image processing in matlab.
this is my code
I=imread('pic.jpg'); b=im2bw(I); a=edge(b,'canny'); figure,imshow(a); [X,Y] = find(a==0)
Is the code correct?? On executing i am getting indices , but i wanted coordinates . which function should i use??
@image analyst
i tried your code, but i am getting error.
Undefined function or variable 'boundary2x'.
and getting error in this line
for k = 1 : length(boundary2x)
Like I said, untested so you may have to do debugging. I'll do it this time. I think it should say length(boundary2)
@ chad Greene
sir i am not knowing how to use 'ipdm' in my program. plz provide me the syntax .and this is my code.
I=imread('pic.jpg');
b=im2bw(I);
a=edge(b,'canny');
figure,imshow(a);
[X,Y] = find(a==0)
Lakshya, okay, I did it all for you. I could see you, for some reason, were convinced that edge detection was necessary and that would only complicate the algorithm. I don't know who suggest that to you but they need to take a second look at this image or take a refresher course in image analysis.
See the attached code below the image. It will product this image.
Thank you Image Analyst for the code. However, I have a similar problem but the image is rotated and the method seems to be not working well. Maybe some modification is needed.
Any idea how to make it working correctly?
Post the original image and I might be able to look at it later today - possibly . I'm traveling all day today and tomorrow.
I'm also traveling until coming Thursday. Will send you as soon I come back home. Thank you very much.
I tried here to use the same image but just rotate it 90 degrees to the right.
The result I go is
Is there a way to get the straight shortest line that connect the two objects?
We needed to adjust the threshold because at 10, the boundary was not closed so the object could not be filled. Also we forgot to update the overallMinDistance when we found a new one. New code is attached as test3.m below the image.
That's good. Thank you very much.
What is the unit of this code?
the unit of min. distance?
And is there a reference of this method?
No of course not. It's too basic and simple for anyone to have written a paper just on that.

Sign in to comment.

More Answers (6)

Lakshya
Lakshya on 31 Aug 2014
Edited: Lakshya on 31 Aug 2014
Thank you so very much IMAGE ANALYST , this code is really helpful ,thank you once again .
You told about refresher course ,is there any online refresher on IMAGE PROCESSING?? if so plz attach the link.
As i am doing project on real time image processing, i was told to find the Euclidean distance between two objects, and then find the distance in terms of units ( meters , centimeters etc...)so my guide gave me a hint that i can do it using edge detection, so i did using canny edge detection method .
suppose if this is my image , using this code I am getting min distance as 18.248 , how to convert it to units??

5 Comments

I think you misunderstood your guide. You do need to find the edges because of the measurement you need to make, but that does not mean that you do edge detection like Canny, Sobel, etc. It means that you first need to find the objects (and thresholding will do a great job here), and then find the boundary with bwboundaries. That is just what I did in my answer.
An excellent book, and in-person course, is by John Russ http://www.drjohnruss.com/
Steve Eddins of the image processing team at the Mathworks has also written a book. Go here to amazon.com to see it.
Coursera has some online university level classes: https://www.coursera.org/courses?search=image%20processing
MIT also has some online courses Click here for the MIT courses
You can find several others via Google.
thank you image analyst for your patience to sort out my problem it means a lot. and in this image, i am getting minimum distance as 18.248 .Wat is this value actually ?? and how to convert it to get units ???plz help
For images that are flat and perpendicular to the optic axis, you can adapt my spatial calibration demo, attached.
For scenes at some arbitrary oddball angle, you'll need the Computer Vision System Toolbox http://www.mathworks.com/products/computer-vision/features.html#camera-calibration because the spatial calibration factor at different locations in the scene will be different.
Thank you so much image analyst.... it would be greatful if you could help me solve out this...
i am getting distance between pixels like 20 , 14.025... how can i get it in real time ... like in cms or meters etc...
can we solve this using matlab or we need to do it using some other software...??? plz suggest...
I can't really add more than what I said in my prior comment.

Sign in to comment.

You Can calculate the Distance of multiple Objects of Center point by using this code:
k=2; for i=1:1:length(g)-1 x(i) = g(i).Centroid(1); y(i) = g(i).Centroid(2);
x(k)=g(k).Centroid(1); y(k)=g(k).Centroid(2);
distance=sqrt((x(i)-x(k))^2+(y(i)-y(k))^2);
@Image Analyst I have been following the code you attached above 'test3' for finding the distance between two objects. I am unable to find the distance between the objects, instead I am able to find the distance between the boudary of the image to one of the objects. I am attaching the input as well as the output image that I am getting after applying your code, please help me find the minimum distance between these two bones. Output Image
Input Image

5 Comments

@Vihan P, can you start your own question and attach your imagte and code? (Since this is not an answer to @Lakshya).
@Image Analyst I have started my own question and tagged you in it as well!
Vihan, it looks like Matt J answered your question and you accepted it.
Hello @Image Analyst Yes, he did help me find a solution. Although, I would love to understand how things can be changed in the code that you have provided.
@Vihan P, see code adapted for your image. I also did it both ways, using sqrt(), where I just plotted one of the closest pairs, and pdist2() where I plotted all 3 of the closest pairs.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fprintf('Beginning to run %s.m ...\n', mfilename);
fontSize = 13;
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
%===============================================================================
% Read in a standard MATLAB color demo image.
folder = pwd; %'C:\Users\Lakshya\Documents\Temporary';
baseFileName = 'knee.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 3.
[rows, columns, numberOfColorBands] = size(grayImage);
% Display the original image.
subplot(2, 2, 1);
imshow(grayImage);
axis on;
title('Original Gray Scale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Binarize the image
binaryImage = imbinarize(grayImage);
% Display the image.
subplot(2, 2, 2);
imshow(binaryImage);
title('Binary Image', 'FontSize', fontSize);
% Fill the outline to make it solid so we don't get boundaries
% on both the inside of the shape and the outside of the shape.
binaryImage = imfill(binaryImage, 'holes');
% Display the image.
subplot(2, 2, 3);
imshow(binaryImage);
% bwboundaries() returns a cell array, where each cell contains the row/column coordinates for an object in the image.
% Plot the borders of all the coins on the original grayscale image using the coordinates returned by bwboundaries.
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), 'r', 'LineWidth', 3);
end
title('Filled Binary Image with Boundaries', 'FontSize', fontSize);
hold off;
% Define object boundaries
numberOfBoundaries = size(boundaries, 1)
boundary1 = boundaries{1};
boundary2 = boundaries{2};
boundary1x = boundary1(:, 2);
boundary1y = boundary1(:, 1);
x1=1;
y1=1;
x2=1;
y2=1;
overallMinDistance = inf; % Initialize.
index1 = 1;
index2 = 1;
for k = 1 : length(boundary2)
boundary2x = boundary2(k, 2);
boundary2y = boundary2(k, 1);
% For this blob, compute distances from boundaries to edge.
allDistances = sqrt((boundary1x - boundary2x).^2 + (boundary1y - boundary2y).^2);
% Find closest point, min distance.
[minDistance(k), indexOfMin] = min(allDistances);
if minDistance(k) < overallMinDistance
overallMinDistance = minDistance(k);
x1 = boundary1x(indexOfMin);
y1 = boundary1y(indexOfMin);
x2 = boundary2x;
y2 = boundary2y;
index2 = k;
index1 = indexOfMin;
end
end
% Report to command window.
fprintf('Min Distance from sqrt() method = %f at index %d of boundary 1 and index %d of boundary 2.\n', ...
overallMinDistance, index1, index2);
hFig = figure;
h1 = subplot(1, 2, 1);
imshow(binaryImage);
axis on;
title('Closest Distance from sqrt()', 'FontSize', fontSize);
h2 = subplot(1, 2, 2);
imshow(binaryImage);
axis on;
title('Closest Distances from pdist2()', 'FontSize', fontSize);
hFig.WindowState = 'maximized';
hold on;
% Draw a line between point 1 and 2
line(h1, [x1, x2], [y1, y2], 'Color', 'y', 'LineWidth', 3);
%======================================================================================
% For comparison, use pdist2()
allDistances2 = pdist2(boundary1, boundary2);
minDistance2 = min(allDistances2(:));
% Find all points that have that min distance - there may be several that have it.
[r, c] = find(allDistances2 == minDistance2)
boundary1x = boundary1(:, 2);
boundary1y = boundary1(:, 1);
boundary2x = boundary2(:, 2);
boundary2y = boundary2(:, 1);
for k = 1 : length(r)
% Report to command window.
index1 = r(k);
index2 = c(k);
fprintf('Min Distance from pdist2() method = %f at index %d of boundary 1 and index %d of boundary 2.\n', ...
minDistance2, index1, index2);
xLine = [boundary1x(index1), boundary2x(index2)];
yLine = [boundary1y(index1), boundary2y(index2)];
line(h2, xLine, yLine, 'Color', 'm', 'LineWidth', 1.5);
end
You can't see the magenta lines in the right image very well, but they're there.

Sign in to comment.

Following this code. Can you tell me how to detect the bubble border(black region) and the tube wall(this black line near the bubble). And then calculate the distance between the border of the bubble and the closest wall pixel near this bubble?
Also if I know that the inside diameter is 15 mm. Can I have this distances in mm?
Appreciate

1 Comment

@Rhandrey Maestri, start a new question with this since it's sufficiently different. In there, show us how you processed the horizontal profile
horizontalProfile = mean(grayImage);
plot(horizontalProfile, 'b-');
to find the two valleys, and how you used thresholding to get the bubble, then how you use find() to find the edges, row-by-row, of the inner walls and the outer bubble walls. If you still need help, I'll help you there.
There is a variety of ways to do this, and it could be easier if you knew that the walls and bubbles were in approximately the same location every time, like just mask off the middle part and deal with only the central part, then threshold and take the 3 largest blobs with bwareafilt.

Sign in to comment.

@Image Analyst Can you help me how I can find distance which I have marked with red line

1 Comment

Use imdistline to find the distance in pixels. Use the camera calibration functionality in the Computer Vision Toolbox if you need real world distances.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!