Corresponding image coordinates of 3D points plotted in MATLAB - matlab

I have the following simple MATLAB code:
figure()
x = [0, 0, 0];
y = [0, 0, 0];
z = [-10, 0, 10];
plot3(x, y, z, 'ro');
xlim([-20 20])
ylim([-20 20])
zlim([-20 20])
xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis')
With a certain camera view the resulting figure looks like this:
Now I want to know the resulting image coordinates of the three 3D points if I save the axes to an image:
img = frame2im(getframe(gca));
E.g. Point [0 0 -10] corresponds to pixel (x = ?, y = ?) in img
Is there any straightforward way to compute this mapping?

Related

How can I create a rectangle with a hole in MATLAB/OCTAVE?

I would like to plot/draw exactly this shape in MATLAB or OCTAVE. Of course I do know how to plot, and how to create rectangles, using either the plot, the line or the rectangle functions. But I have not yet managed to add this "hole" on the top side of the rectangle. I figure, it's a (half-)circle of radius 0.5 and center point (1.5|2). In OCTAVE, there is a drawCircleArc function, but I don't want to only draw that thing, but also to have the necessary coordinates defining the whole shape for further manipulation.
Here is one way (matlab/octave compatible):
% Specify all polygon points, excluding the semi-circle outline
X = [1, 0, 0, 3, 3, 2];
Y = [2, 2, 0, 0, 2, 2];
% Add semi-circle outline to array of polygon points
t = 0 : -0.01 : -pi;
X = [X, 1.5 + 0.5 * cos(t)];
Y = [Y, 2 + 0.5 * sin(t)];
% Use fill to plot the filled polygon, with desired settings
fill( X, Y, [0.8, 0.8, 0.8], 'linewidth', 1.5 );
axis( [-2, 4, -2, 4] ); axis equal;
As of 2017b you can also use polyshapes and boolean operators.
rect = polyshape([0 3 3 0], [0 0 2 2]);
t = linspace(0, 2*pi, 32);
circ = polyshape(1.5+.5*cos(t), 2+.5*sin(t));
subplot 121, hold on
plot(rect)
plot(circ)
axis equal
shape = subtract(rect, circ);
subplot 122
plot(shape)
axis equal

Polygon Rotation using matrix-vector multiplication

Consider the polygon with vertices (0, 0), (1, 0), (7/10, 1), (1/2, 1/2), and (3/10, 1). Make a plot of this polygon in Matlab using the fill function. Rotate this polygon by an angle of 100 degrees using matrix-vector multiplication in Matlab with an appropriately chosen rotation matrix R. Make another plot of the rotated polygon using fill.
% Makes original polygon
X = [0 1 7/10 1/2 3/10];
Y = [0 0 1 1/2 1];
norm_poly = fill(X,Y,'k');
thetad = 100;
R = [cosd(thetad) -sind(thetad); sind(thetad) cosd(thetad)];
C = repmat([0 0], 5, 1)';
axis([-10 10 -10 10])
V = get(norm_poly,'Vertices')'; % get the current set of vertices
V = R*(V - C) + C; % do the rotation relative to the centre of the
square
set(norm_poly,'Vertices',V'); % update the vertices
How would I make to different plots to show them? Does the code to rotate make sense and answer all the requirements?
The rotation itself makes sense. To plot multiple things to the same graph use hold on after making the first plot. Alternatively you can make a new figure and plot a new fill there.
P = [0, 1, 7/10, 1/2, 3/10;
0, 0, 1, 1/2, 1];
fill(P(1,:), P(2,:), 'k');
theta = 100;
R = #(t) [cosd(t) -sind(t); sind(t) cosd(t)];
axis([-3 3 -3 3])
grid on
V = R(theta)*P;
hold on;
fill(V(1,:), V(2,:), 'k');

How can I fill an area below a 3D graph in MATLAB?

I created the following 3d plot in MATLAB using the function plot3:
Now, I want to get a hatched area below the "2d sub-graphs" (i.e. below the blue and red curves). Unfortunately, I don't have any idea how to realize that.
I would appreciate it very much if somebody had an idea.
You can do this using the function fill3 and referencing this answer for the 2D case to see how you have to add points on the ends of your data vectors to "close" your filled polygons. Although creating a pattern (i.e. hatching) is difficult if not impossible, an alternative is to simply adjust the alpha transparency of the filled patch. Here's a simple example for just one patch:
x = 1:10;
y = rand(1, 10);
hFill = fill3(zeros(1, 12), x([1 1:end end]), [0 y 0], 'b', 'FaceAlpha', 0.5);
grid on
And here's the plot this makes:
You can also create multiple patches in one call to fill3. Here's an example with 4 sets of data:
nPoints = 10; % Number of data points
nPlots = 4; % Number of curves
data = rand(nPoints, nPlots); % Sample data, one curve per column
% Create data matrices:
[X, Y] = meshgrid(0:(nPlots-1), [1 1:nPoints nPoints]);
Z = [zeros(1, nPlots); data; zeros(1, nPlots)];
patchColor = [0 0.4470 0.7410]; % RGB color for patch edge and face
% Plot patches:
hFill = fill3(X, Y, Z, patchColor, 'LineWidth', 1, 'EdgeColor', patchColor, ...
'FaceAlpha', 0.5);
set(gca, 'YDir', 'reverse', 'YLim', [1 nPoints]);
grid on
And here's the plot this makes:

Filling an area above a curve with many colors (matlab, surf)

I'm trying to create a figure in matlab that looks like this:
desired figure
I am doing so by: (i) assigning value points to each x,y coordinate, (ii) plotting a surf, and (iii) change the view point so the third axis is not seen. Here is the code:
x = linspace(0, 1, 10);
y = linspace(0, 1, 10);
z = linspace(0, 1, 10);
z = repmat(z, 10, 1);
z = flipud(triu(z));
z(z==0) = nan;
hold off
surf(x, y, z, 'linestyle', 'none')
colormap([linspace(0.39, 1, 20)',linspace(0.58, 0.25, 20)', linspace(0.93, 0.25, 20)']);
colorbar
xlim([x(1) x(end)])
shading interp
view([90 -90])
hold on
plot(x, 1-y, 'linewidth', 2)
I get the following figure: matlab figure I get
As you can see, there a lot of white spaces above the line which I would like to be in color as well. Unfortunately, I cannot add any more grid points as calculating the actual value of the points takes a lot of time (unlike the example above).
Is there a way to have matlab draw colors in those white spaces as well?
Thanks!
You can try to use patch function to create filled polygon.
See http://www.mathworks.com/help/matlab/ref/patch.html
Try the following code:
vert = [0 1;1 1;1 0]; % x and y vertex coordinates
fac = [1 2 3]; % vertices to connect to make triangle
fvc = [1 0 0; 1 1 1; 0 0 1];
patch('Faces',fac,'Vertices',vert,'FaceVertexCData',fvc,'FaceColor','interp');
Result is close:
I was managed to get closer to the desired figure:
close all
x = linspace(0, 1, 10);
y = linspace(0, 1, 10);
%colorbar
xlim([x(1) x(end)])
%Fill rectangle.
vert = [0 0; 1 0; 1 1; 0 1]; % x and y vertex coordinates
fac = [1 2 3 4]; % vertices to connect to make squares
%patch('Faces',fac,'Vertices',vert,'FaceColor','red')
fvc = [1 0 0; 0.6 0.7 1; 0.6 0.7 1; 1 0 0]; %Color of vertices (selected to be close to example image).
patch('Faces',fac,'Vertices',vert,'FaceVertexCData',fvc,'FaceColor','interp')
hold on
%Fill lower triangle with white color.
vert = [0 0;0 1;1 0]; % x and y vertex coordinates
fac = [1 2 3]; % vertices to connect to make triangle
fvc = [1 1 1; 1, 1, 1; 1, 1, 1]; %White color
patch('Faces',fac,'Vertices',vert,'FaceVertexCData',fvc,'FaceColor','interp');
plot(x, 1-y, 'linewidth', 2)
set(gca,'Xtick',[],'Ytick',[]); %Remove tick marks
Result:
Thank you Rotem! I wasn't aware of the patch function and indeed it solved the issue!
The colors on the actual figure I'm trying to achieve are not linear, so I just used patch for all the empty triangles. Here is the adjusted code I use for the simple example (again, this is just a bit more general just to be able to have non linear colors in the area above the curve):
x = linspace(0, 1, 10);
y = linspace(0, 1, 10);
z = linspace(0, 1, 10);
z = repmat(z, 10, 1)+0.1;
z = flipud(triu(z));
z(z==0) = nan;
z = z-0.1;
hold off
surf(x, y, z, 'linestyle', 'none')
colormap([linspace(0.39, 1, 20)',linspace(0.58, 0.25, 20)', linspace(0.93, 0.25, 20)']);
colorbar
xlim([x(1) x(end)])
shading interp
view([90 -90])
hold on
patch_cor_y = kron((length(y):-1:1)', ones(3, 1));
patch_cor_x = kron((1:length(x))', ones(3, 1));
patch_cor = [y(patch_cor_y(2:end-2))', x(patch_cor_x(3:end-1))'];
patch_path = reshape(1:length(patch_cor),3, length(patch_cor)/3)';
patch_col = z(sub2ind(size(z), patch_cor_x(3:end-1), patch_cor_y(2:end-2)));
patch('Faces',patch_path,'Vertices',patch_cor,'FaceVertexCData',patch_col,'FaceColor','interp', 'EdgeColor', 'none');
plot(x, 1-y, 'linewidth', 2)
The figure achieved: figure

3D binary matrix/image from a surface mesh in Matlab

How could I create a 3D binary matrix/image from a surface mesh in Matlab?
For instance, when I create ellipsoid using:
[x, y, z] = ellipsoid(0,0,0,5.9,3.25,3.25,30);
X, Y and X are all 2D matrix with size 31 x 31.
Edited based on suggestion of #Magla:
function Create_Mask_Basedon_Ellapsoid3()
close all
SurroundingVol = [50, 50, 20];
%DATA
[MatX,MatY,MatZ] = meshgrid(-24:1:25, -24:1:25, -9:1:10);
[mask1, x, y, z] = DrawEllipsoid([0, -10, 0], [6, 3, 3], MatX,MatY,MatZ);
[mask2, x2, y2, z2] = DrawEllipsoid([15, 14, 6], [6, 3, 3], MatX,MatY,MatZ);
mask = mask1 + mask2;
%Surface PLOT
figure('Color', 'w');
subplot(1,2,1);
%help: Ideally I would like to generate surf plot directly from combined mask= mask1 + mask2;
s = surf(x,y,z); hold on;
s2 = surf(x2,y2,z2); hold off;
title('SURFACE', 'FontSize', 16);
view(-78,22)
subplot(1,2,2);
xslice = median(MatX(:));
yslice = median(MatY(:));
zslice = median(MatZ(:));
%help: Also how do I decide correct "slice" and angles to 3D visualization.
h = slice(MatX, MatY, MatZ, double(mask), xslice, yslice, zslice)
title('BINARY MASK - SLICE VOLUME', 'FontSize', 16);
set(h, 'EdgeColor','none');
view(-78, 22)
%az = 0; el = 90;
%view(az, el);
end
function [mask, Ellipsoid_x, Ellipsoid_y, Ellipsoid_z] = DrawEllipsoid(CenterEllipsoid, SizeEllipsoid, MatX, MatY, MatZ)
[Ellipsoid_x, Ellipsoid_y, Ellipsoid_z] = ellipsoid(CenterEllipsoid(1), CenterEllipsoid(2), CenterEllipsoid(3), SizeEllipsoid(1)/2 , SizeEllipsoid(2)/2 , SizeEllipsoid(3)/2 ,30);
v = [Ellipsoid_x(:), Ellipsoid_y(:), Ellipsoid_z(:)]; %3D points
%v = [x(:), y(:), z(:)]; %3D points
tri = DelaunayTri(v); %triangulation
SI = pointLocation(tri,MatX(:),MatY(:),MatZ(:)); %index of simplex (returns NaN for all points outside the convex hull)
mask = ~isnan(SI); %binary
mask = reshape(mask,size(MatX)); %reshape the mask
end
There you go:
%// Points you want to test. Define as you need. This example uses a grid of 1e6
%// points on a cube of sides [-10,10]:
[x y z] = meshgrid(linspace(-10,10,100));
x = x(:);
y = y(:);
z = z(:); %// linearize
%// Ellipsoid data
center = [0 0 0]; %// center
semiaxes = [5 4 3]; %// semiaxes
%// Actual computation:
inner = (x-center(1)).^2/semiaxes(1).^2 ...
+ (y-center(2)).^2/semiaxes(2).^2 ...
+ (z-center(3)).^2/semiaxes(3).^2 <= 1;
For the n-th point of the grid, whose coordinates are x(n), y(n), z(n), inner(n) is 1 if the point lies in the interior of the ellipsoid and 0 otherwise.
For example: draw the interior points:
plot3(x(inner), y(inner), z(inner), '.' , 'markersize', .5)
Here is a method for creating a binary mask from an ellipsoid. It creates a corresponding volume and sets to NaN the points outside the ellipsoid (ones inside).
It doesn't take into consideration the formula of the ellipsoid, but uses a convex hull. Actually, it works for any volume that can be correctly described by a 3D convex hull. Here, the convexhulln step is bypassed since the ellipsoid is already a convex hull.
All credits go to Converting convex hull to binary mask
The following plot
is produced by
%DATA
[x, y, z] = ellipsoid(0,0,0,5.9,3.25,3.25,30);
%METHOD
v = [x(:), y(:), z(:)]; %3D points
[X,Y,Z] = meshgrid(min(v(:)):0.1:max(v(:))); %volume mesh
tri = DelaunayTri(v); %triangulation
SI = pointLocation(tri,X(:),Y(:),Z(:)); %index of simplex (returns NaN for all points outside the convex hull)
mask = ~isnan(SI); %binary
mask = reshape(mask,size(X)); %reshape the mask
%PLOT
figure('Color', 'w');
subplot(1,2,1);
s = surf(x,y,z);
title('SURFACE', 'FontSize', 16);
view(-78,22)
subplot(1,2,2);
xslice = median(X(:));
yslice = median(Y(:));
zslice = median(Z(:));
h = slice(X, Y, Z, double(mask), xslice, yslice, zslice)
title('BINARY MASK - SLICE VOLUME', 'FontSize', 16);
set(h, 'EdgeColor','none');
view(-78,22)
Several ellipsoids
If you have more than one ellipsoid, one may use this masking method for each of them, and then combine the resulting masks with &.
Choice of slices and angle
"Correct" is a matter of personal choice. You can either
create the unrotated mask and rotate it after (Rotate a 3D array in matlab).
create a mask on already rotated ellipsoid.
create a mask on a slightly rotated ellipsoid (that gives you the choice of a "correct" slicing), and rotate it further to its final position.