I have been using Peter Kovesi's MatLab functions for machine vision (which are outstanding if you aren't aware of them).
I have been transforming images to polar co-ordinates using the polar transform. The function from Peter Kovesi is named 'PolarTrans' and can be found here -
http://www.peterkovesi.com/matlabfns/#syntheticimages
The function beautifully transforms an images into polar co-ordinates. However, I would like the reverse to happen also. Peter Kovesi uses interp2 to transform images, but I can't seem to figure out how to reverse this transform. A requirement of interp2 is that it needs a meshgrid as input.
In short - can you help me reverse the transformation: polar to cartesian. I would like it be accordance with Peter's function - i.e. using the same parameters for coherence.
Dear Swjm,
I am posting my reply here because I do not have space in the comments section.
Firstly, thank you very much indeed for your reply. You have shown me how to invert interp2 - something I thought was impossible. This is a huge step forwards. However your code only maps a small segment of the image. Please see the demo code below to understand what I mean.
clc; clear all; close all;
gauss = fspecial('gauss',64,15);
gauss = uint8(mat2gray(gauss).*255);
[H,W] = size(gauss);
pim = polartrans(gauss,64,360);
cim = carttrans(pim,64,64);
subplot(2,2,1);
imagesc(gauss); colormap(jet);
axis off;
title('Image to be Transformed');
subplot(2,2,2);
imagesc(pim); colormap(jet);
axis off;
title('Polar Representation');
subplot(2,2,3);
imagesc(cim); colormap(jet);
axis off;
title('Back to Cartesian');
subplot(2,2,4);
diff = uint8(gauss) - uint8(cim);
imagesc(diff); colormap(jet);
axis off;
title('Difference Image');
I've had a look at Kovesi's code and this code should perform the reverse transformation. It assumes you used the 'full' shape and 'linear' map parameters in polartrans. Note that polar transforms generally lose resolution at low radial values (and gain resolution at high values), so it won't be lossless even if your polar image has the same dimensions as your original image.
function im = carttrans(pim, nrows, ncols, cx, cy)
[rad, theta] = size(pim); % Dimensions of polar image.
if nargin==3
cx = ncols/2 + .5; % Polar coordinate center, should match
cy = nrows/2 + .5; % polartrans. Defaults to same.
end
[X,Y] = meshgrid(1:ncols, 1:nrows);
[TH,R] = cart2pol(X-cx,Y-cy); % Polar coordinate arrays.
TH(TH<0) = TH(TH<0)+2*pi; % Put angles in range [0, 2*pi].
rmax = max(R(:)); % Max radius.
xi = TH * (theta+1) / 2*pi; % Query array for angles.
yi = R * rad / (rmax-1) + 1; % Query array for radius.
pim = [pim pim(:,1)]; % Add first col to end of polar image.
[pX,pY] = meshgrid(1:theta+1, 1:rad);
im = interp2(pX, pY, pim, xi, yi);
Related
I have implemented the Hermite-Gaussian function in matlab for producing different modes. The light beam along z direction can be seen as a complex matrix in the plane.
The function for HG modes is as below.
%Hermite polynomial
function hk = HermitePoly(n)
if n==0
hk = 1;
elseif n==1
hk = [2 0];
else
hkm2 = zeros(1,n+1);
hkm2(n+1) = 1;
hkm1 = zeros(1,n+1);
hkm1(n) = 2;
for k=2:n
hk = zeros(1,n+1);
for e=n-k+1:2:n
hk(e) = 2*(hkm1(e+1) - (k-1)*hkm2(e));
end
hk(n+1) = -2*(k-1)*hkm2(n+1);
if k<n
hkm2 = hkm1;
hkm1 = hk;
end
end
end
% this is the function of HG modes in z position.
function [HGBeam,X,Y] = Hermite_Gaussian(N,hx,hy,w0,delta,lamda,z)
[X Y]=meshgrid((-N/2:N/2-1)*delta);
[theta,rad] = cart2pol(X,Y);
k=2*pi/lamda;
zr=pi*w0^2/lamda;
wz=w0*sqrt(1+(z/zr)^2);
qz=z+1i*zr;
q0=1i*zr;
if z==0
rz=Inf;
else
rz=z*(1+(zr/z)^2);
end
AmpLGB=sqrt(2/(2^(hx+hy)*pi*factorial(hx)*factorial(hy)*w0^2)).*(q0/qz).*(-conj(qz)/qz)^((hx+hy)/2).*exp(-(rad.*rad)/(wz)^2).*polyval(HermitePoly(hx),sqrt(2)*X/wz).*polyval(HermitePoly(hy),sqrt(2)*Y/wz);
PsLGB=exp(-1i*(k*(rad.*rad)/(2*rz)+k*z-(hx+hy+1)*atan(z/zr)));
HGBeam=AmpLGB.*PsLGB;
end
Now I plot one example for HG(2,0) as the following (example1):
clc
clear all;
close all;
lambda=809e-9; % optical wavelength
w0=0.025; %optical beam waist 15mm
k=2*pi/lambda; % optical wavenumber
Zr=pi*w0^2/lambda; % Rayleigh range
z0=0; % start position z=0; but careful 0*Inf is undefined, here 0*Inf=NAN
N=1024; % samples/side length at source plane
D1=0.25; % side length [m] at source plane
delta1=D1/N; % grid spacing [m]
x1=-D1/2:delta1:D1/2-delta1; % source plane x and y coordinates
y1=x1;
%% HG modes
HGx=2;
HGy=0;
HGintheory=Hermite_Gaussian(N,HGx,HGy,w0,delta1,lambda,z0);
h7=figure(7);
imagesc(x1,y1,abs(HGintheory).^2);
title(sprintf('z=%d; HG(%d,%d)',z0,HGx,HGy))
xlabel('x (m)'); ylabel('y (m)');
The plot of the light field will be as the following picture in the left side (its intensity):
We can use rot90() function to rotate matrix HGintheory (which is add one line code: HGintheory=rot90(HGintheory);) and then the field will rotate 90 degree (right side of the intensity plot).
Because I want to work with the light field. So the question is how can I rotate the complex matrix HGintheory in
arbitrary angle? For example 45 degree?
Does anyone knows how to rotate a complex matrix with big size? If something is wrong or unclear, please pointing out and Thank you in advance!
You can decompose your complex field into two real fields (amplitude and phase), rotate both with imrotate, and combine them afterwards pixel-wise
Hamp=abs(HGintheory);
Hphase=angle(HGintheory);
RotAngle=45;
HampRot=imrotate(Hamp,RotAngle,'bilinear','crop');
HphaseRot=imrotate(Hphase,RotAngle,'bilinear','crop');
HfullRot=HampRot.*exp(1i*HphaseRot);
figure(1);
imagesc(x1,y1,abs(HGintheory).^2);
figure(2);
imagesc(x1,y1,abs(HfullRot).^2);
You can rotate your initial meshgrid using:
[X,Y] = meshgrid(x1,y1)
xyc = [mean(x1), mean(y1)];
angel = 45;
R = [cosd(angel), -sind(angel); sind(angel), cosd(angel)];
XY = xyc' + R * ([X(:) Y(:)]-xyc)';
XR = reshape(XY(1,:),size(X));
YR = reshape(XY(2,:),size(Y));
and then use those transformed coordinates to plot:
imagesc(XR,YR,IntensityHGin);
I'm trying to create a gradient fill inside a circular area according to a given function. I hope the plot below explains it at best
I'm not sure how to approach this, as in the simulation I'm working on the direction of the gradient changes (not always in the x direction as below, but free to be along all the defined angles), so I'm looking for a solution that will be flexible in that manner as well.
The code I have is below
clear t
N=10;
for i=0:N
t(i+1) = 0+(2*i*pi) / N;
end
F = exp(-cos(t))./(2.*pi*besseli(1,1));
figure(1)
subplot(1,3,1)
plot(t*180/pi,F,'-ob')
xlim([0 360])
xlabel('angle')
subplot(1,3,2)
hold on
plot(cos([t 2*pi]), sin([t 2*pi]),'-k','linewidth',2);
plot(cos([t 2*pi]), sin([t 2*pi]),'ob');
plot(cos(t).*F,sin(t).*F,'b','linewidth',2);
subplot(1,3,3)
hold on
plot(cos([t 2*pi]), sin([t 2*pi]),'-k','linewidth',2);
plot(cos([t 2*pi]), sin([t 2*pi]),'ob');
To fill surface, you need to use the patch command.
t = linspace(0, 2*pi, 100);
x = cos(t);
y = sin(t);
c = x; % colored following x value and current colormap
figure
patch(x,y,c)
hold on
scatter(x,y)
hold off
colorbar
Resulting graph:
Colors are defined in c per point, and are interpolated inside the shape, so I'm sure that you should have all freedom to color as you want!
For example, the rotated version:
t = linspace(0, 2*pi, 100);
x = cos(t);
y = sin(t);
c = cos(t+pi/4)
figure
patch(x,y,c)
colorbar
To understand how it is going on, just think that every point has a color, and matlab interpolate inside. So here I just rotated the intensity per point by pi /4.
For this to work you need to have a filled shape, and you may need to customize the color (c) parameter so that it matches your need. For example, if your gradient direction is encoded in a vector, you want to project all your point onto that vector to get the value along the gradient for all points.
For example:
% v controls the direction of the gradient
v = [0.1, 1];
t = linspace(0, 2*pi, 100);
F = exp(-cos(t))./(2.*pi*besseli(1,1));
% reconstructing point coordinate all around the surface
% this closes the path so with enough points so that interpolation works correctly
pts = [[t', F']; [t(end:-1:1)', ones(size(t'))*min(F)]];
% projecting all points on the vector to get the color
c = pts * (v');
clf
patch(pts(:,1),pts(:,2),c)
hold on
scatter(t, F)
hold off
I have a problem and maybe you will be able to help me. Like in the title i have cross section data of a symmetric lens - coordinates s=-100:1:100 and height y - and I would like to create 3D plot the whole lens (x,y,z). Is there any build in function that helps with that? Thanks for help in advance!
If I'm understanding correctly, you have a 1-D array that you'd effectively like to 'sweep' around a circle to produce a 3-D plot. Here is an example of how to do that
% Some dummy data
Npts = 100;
z = sin(linspace(0, pi, Npts));
Nreps = 100; % How many times to repeat around circle
% Create polar meshgrid and convert to Cartesian
[r, theta] = meshgrid( ...
linspace(-length(z)/2, length(z)/2, Npts), ...
linspace(0, pi, Nreps));
[X, Y] = pol2cart(theta, r);
% Copy data Nreps times
Z = repmat(z, Nreps, 1);
% Plot!
surf(X, Y, Z)
Without more specs (such as if your y is a 2D matrix or a 1D array), it's not possible to give you the exact answer. However here is how you draw a surface in Matlab:
% create a meshgrid used as the independent variables of your surface
[sx, sy] = meshgrid(-100:100);
% if you have your own 2D matrix, ignore this line.
% if you have a formula, replace this line with your own formula
y = cos(sqrt(((sx/100).^2+(sy/100).^2)/2)*(pi/2));
% draw the surface
surf(sx, sy, y);
To have the opposite side as well, draw another surf on the same figure:
hold on;
surf(sx, sy, -y);
I have a dataset that describes a point cloud of a 3D cylinder (xx,yy,zz,C):
and I would like to make a surface plot from this dataset, similar to this
In order to do this I thought I could interpolate my scattered data using TriScatteredInterp onto a regular grid and then plot it using surf:
F = TriScatteredInterp(xx,yy,zz);
max_x = max(xx); min_x = min(xx);
max_y = max(yy); min_y = min(yy);
max_z = max(zz); min_z = min(zz);
xi = min_x:abs(stepSize):max_x;
yi = min_y:abs(stepSize):max_y;
zi = min_z:abs(stepSize):max_z;
[qx,qy] = meshgrid(xi,yi);
qz = F(qx,qy);
F = TriScatteredInterp(xx,yy,C);
qc = F(qx,qy);
figure
surf(qx,qy,qz,qc);
axis image
This works really well for convex and concave objects but ends in this for the cylinder:
Can anybody help me as to how to achieve a nicer plot?
Have you tried Delaunay triangulation?
http://www.mathworks.com/help/matlab/ref/delaunay.html
load seamount
tri = delaunay(x,y);
trisurf(tri,x,y,z);
There is also TriScatteredInterp
http://www.mathworks.com/help/matlab/ref/triscatteredinterp.html
ti = -2:.25:2;
[qx,qy] = meshgrid(ti,ti);
qz = F(qx,qy);
mesh(qx,qy,qz);
hold on;
plot3(x,y,z,'o');
I think what you are loking for is the Convex hull function. See its documentation.
K = convhull(X,Y,Z) returns the 3-D convex hull of the points (X,Y,Z),
where X, Y, and Z are column vectors. K is a triangulation
representing the boundary of the convex hull. K is of size mtri-by-3,
where mtri is the number of triangular facets. That is, each row of K
is a triangle defined in terms of the point indices.
Example in 2D
xx = -1:.05:1; yy = abs(sqrt(xx));
[x,y] = pol2cart(xx,yy);
k = convhull(x,y);
plot(x(k),y(k),'r-',x,y,'b+')
Use plot to plot the output of convhull in 2-D. Use trisurf or trimesh to plot the output of convhull in 3-D.
A cylinder is the collection of all points equidistant to a line. So you know that your xx, yy and zz data have one thing in common, and that is that they all should lie at an equal distance to the line of symmetry. You can use that to generate a new cylinder (line of symmetry taken to be z-axis in this example):
% best-fitting radius
% NOTE: only works if z-axis is cylinder's line of symmetry
R = mean( sqrt(xx.^2+yy.^2) );
% generate some cylinder
[x y z] = cylinder(ones(numel(xx),1));
% adjust z-range and set best-fitting radius
z = z * (max(zz(:))-min(zz(:))) + min(zz(:));
x=x*R;
y=y*R;
% plot cylinder
surf(x,y,z)
TriScatteredInterp is good for fitting 2D surfaces of the form z = f(x,y), where f is a single-valued function. It won't work to fit a point cloud like you have.
Since you're dealing with a cylinder, which is, in essence, a 2D surface, you can still use TriScatterdInterp if you convert to polar coordinates, and, say, fit radius as a function of angle and height--something like:
% convert to polar coordinates:
theta = atan2(yy,xx);
h = zz;
r = sqrt(xx.^2+yy.^2);
% fit radius as a function of theta and h
RFit = TriScatteredInterp(theta(:),h(:),r(:));
% define interpolation points
stepSize = 0.1;
ti = min(theta):abs(stepSize):max(theta);
hi = min(h):abs(stepSize):max(h);
[qx,qy] = meshgrid(ti,hi);
% find r values at points:
rfit = reshape(RFit(qx(:),qy(:)),size(qx));
% plot
surf(rfit.*cos(qx),rfit.*sin(qx),qy)
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