How to use regionprops to find areas of specific size, and draw an ellipse around them of different colors?

19 views (last 30 days)
I have a script that finds all the "nuclei" of an image, but I want to exclude pixels less than three or greater than 200 and draw a green ellipse around them, while for everything within that range I want to create a yellow ellipse.
I've uploaded the code to Github here and the code is also found below.
Figure is here and below the code.
I think I have to use s.area but I'm not sure how to use that.
hy = fspecial('sobel');
hx = hy';
Iy = imfilter(double(graypic), hy, 'replicate');
Ix = imfilter(double(graypic), hx, 'replicate');
img = sqrt(Ix.^2 + Iy.^2);
figure(2), imshow(img,[]), title('Sobel')
img = img./max(max(img));
%chosen threshold
threshs = [0.34]
for i =1:length(threshs)
BW = im2bw(sobelpic,threshs(i));
title(['threshs=0.34 ',num2str(i)]);
BW = im2bw(sobelpic,threshs(1));
BW = imcomplement(BW);
s = regionprops(BW,'Orientation', 'MajorAxisLength', ...
'MinorAxisLength', 'Eccentricity', 'Centroid');
hold on
phi = linspace(0,2*pi,50);
cosphi = cos(phi);
sinphi = sin(phi);
for k = 1:length(s)
xbar = s(k).Centroid(1);
ybar = s(k).Centroid(2);
a = s(k).MajorAxisLength/2; % I believe I need to work in this area? But I'm not sure.
b = s(k).MinorAxisLength/2;
theta = pi*s(k).Orientation/180;
R = [ cos(theta) sin(theta)
-sin(theta) cos(theta)];
xy = [a*cosphi; b*sinphi];
xy = R*xy;
x = xy(1,:) + xbar;
y = xy(2,:) + ybar;
hold on;
%s=regionprops (number of nuclei) = 803
%I've tried
for k=1:length(s)
area=s.Area(LB> 3, UB<200);
upperareas = (s.Area.<200)
lowerareas= (s.Area.>3)
diameters = mean([s.MajorAxisLength<200 s.MinorAxisLength>3],2);
radii = diameters/2;
%but I'm not exactly sure what I'm doing.

Answers (1)

Harikrishnan Balachandran Nair
Hi Kristin,
I understand that you are trying to find connected Components in your binary image having areas within a specified limit , using the 'regionprops' function.
In the given code, since you have not mentioned the 'Area' property inside the 'regionprops' function, the resulting struct 's' will not have a field named 'Area'. You can add the 'Area' field to the output using the following code
s = regionprops(BW,'Orientation', 'MajorAxisLength', ...
'MinorAxisLength', 'Eccentricity', 'Centroid','Area');
You can further extract the 'Area' field of all components as an array, and find the indices where the value of area is in the desired range.
idx = ([s.Area]<UB & [s.Area]>LB);
Now , with the help of these indices, you can draw the circles of desired colour at the required centroids using the 'viscircles' function.

Community Treasure Hunt

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

Start Hunting!