1

I wish to fit an inside circle of an outline object, how can I do it? in the example shown I tried to calculate the r by dividing the MajorAxisLength but it does not work.

Code:

clc;
clear;
RGB = imread('pillsetc.png');
I = rgb2gray(RGB);
bw = imbinarize(I);
imshow(bw)
bw = bwareaopen(bw,30);
bw = imfill(bw,'holes');
imshow(bw)
[B,L] = bwboundaries(bw,'noholes');
stats = regionprops(L,'Centroid','MajorAxisLength');
hold on   
k=3;  
boundary = B{k};
r = stats(k).MajorAxisLength/2;
centroid = stats(k).Centroid;
plot(centroid(1),centroid(2),'+');
theta = linspace(0,2*pi);
x = r*cos(theta) + centroid(1);;
y = r*sin(theta) + centroid(2);;
plot(x,y)
axis equal

enter image description here

enter image description here

AsiJapan
  • 313
  • 1
  • 10

1 Answers1

1

Ok, this is an approximated solution, but given the limited parameters you can get from regionprops, this is probably good enough.

My derivations are follows:

the goal to calculate the radius of the inscribed circle of a rectangle is to estimate the length of the short-edge.

If we assume the elliptic fitting to a rectangle yields approximately the same area as the rectangle, and the short/long edge ratio is the same as the minor/major axis ratios, then, we can obtain the following equation:

x=short edge of the rectangle;
y=long edge of the rectangle;
b=minor axis of the fitted ellipse;
a=major axis of the fitted ellipse;

then we have

x/y=b/a
x*y=a*b*pi

from that, we can solve the value of x is sqrt(pi)*b. That makes the radius of the inscribed circle sqrt(pi)/2*b.

changing your below two lines of code

stats = regionprops(L,'Centroid','MinorAxisLength');
...
r = stats(k).MinorAxisLength*(sqrt(pi)/4);
...

I was able to get something pretty close to the inscribed circle. Give it a try.

FangQ
  • 1,444
  • 10
  • 18
  • Thanks. I tried your solution and checked some other object. It does not look that it is the best radius. Image added to question. Any way to optimize it? – AsiJapan Apr 11 '20 at 08:24
  • for round-shaped objects, try MinorAxisLength by itself. – FangQ Apr 11 '20 at 13:06