Finding the centroid of a binary image

2 views (last 30 days)
vid_c111=read(v,1);
J = imcrop( vid_c111,[766 212 80 150]);
fontSize = 20;
subplot(2, 1, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize, 'Interpreter', 'None');
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
binaryImage = grayImage > 150;
[rows, columns, numberOfColorBands] = size(J);
if numberOfColorBands > 1
grayImage = J(:, :, 3);
end
binaryImage = bwareaopen(binaryImage, 1000);
subplot(2, 1, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
labeledImage = bwlabel(binaryImage, 8);
blobMeasurements = regionprops(labeledImage, 'Centroid');
numberOfBlobs = size(blobMeasurements, 1);
hold on;
for k = 1 : length(blobMeasurements)
x = blobMeasurements(k).Centroid(1);
y = blobMeasurements(k).Centroid(2);
plot(x, y, 'r+', 'MarkerSize', 30, 'LineWidth', 3);
end
The code above was what I used to try and find the centroid of two blobs in my image. Instead of finding the center, it only found the center of the entire image. Any help???
  3 Comments
Guillaume
Guillaume on 17 Apr 2018
Please don't edit your question to remove the useful parts nor remove your comments as it is necessary context to the answer you've accepted.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 17 Apr 2018
Edited: Guillaume on 17 Apr 2018

"I'm only using the first frame of the video"

No, you're using whatever is in grayImage before you run the code above. If before you ran that code you did

grayImage = zeros(10,10);

You'd be using that. You are not using the image created by:

vid_c111=read(v,1); 
J = imcrop( vid_c111,[766 212 80 150]);

If you intended to use that as the grayImage then you need to move the if test up in your code, before you start using grayImage. I'd move it just after the first two lines, and also add an else:

vid_c111=read(v,1); 
J = imcrop( vid_c111,[766 212 80 150]);
if size(J, 3) > 1
    grayImage = J(:, :, 3); %only use blue channel
else
    grayImage = J;
end

With regards to your actual problem, by convention for binary images the background is the black part, and the object is the white part. The centroid of the big white blob is indeed very close to the image centre.

If you intended to find the centroid of the small black blobs, then you need to invert your binary image before you do any processing. The easiest way to do that is to invert your comparison test:

binaryImage = grayImage <= 150;

More Answers (0)

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!