MATLAB Answers


I want to find the centroid for the marked object.

Asked by alaa shamasneh on 14 Jul 2018
Latest activity Commented on by alaa shamasneh on 17 Jul 2018
I want to find the centroid for the marked object. After finding the centroid, find the distance between the centre point and the boundaries.
Please, can anybody help by writing the code which can find the centroid and distance?


What/which shape? The yellow (as if it were filled in or solid), or the white curve inside of the yellow? If the white curve, what do you consider to be the centroid of the white line/curve? Some point lying ON the curve, like it's middle? Or just the actual centroid like the average of the x and y coordinates of it, like
xCenter = mean(x);
yCenter = mean(y);
which may give a centroid off the curve in the middle of the black space? Or do you want the centroid of the convex hull of the white curve? I can't answer until I know what you consider to be the centroid. But whatever it is, it's trivial with the Image Processing Toolbox - I just don't want to give 3 or 4 different scenarios, most of which will be useless to you.
Once you've found the center, you can find the distances from any x,y to xCenter, yCenter like this:
distances = sqrt((x - xCenter) .^ 2 + (y - yCenter) .^ 2);
where x and y are 1-D vectors of the x and y coordinates. distances will also be a 1-D vector of all the distances.
Dear Sir thanks for your replay i appreciate this , i attached a figure to be clear what i want and i already answer your question i want to fined the centre for the white curve i put an arrow on it to be more clear which object.
I want to fined just the actual centroid like the average of the x and y coordinates of it. the centroid in the middle of the black space
after find the centre of object i want to find the distance between centre and boundaries. In the attached figure am try to clear where the centre suppose to be and i draw lines from center to boundaries to try to find distance.
please help me to put the full code thanks very much for help

Sign in to comment.

2 Answers

Answer by Image Analyst
on 14 Jul 2018
 Accepted Answer

After my comment above, you've probably already solved this, but for what it's worth, here is my solution. I didn't draw the lines because there would be too many of them and it would basically just make the shape solid. If you want, you can put line() in a loop. If it does what you want, then please mark the answer as "Accepted". Thanks.
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;
fontSize = 20;
% Read in gray scale demo image.
folder = pwd; % Determine where demo folder is (works with all versions).
baseFileName = 'Alaa_Shamasneh.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Use weighted sum of ALL channels to create a gray scale image.
% grayImage = rgb2gray(rgbImage);
% ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,
% which in a typical snapshot will be the least noisy channel.
grayImage = rgbImage(:, :, 2); % Take green channel.
grayImage = rgbImage; % It's already gray scale.
% Now it's gray scale with range of 0 to 255.
% Turn it into a binary image.
binaryImage = grayImage > 128;
% Display the image.
subplot(2, 2, 1);
imshow(binaryImage, []);
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
% Label each blob with 8-connectivity, so we can make measurements of it
[labeledImage, numberOfBlobs] = bwlabel(binaryImage, 8);
% Apply a variety of pseudo-colors to the regions.
coloredLabelsImage = label2rgb (labeledImage, 'hsv', 'k', 'shuffle');
% Display the pseudo-colored image.
subplot(2, 2, 2);
title('Labeled blobs, uniquely colored.', 'FontSize', fontSize, 'Interpreter', 'None');
% Extract only blob #1, the upper left one.
blob1 = ismember(labeledImage, 1);
% Display the image.
subplot(2, 2, 3);
imshow(blob1, []);
title('Blob #1 with centroid marked', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Get all the blob properties for only this one blob.
[y, x] = find(blob1);
xCenter = mean(x)
yCenter = mean(y)
% Plot a star there
hold on;
plot(xCenter, yCenter, 'r*', 'MarkerSize', 13, 'LineWidth', 2);
% Find distances of everypoint in blob1 to the center point.
distances = sqrt((x - xCenter) .^ 2 + (y - yCenter) .^ 2);
% Display the histogram of distances.
subplot(2, 2, 4);
histogram(distances, 20);
caption = sprintf('Histogram of distances\nfrom center to all other points.');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
xlabel('Distance', 'FontSize', fontSize);
ylabel('Count', 'FontSize', fontSize);
% Compute the mean distance
meanDistance = mean(distances)
% Put a red line there on the histogram.
line([meanDistance, meanDistance], ylim, 'Color', 'r', 'LineWidth', 2);
grid on;
% Label the mean on the plot.
yl = ylim(); % Get range of y axis.
caption = sprintf(' Mean distance = %.2f pixels', meanDistance)
text(meanDistance, 0.95*yl(2), caption, 'FontSize', 14, 'FontWeight', 'bold', 'Color', 'r');


great solution thaaaaanks so much for you.Image analyst you are the best. I have another question please, i want to keep the shape which you fined the centre for it and remove all objects around it do you know how
i will be really thankful for you if you continuous help me to solve this issue.
I did that. In the lower left image is only one object. You can see from the color coded objects in the upper right. Each blob has an ID number - that's why I called bwlabel(). You can extract any one you want with ismember().

Sign in to comment.

Answer by alaa shamasneh on 15 Jul 2018

blob1 = ismember(labeledImage, 1); % Display the image. subplot(2, 2, 3); imshow(blob1, []); title('Blob #1 with centroid marked', 'FontSize', fontSize, 'Interpreter', 'None'); axis('on', 'image');
You defined Blob#1 to be your wanted segment, but this is not how it should be done, because you defined them manually by looking at them. Blob definition should be done automatically by the code . This should be done by analyzing all segments (detection criteria such as measuring area, or perimeter) then pick the most suitable one which resembles the kidneys the most (all of this should be done by the code and without human intervention).


Show 1 older comment
The way I'd do it is to use bwconvhull() to get the convex hull of the objects. Then use
kidneyMask = bwareafilt(convexHullImage, 1);
to extract the largest one. If you want the line inside that again then use that as a mask against your line/curves image.
kidneyCurveOnly = binaryImage; % Initialize
kidneyCurveOnly(~kidneyMask) = false;
If there are separate curves inside the convex hull then you'll need additional steps if you want to extract only one, like calling bwareafilt() again to extract just the longest curve in the kidney mask.
What happened to your other comment and the image you posted? It's gone!
yes i applied what you mention a above but still have some things still not work, i put the result i got and my questions but no one answer , so i remove it .Any way i will put a gain the problem which i try to solve it but i can not if any one can help

Sign in to comment.