Fit an inside circle of an object - Matlab - matlab

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

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.

Related

Width and height of a rotated polyshape object - Matlab

Based on this question I am trying to calculate the width and height of an object. I did so by converting the examined object to a polyshape and rotated. How can I extract the width and height of the rotated polyshape object? Is there a way to do it using regionprop and will it be more efficient?
Code:
clc;
clear;
close all;
Image = rgb2gray(imread('pillsetc.png'));
BW = imbinarize(Image);
BW = imfill(BW,'holes');
BW = bwareaopen(BW, 100);
[B,L] = bwboundaries(BW,'noholes');
imshow(Image);
hold on;
k=3;
stat = regionprops(BW,'Centroid','Orientation','MajorAxisLength');
b = B{k};
yBoundary = b(:,2);
xBoundary = b(:,1);
centroidObject = stat(k).Centroid;
xCentre = centroidObject(:,2);
yCentre = centroidObject(:,1);
plot(yCentre, xCentre, 'r*')
orientationDegree = stat(k).Orientation
hlen = stat(k).MajorAxisLength/2;
cosOrient = cosd(stat(k).Orientation);
sinOrient = sind(stat(k).Orientation);
xcoords = xCentre + hlen * [cosOrient -cosOrient];
ycoords = yCentre + hlen * [-sinOrient sinOrient];
plot(yBoundary, xBoundary, 'r', 'linewidth', 3);
pgon = polyshape(yBoundary, xBoundary);
polyRot = rotate(pgon,(90+orientationDegree),centroidObject);
plot(polyRot);
[xlim,ylim] = boundingbox(polyRot);
Height = xlim(2) - xlim(1);
Width = ylim(2) - ylim(1);
I would use the angle returned by the minimum Feret diameter calculation to rotate the polygon. Usually, the box at this rotation is the box with minimal area (exceptions seem to be very rare). The 'Orientation' feature is computed based on the best fit ellipse, and would not necessarily yield a small box.
Instead of rotating the full object polygon, you can also rotate only the convex hull, which typically contains fewer points and thus would be more efficient. The Feret computation already uses the convex hull, so there is no additional cost to requesting it from regionprops.
This is code that does what I describe:
Image = rgb2gray(imread('pillsetc.png'));
BW = imbinarize(Image);
BW = imfill(BW,'holes');
BW = bwareaopen(BW, 100);
stat = regionprops(BW,'ConvexHull','MinFeretProperties');
% Compute Feret diameter perpendicular to the minimum diameter
for ii=1:numel(stat)
phi = stat(ii).MinFeretAngle; % in degrees
p = stat(ii).ConvexHull * [cosd(phi),-sind(phi); sind(phi),cosd(phi)];
minRect = max(p) - min(p); % this is the size (width and height) of the minimal bounding box
stat(ii).MinPerpFeretDiameter = minRect(2); % add height to the measurement structure
end
Note that the first value of minRect in the code above is the width of the object (smallest side of minimum bounding box), and equivalent to stat(ii).MinFeretDiameter. The two values are not identical because they are computed differently, but they are pretty close. The second value of minRect, which is saved as “MinPerpFeretDiameter”, is the height (or rather the longest side of the minimum bounding box).

Draw line and Cut off Circuler area

I have got the below Image after running the below code.
file='grayscale.png';
I=imread(file);
bw = im2bw(I);
bw = bwareaopen(bw,870);
imwrite(bw,'noiseReduced.png')
subplot(2,3,1),imshow(bw);
[~, threshold] = edge(bw, 'sobel');
fudgeFactor = .5;
im = edge(bw,'sobel', threshold * fudgeFactor);
subplot(2,3,2), imshow(im), title('binary gradient mask');
se = strel('disk',5);
closedim = imclose(im,se);
subplot(2,3,3), imshow(closedim), title('Connected Cirlces');
cc = bwconncomp(closedim);
S = regionprops(cc,'Centroid'); //returns the centers S(2) for innercircle
numPixels = cellfun(#numel,cc.PixelIdxList);
[biggest,idx] = min(numPixels);
im(cc.PixelIdxList{idx}) = 0;
subplot(2,3,4), imshow(im), title('Inner Cirlces Only');
c = S(2);
My target is now to draw a red cirle around the circular object(see image) and cut the circle region(area) from the original image 'I' and save the cropped area as image or perform other tasks. How can I do it?
Alternatively, you can optimize/fit the circle with least r that contains all the points:
bw = imread('http://i.stack.imgur.com/il0Va.png');
[yy xx]=find(bw);
Now, let p be a three vector parameterizing a circle: p(1), p(2) are the x-y coordinates of the center and p(3) its radii. Then we want to minimize r (i.e., p(3)):
obj = #(p) p(3);
Subject to all points inside the circle
con = #(p) deal((xx-p(1)).^2+(yy-p(2)).^2-p(3).^2, []);
Optimizing with fmincon:
[p, fval] = fmincon(obj, [mean(xx), mean(yy), size(bw,1)/4], [],[],[],[],[],[],con);
Yields
p =
471.6397 484.4164 373.2125
Drawing the result
imshow(bw,'border','tight');
colormap gray;hold on;
t=linspace(-pi,pi,1000);
plot(p(3)*cos(t)+p(1),p(3)*sin(t)+p(2),'r', 'LineWidth',1);
You can generate a binary mask of the same size as bw with true in the circle and false outside
msk = bsxfun(#plus, ((1:size(bw,2))-p(1)).^2, ((1:size(bw,1)).'-p(2)).^2 ) <= p(3).^2;
The mask looks like:
The convexhull of the white pixels will give you a fairly good approximation of the circle. You can find the center as the centroid of the area of the hull and the radius as the average distance from the center to the hull vertices.

Matlab - Subtracting two 3D figures with surf and min function

I'm trying to make a surf plot that looks like:
So far I have:
x = [-1:1/100:1];
y = [-1:1/100:1];
[X,Y] = meshgrid(x,y);
Triangle1 = -abs(X) + 1.5;
Triangle2 = -abs(Y) + 1.5;
Z = min(Triangle1, Triangle2);
surf(X,Y,Z);
shading flat
colormap winter;
hold on;
[X,Y,Z] = sphere();
Sphere = surf(X, Y, Z + 1.5 );% sphere with radius 1 centred at (0,0,1.5)
hold off;
This code produces a graph that looks like :
A pyramid with square base ([-1,1]x[-1,1]) and vertex at height c = 1.5 above the origin (0,0) is erected.
The top of the pyramid is hollowed out by removing the portion of it that falls within a sphere of radius r=1 centered at the vertex.
So I need to keep the part of the surface of the sphere that is inside the pyramid and delete the rest. Note that the y axis in each plot is different, that's why the second plot looks condensed a bit. Yes there is a pyramid going into the sphere which is hard to see from that angle.
I will use viewing angles of 70 (azimuth) and 35 (elevation). And make sure the axes are properly scaled (as shown). I will use the AXIS TIGHT option to get the proper dimensions after the removal of the appropriate surface of the sphere.
Here is my humble suggestion:
N = 400; % resolution
x = linspace(-1,1,N);
y = linspace(-1,1,N);
[X,Y] = meshgrid(x,y);
Triangle1 = -abs(X)+1.5 ;
Triangle2 = -abs(Y)+1.5 ;
Z = min(Triangle1, Triangle2);
Trig = alphaShape(X(:),Y(:),Z(:),2);
[Xs,Ys,Zs] = sphere(N-1);
Sphere = alphaShape(Xs(:),Ys(:),Zs(:)+2,2);
% get all the points from the pyramid that are within the sphere:
inSphere = inShape(Sphere,X(:),Y(:),Z(:));
Zt = Z;
Zt(inSphere) = nan; % remove the points in the sphere
surf(X,Y,Zt)
shading interp
view(70,35)
axis tight
I use alphaShape object to remove all unwanted points from the pyramid and then plot it without them:
I know, it's not perfect, as you don't see the bottom of the circle within the pyramid, but all my tries to achieve this have failed. My basic idea was plotting them together like this:
hold on;
Zc = Zs;
inTrig = inShape(Trig,Xs(:),Ys(:),Zs(:)+1.5);
Zc(~inTrig) = nan;
surf(Xs,Ys,Zc+1.5)
hold off
But the result is not so good, as you can't really see the circle within the pyramid.
Anyway, I post this here as it might give you a direction to work on.
An alternative to EBH's method.
A general algorithm from subtracting two shapes in 3d is difficult in MATLAB. If instead you remember that the equation for a sphere with radius r centered at (x0,y0,z0) is
r^2 = (x-x0)^2 + (y-y0)^2 + (z-z0)^2
Then solving for z gives z = z0 +/- sqrt(r^2-(x-x0)^2-(y-y0)^2) where using + in front of the square root gives the top of the sphere and - gives the bottom. In this case we are only interested in the bottom of the sphere. To get the final surface we simply take the minimum z between the pyramid and the half-sphere.
Note that the domain of the half-sphere is defined by the filled circle r^2-(x-x0)^2-(y-y0)^2 >= 0. We define any terms outside the domain as infinity so that they are ignored when the minimum is taken.
N = 400; % resolution
z0 = 1.5; % sphere z offset
r = 1; % sphere radius
x = linspace(-1,1,N);
y = linspace(-1,1,N);
[X,Y] = meshgrid(x,y);
% pyramid
Triangle1 = -abs(X)+1.5 ;
Triangle2 = -abs(Y)+1.5 ;
Pyramid = min(Triangle1, Triangle2);
% half-sphere (hemisphere)
sqrt_term = r^2 - X.^2 - Y.^2;
HalfSphere = -sqrt(sqrt_term) + z0;
HalfSphere(sqrt_term < 0) = inf;
Z = min(HalfSphere, Pyramid);
surf(X,Y,Z)
shading interp
view(70,35)
axis tight

examples to convert image to polar coordinates do it explicitly - want a slick matrix method

I am trying to convert an image from cartesian to polar coordinates.
I know how to do it explicitly using for loops, but I am looking for something more compact.
I want to do something like:
[x y] = size(CartImage);
minr = floor(min(x,y)/2);
r = linspace(0,minr,minr);
phi = linspace(0,2*pi,minr);
[r, phi] = ndgrid(r,phi);
PolarImage = CartImage(floor(r.*cos(phi)) + minr, floor(r.sin(phi)) + minr);
But this obviously doesn't work.
Basically I want to be able to index the CartImage on a grid.
The polar image would then be defined on the grid.
given a matrix M (just a 2d Gaussian for this example), and a known origin point (X0,Y0) from which the polar transform takes place, we expect that iso-intensity circles will transform to iso-intensity lines:
M=fspecial('gaussian',256,32); % generate fake image
X0=size(M,1)/2; Y0=size(M,2)/2;
[Y X z]=find(M);
X=X-X0; Y=Y-Y0;
theta = atan2(Y,X);
rho = sqrt(X.^2+Y.^2);
% Determine the minimum and the maximum x and y values:
rmin = min(rho); tmin = min(theta);
rmax = max(rho); tmax = max(theta);
% Define the resolution of the grid:
rres=128; % # of grid points for R coordinate. (change to needed binning)
tres=128; % # of grid points for theta coordinate (change to needed binning)
F = TriScatteredInterp(rho,theta,z,'natural');
%Evaluate the interpolant at the locations (rhoi, thetai).
%The corresponding value at these locations is Zinterp:
[rhoi,thetai] = meshgrid(linspace(rmin,rmax,rres),linspace(tmin,tmax,tres));
Zinterp = F(rhoi,thetai);
subplot(1,2,1); imagesc(M) ; axis square
subplot(1,2,2); imagesc(Zinterp) ; axis square
getting the wrong (X0,Y0) will show up as deformations in the transform, so be careful and check that.
I notice that the answer from bla is from polar to cartesian coordinates.
However the question is in the opposite direction.
I=imread('output.png'); %read image
I1=flipud(I);
A=imresize(I1,[1024 1024]);
A1=double(A(:,:,1));
A2=double(A(:,:,2));
A3=double(A(:,:,3)); %rgb3 channel to double
[m n]=size(A1);
[t r]=meshgrid(linspace(-pi,pi,n),1:m); %Original coordinate
M=2*m;
N=2*n;
[NN MM]=meshgrid((1:N)-n-0.5,(1:M)-m-0.5);
T=atan2(NN,MM);
R=sqrt(MM.^2+NN.^2);
B1=interp2(t,r,A1,T,R,'linear',0);
B2=interp2(t,r,A2,T,R,'linear',0);
B3=interp2(t,r,A3,T,R,'linear',0); %rgb3 channel Interpolation
B=uint8(cat(3,B1,B2,B3));
subplot(211),imshow(I); %draw the Original Picture
subplot(212),imshow(B); %draw the result

How to change an image from Cartesian to Polar coordinates in Matlab?

I am trying to convert the pixels of an image from x-y coordinate to polar coordinate and I have problem with it, as I want to code the function by myself.
Here is the code I did so far:
function [ newImage ] = PolarCartRot
% read and show the image
image= imread('1.jpg');
%%imshow(image);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%change to polar coordinate
[x y z]= size(image);
r = sqrt(x*x+y*y);
theta = atan2(y,x);
for i =0:r
for j= 0:theta
newpixel = [i; j];
newImage(newpixel(1), newpixel(2),:) = image(i,j,:);
end
end
figure;
imshow (newImage);
It is not quite clear what you are trying to do, which is why I am making my own example...
So given an image, I am converting the pixel x/y coordinates from Cartesian to polar with CART2POL.
In the first figure, I am showing the locations of the points, and in the second, I plot both the original image and the one with polar coordinates.
Note that I am using the WARP function from the Image Processing Toolbox. Under the hood, it uses the SURF/SURFACE function to display a texture-mapped image.
% load image
load clown;
img = ind2rgb(X,map);
%img = imread(...); % or use any other image
% convert pixel coordinates from cartesian to polar
[h,w,~] = size(img);
[X,Y] = meshgrid(1:w,1:h);
[theta,rho] = cart2pol(X, Y);
Z = zeros(size(theta));
% show pixel locations (subsample to get less dense points)
XX = X(1:8:end,1:4:end);
YY = Y(1:8:end,1:4:end);
tt = theta(1:8:end,1:4:end);
rr = rho(1:8:end,1:4:end);
subplot(121), scatter(XX(:),YY(:),3,'filled'), axis ij image
subplot(122), scatter(tt(:),rr(:),3,'filled'), axis ij square tight
% show images
figure
subplot(121), imshow(img), axis on
subplot(122), warp(theta, rho, Z, img), view(2), axis square
EDIT
As I originally stated, the question is not clear. You have to describe the mapping you want in a well defined manner...
For one you need to think about where the origin is located before converting to polar coordinates. The previous example assume the origin to be the axes base at (0,0). Suppose you want to take the center of the image (w/2,h/2) as origin, then you would do this instead:
[X,Y] = meshgrid((1:w)-floor(w/2), (1:h)-floor(h/2));
with the rest of the code unchanged. To better illustrate the effect, consider a source image with concentric circles drawn in Cartesian coordinates, and notice how they map to straight lines in polar coordinates when using the center of the circles as origin:
EDIT
Here is another example of how to display an image in polar coordinates as requested in the comments. Note that we perform the mapping in the inverse direction pol2cart:
[h,w,~] = size(img);
s = min(h,w)/2;
[rho,theta] = meshgrid(linspace(0,s-1,s), linspace(0,2*pi));
[x,y] = pol2cart(theta, rho);
z = zeros(size(x));
subplot(121), imshow(img)
subplot(122), warp(x, y, z, img), view(2), axis square tight off
Again the effect is better show if you feed it an input image with straight lines, and see how they map in polar coordinates (vertical lines become circles, and horizontal lines become rays emanating from the origin):