I am working on a MATLAB project where the user will upload a scanned image of ellipse-like objects, and the program have to calculate measurements (height, width, area,..etc) of every object in the image.
I started with thresholding that produces a binary image (a black background and white independent objects). This is the BW image after thresholding:
After that, I used regionprops
since it returns most of the measurements that I need, and it worked perfectly.
The problem is that the order in which the function "recognizes/detects" objects is not consistent. I added a code to show the number of each object so I could know which object has regionprops
considered as the first and which one is the second..etc.
The code:
% read image
rgb=imread('bw');
s = regionprops(bw,'Area', 'BoundingBox', 'Eccentricity', 'MajorAxisLength', 'MinorAxisLength', 'Orientation', 'Perimeter','Centroid');
% show the number of each object
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', 'color', 'r');
end
hold off;
This is the image after showing the order of objects:
I need the order to be from top-left to bottom-right. ( first row of objects is numbered from 1 to 6, second row from 7 to 12..etc). Is that possible?
Many thanks.
The regionprops function returns the centroids in a structure array. s = regionprops(BW,'centroid'); Store the x- and y-coordinates of the centroids into a two-column matrix. centroids = cat(1,s.
Get information about the objects in an image. Image regions, also called objects, connected components, or blobs, have properties such as area, center of mass, orientation, and bounding box.
When we right click on an image and select properties->details , we have the resolution information.
Description. [ x , y ] = centroid( polyin ) returns the x-coordinates and the y-coordinates of the centroid of a polyshape . [ x , y ] = centroid( polyin , I ) returns the coordinates of the centroid of the I th boundary of polyin .
Working off of Suever's suggestion to use the Centroid
data, and assuming that s
contains only the 18 regions of interest in the examples, here's one way to sort s
from left-to-right, top-to-bottom using histcounts
and sortrows
:
coords = vertcat(s.Centroid); % 2-by-18 matrix of centroid data
[~, ~, coords(:, 2)] = histcounts(coords(:, 2), 3); % Bin the "y" data
[~, sortIndex] = sortrows(coords, [2 1]); % Sort by "y" ascending, then "x" ascending
s = s(sortIndex); % Apply sort index to s
And here's a picture showing the labeling of each area (as you did in your code sample):
The binning of the "y" data first allows us to group objects into 3 rows of 6. The sortrows
function, after sorting by this bin value, is then able to do sub-sorting of all the "x" values for each unique binned group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With