How to arrange the shape# (Blob#) in proper order (ascending/descending)?

2 views (last 30 days)
Hello, I am using matlab to recognize the all square object. I need centriods of each square. I am using the following:
[labeledImage, numberOfObjects] = bwlabel(binaryImage);
s = regionprops(labeledImage,'centroid');
to get the centriods. But these shape numbers are so random and I am struggling to arrange it in any proper way. I have to dot it manually which is quite time consuming. Any expert comments will be highly appreciated.
<<
>>
  1 Comment
Saqib Sharif
Saqib Sharif on 10 Sep 2017
My complete Code:
function mesh
ImageFile=('GIST_S16_03.tif');
RGB = imread(ImageFile);
GRAY = rgb2gray(RGB);
threshold = adaptthresh(GRAY,0.613);
BW = imbinarize(GRAY, threshold);
BW = ~ BW;
binaryImage = imfill(BW,'holes');
binaryImage = bwareaopen(binaryImage, 800);
[labeledImage, numberOfObjects] = bwlabel(binaryImage);
filledImage = imfill(binaryImage, 'holes');
boundaries = bwboundaries(filledImage);
figure
imshow(labeledImage);
title('Binary Image with centriods');
hold on
s = regionprops(labeledImage,'centroid');
centroids = cat(1, s.Centroid);
x=centroids(:,1);
y=centroids(:,2);
plot(x,y, 'r*');
for blobNumber = 1 : numberOfObjects
thisBoundary = boundaries{blobNumber};
plot(thisBoundary(:,2), thisBoundary(:,1), 'r', 'LineWidth', 2);
overlayMessage = sprintf('%d',blobNumber);
text(centroids(blobNumber,1), centroids(blobNumber,2), ...
overlayMessage, 'Color', 'g','FontSize',14);
end

Sign in to comment.

Accepted Answer

Jim Joy
Jim Joy on 13 Sep 2017
Hi Saqib,
The labeled image that you have shown is consistent with the conventions that "bwlabel" uses to label the image. The labeling occurs like this because "bwlabel" searches down each column, and labels each region based on when it encounters a pixel first. That is, regions with pixels further leftward than others will be counted first. You can read more about this in the blog post linked below:
To relabel the image regions in the manner that you would like, I would recommend looping over the columnar structure of your labeled image, and relabeling the regions based on the y-positions of the centroid. For example, the first 'column' would be transformed from [8, 9, 6, 5, 7, 3, 4, 2] to [2, 3, 4, 5, 6, 7, 8, 9]. Please note that looping in this fashion will require some level of filtering to divide the image into columns.
I hope this helps.
Jim
  1 Comment
Walter Roberson
Walter Roberson on 13 Sep 2017
Edited: Walter Roberson on 13 Sep 2017
s = regionprops(labeledImage,'centroid');
cents = vertcat(s.Centroid);
[~, sortidx] = sortrows(cents);
s = s(sortidx);
Though as Jim points out you might want to do some smoothing on the x coordinates, or some quantization.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!