Displaying surf actual size? - matlab

Is there a way to display surf in its actual size and aspect ratio? I've been looking in the web but couldn't find anything which worked. I'm also quite new to MATLAB.
Here is my code:
rpos1 = 0; % image row vector pos counter
rpos2 = 0; % existing image vector pos counter
rpos3 = 0; % avg vector pos counter
prompt = {'Image location:','Lowest image #:','Highest image #:','Row of interest:','Background noise reduction:'};
dlg_title = 'Input';
num_lines = 1;
def = {'C:\Users\Moz\Desktop\Hyperspecdata\images','300','390','700','100'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
directory = (answer{1});
x1 = str2num(answer{2});
x2 = x1;
y1 = str2num(answer{3});
y2 = y1-1;
z = str2num(answer{4});
v = str2num(answer{5});
finalslice = zeros(1,1312); % create matrix (imagecount x 1312)
%INSERT SLICES WITH 1 GAP%
for k = x1 : y1
baseFileName = sprintf('image0000000%03d.pgm',k);
fullFileName = fullfile(directory, baseFileName); %fullfile(folder, baseFileName);
A = imread(fullFileName);
A = floor(A./16); % transform back to 12 bit
B = A-v; % remove background noise
rpos1 = rpos1+1; % jump to next row
thisline = B(z,:); % desired row in images
finalslice(rpos1,:) = thisline; % add row vector
rpos1 = rpos1+1; % jump to next row
emptyline = zeros(1,1312); % create empty row vector
finalslice(rpos1,:) = emptyline; % insert empty row vector
end
%INSERT AVERAGES INTO GAPS%
for k = x2 : y2
rpos2 = rpos2+1; % find first existing vector
line1 = finalslice(rpos2,:);
rpos2 = rpos2+2; % find second existing vector
line2 = finalslice(rpos2,:);
avgline1 = (line1 + line2)/2; % average both
rpos3 = rpos3+2;
finalslice(rpos3,:) = avgline1; % insert average vector
rpos2 = rpos2-1; % jump back to second existing vector
end
figure(1)
h = surf(finalslice,'EdgeColor','none','LineStyle','none','FaceLighting','phong');
colormap('jet');
view(2)
I'm loading a bunch of images and taking slices at a specific points and stitching them together. The output doesn't display the actual size and aspect ratio.

SOLVED:
Added daspect()
o = max(max(finalslice));
[m n] = size(finalslice);
figure(1) h = surf(finalslice,'EdgeColor','none','LineStyle','none','FaceLighting','phong'); colormap('jet');
view(2)
daspect([m n o]);

Related

How to cut part of the data out of a plot in Matlab

I just wanted to cut part of my data out in MATLAB, for example:
If I click on two points on the axis, it will cut the elements after the I click on with respect to the x-axis. I will post my code and a pic for further details
Thank you in advance
load sample.mat
X = sample.current;
X1 = sample.voltage;
Ts = 0.01;
Fs = 1/Ts;
Fm = Fs/2;
Fc = 2;
N =10;
d = fdesign.lowpass('N,Fc',N,Fc,Fs);
designmethods(d);
Hd = design(d);
%fvtool(Hd)
%X is a variable form csv
%X1 is a variable from csv
output = filter(Hd,X);
output1 = filter(Hd,X1);
figure;
plot(X,X1,'-g');
hold on
plot(output, output1,'r');
hold off
legend('raw signal','filtered signal')
grid on
x = output, output1;
y = output1;
figure
subplot(2,1,1)
plot(x,y,'r');
title('Original plot');
uiwait(msgbox('Select an x-value from which to crop','modal'));
[x_user ~] = ginput(1); % Let the user select an x-value from which to crop.
x(x>x_user) = [];
subplot(2,1,2);
plot(x,y,'r');
title('New plot with cropped values');
xlim([min(x(:)) max(x(:))]);
enter image description here
*Posting this as an answer to format code.
If its only one graphic you can just select the points that you want to delete using the "Brush/Select Data" (icon of a brush with a red square located at the menubar of the figure) selecting the data you want to be gone and then pressing the delete key.
If you want to do it with code you can try to find the index of the point where the signal starts to decrease over the X using something like:
% Find the index where X starts to decrease
maxIndex = find(data.x == max(data.x));
% In case of multiple indexs, ensure we get the first one
maxIndex = maxIndex(1);
% Copy data to new vector
saveData.x = data.x(1:maxIndex);
saveData.y = data.y(1:maxIndex);
If you want to use the users' click position you can use find to locate the index of the first element after the click:
% Get the coords of the first click
userFirstClick = ginput(1);
% Get the X component of the coords
xCoordInit = userFirstClick(1);
% Locate the index of the first element that is greater than
% the xCoord
firstXIndex = find(data.x >= xCoordInit);
% In case of multiple indexs, ensure we get the first one
firstXIndex = firstXIndex(1);
% Do the same to get the final index
userSecondClick = ginput(1);
xCoordFinal = userSecondClick(1);
finalXIndex = find(data.x > xCoordFinal);
finalXIndex = finalXIndex(1)-1;
% -1 because data.x(finalXIndex) is already greater than xCoordFinal
% Copy data to the new vector
saveData.x = data.x(firstXIndex:finalXIndex);
saveData.y = data.y(firstXIndex:finalXIndex);
Then just plot saveData.
Edit
There was a typo on my previous code, here you have a fully functional example where you just need to click over the two points where you want to crop.
function cropSine()
% create a period of a Sine to initialize our data
data.x = -pi*3:0.01:pi*3;
data.y = sin(data.x);
% we make it loop back just as in your picture
data.x = [data.x,data.x(end:-1:1)];
data.y = [data.y, -data.y*0.5+5];
% create a figure to show the signal we have just created
figure
% create the axes where the data will be displayed
mainAx = axes();
% Draw our fancy sine!
plot(data.x, data.y, 'b-', 'Parent', mainAx);
% Request the initial position to crop
userFirstClick = ginput(1);
% Get the index of the nearest point
initIndex = getNearest(userFirstClick, data);
% Do the same to get the final index
userSecondClick = ginput(1);
% Get the index of the nearest point
finalIndex = getNearest(userSecondClick, data);
% check if its a valid point
if isempty(initIndex) || isempty(finalIndex)
disp('No points in data vector!');
return;
end
% Ensure that final index is greater than first index
if initIndex > finalIndex
tempVal = initIndex;
initIndex = finalIndex;
finalIndex = tempVal;
end
% Copy the data that we want to save into a new variable
saveData.x = data.x(initIndex:finalIndex);
saveData.y = data.y(initIndex:finalIndex);
% Plot the cropped data in red!
hold(mainAx, 'on');
plot(saveData.x, saveData.y, 'r-', 'Parent', mainAx);
hold(mainAx, 'off');
end
function nearestIndex = getNearest(clickPos, vector)
nearestIndex = [];
numPoints = length(vector.x);
if numPoints == 0
return;
end
nearestIndex = 1;
minDist = calcDist(vector.x(1), vector.y(1), clickPos(1), clickPos(2));
for pointID = 1:numPoints
dist = calcDist(vector.x(pointID), vector.y(pointID), clickPos(1), clickPos(2));
if dist < minDist
nearestIndex = pointID;
minDist = dist;
end
end
end
function dist = calcDist(p1x, p1y, p2x, p2y)
dist = sqrt(power(p1x-p2x,2)+power(p1y-p2y,2));
end

Unexpected result when calculating mean curvature in MatLab

I am running simulations of a protein/membrane system, and want to quantify the degree of membrane deformation. I have averaged the membrane surface on a grid during the simulation, which results in a text file with three columns, containing the x, y, and z points of the membrane. I then convert this information to a mesh surface in matlab, which I then use to calculate the gaussian and/or mean curvature. The problem is, I'm getting similar values at the very beginning of the simulation, when the surface (membrane) is very flat, and at the end, when it is completely deformed. Unless I'm misunderstanding what curvature is, this is not correct and I believe I am doing something wrong in the matlab portion of this process. Here's the script where I loop over many frames (each of which is a different file containing x,y,z coordinates of the averaged membrane) and convert it to a mesh:
https://pastebin.com/reqWAz01
for i = 0:37
file = strcat('cg-topmem_pos-', num2str(i), '.out');
A = load(file);
x = A(:,1);
y = A(:,2);
z = A(:,3);
xv = linspace(min(x), max(x), 20);
yv = linspace(min(y), max(y), 20);
[X,Y] = meshgrid(xv, yv);
Z = griddata(x,y,z,X,Y);
[K,H,Pmax,Pmin] = surfature(X,Y,Z);
M = max(max(H))
if i == 0
fileID = fopen('Average2-NoTMHS-5nmns.txt', 'a');
fprintf(fileID, '%f %f\n',M);
fclose(fileID);
else
fileID = fopen('Average2-NoTMHS-5nmns.txt', 'a');
fprintf(fileID, '\n%f %f\n',M);
fclose(fileID);
end
end
Then using the following calculates curvature:
https://pastebin.com/5D21PdBQ
function [K,H,Pmax,Pmin] = surfature(X,Y,Z),
% SURFATURE - COMPUTE GAUSSIAN AND MEAN CURVATURES OF A SURFACE
% [K,H] = SURFATURE(X,Y,Z), WHERE X,Y,Z ARE 2D ARRAYS OF POINTS ON THE
% SURFACE. K AND H ARE THE GAUSSIAN AND MEAN CURVATURES, RESPECTIVELY.
% SURFATURE RETURNS 2 ADDITIONAL ARGUMENTS,
% [K,H,Pmax,Pmin] = SURFATURE(...), WHERE Pmax AND Pmin ARE THE MINIMUM
% AND MAXIMUM CURVATURES AT EACH POINT, RESPECTIVELY.
% First Derivatives
[Xu,Xv] = gradient(X);
[Yu,Yv] = gradient(Y);
[Zu,Zv] = gradient(Z);
% Second Derivatives
[Xuu,Xuv] = gradient(Xu);
[Yuu,Yuv] = gradient(Yu);
[Zuu,Zuv] = gradient(Zu);
[Xuv,Xvv] = gradient(Xv);
[Yuv,Yvv] = gradient(Yv);
[Zuv,Zvv] = gradient(Zv);
% Reshape 2D Arrays into Vectors
Xu = Xu(:); Yu = Yu(:); Zu = Zu(:);
Xv = Xv(:); Yv = Yv(:); Zv = Zv(:);
Xuu = Xuu(:); Yuu = Yuu(:); Zuu = Zuu(:);
Xuv = Xuv(:); Yuv = Yuv(:); Zuv = Zuv(:);
Xvv = Xvv(:); Yvv = Yvv(:); Zvv = Zvv(:);
Xu = [Xu Yu Zu];
Xv = [Xv Yv Zv];
Xuu = [Xuu Yuu Zuu];
Xuv = [Xuv Yuv Zuv];
Xvv = [Xvv Yvv Zvv];
% First fundamental Coeffecients of the surface (E,F,G)
E = dot(Xu,Xu,2);
F = dot(Xu,Xv,2);
G = dot(Xv,Xv,2);
m = cross(Xu,Xv,2);
p = sqrt(dot(m,m,2));
n = m./[p p p];
% Second fundamental Coeffecients of the surface (L,M,N)
L = dot(Xuu,n,2);
M = dot(Xuv,n,2);
N = dot(Xvv,n,2);
[s,t] = size(Z);
% Gaussian Curvature
K = (L.*N - M.^2)./(E.*G - F.^2);
K = reshape(K,s,t);
% Mean Curvature
H = (E.*N + G.*L - 2.*F.*M)./(2*(E.*G - F.^2));
H = reshape(H,s,t);
% Principal Curvatures
Pmax = H + sqrt(H.^2 - K);
Pmin = H - sqrt(H.^2 - K);
Any help would be greatly appreciated. I'm afraid that there is some issue between how the mesh is created and how curvature is calculated, but I am not matlab literate and could use some help. Thanks very much.

selective direction for voronoi diagram in matlab

How can I create a voronoi diagram on these squares in MATLAB, as the voronoi does not enter the yellow square? Alternatively, just some lines of it enters the yellow ones.
It is possible to put constrains on Delaunay triangulation, and add more checks afterwards. maybe it can help you:
close all
% generate random rectangels [x,y,w,h] format
n = 8;
w = 0.15;
h = 0.05;
rects = [rand(n,2),w*ones(n,1),h*ones(n,1)];
% convert to [xmin ymin xmax ymax] format
boxes = [rects(:,1:2), rects(:,1:2) + rects(:,3:4)];
% convert to one single polygon (with missing vertexes)
X = boxes(:,[1 3 3 1 1]);
Y = boxes(:,[2 2 4 4 2]);
X(:,end+1) = nan;
Y(:,end+1) = nan;
X = X';X = X(:);
Y = Y';Y = Y(:);
% polygon vertxes without the Nans
XX = X;XX(6:6:end) = [];
YY = Y;YY(6:6:end) = [];
% intersections between rectangles
[xi,yi] = polyxpoly(X,Y,X,Y,'unique');
% remove intersections found inside rectangles
IN = any(bsxfun(#gt,xi',boxes(:,1)) & bsxfun(#lt,xi',boxes(:,3)) & ...
bsxfun(#gt,yi',boxes(:,2)) & bsxfun(#lt,yi',boxes(:,4)),1);
xi(IN) = [];
yi(IN) = [];
% find vertex pairs of the rectangles
xeq = bsxfun(#eq,xi,xi');
yeq = bsxfun(#eq,yi,yi');
xyeq = triu(xeq | yeq,1);
[idx1,idx2] = find(xyeq);
% generate constrains for the triangulation
C = [idx1,idx2];
% triangulate
DT = delaunayTriangulation([xi,yi],C);
% get connections (triangles) list
TRI = DT.ConnectivityList;
remIdx = false(size(TRI,1),1);
% check condition to remove triangles
for ii = 1:size(TRI,1)
% current triangle coordinates
xx = xi(TRI(ii,[1:3 1]));
yy = yi(TRI(ii,[1:3 1]));
% find if triangle inside rectangle
BETx = bsxfun(#ge,xx(1:3)',boxes(:,1)) & bsxfun(#le,xx(1:3)',boxes(:,3));
BETy = bsxfun(#ge,yy(1:3)',boxes(:,2)) & bsxfun(#le,yy(1:3)',boxes(:,4));
IN = BETx & BETy;
if any(all(IN,2))
remIdx(ii) = true;
continue;
end
% find if triangle crosses rectangle
[xxi,yyi] = polyxpoly(xx,yy,X,Y,'unique');
notAllowedVertex = ~ismember([xxi yyi],[xi,yi],'rows');
if any(notAllowedVertex)
remIdx(ii) = true;
continue;
end
end
% remove unwanted triangles
TRI(remIdx,:) = [];
% plot
figure;
hold on
plot(X,Y,'g','LineWidth',2)
triplot(TRI,xi,yi)
plot(xi,yi,'or')
axis equal

how to extract each characters from a image?with using this code

i have to extract each characters from a image here i am uploading the code it is segmenting the horizontal lines but not able to segment the each characters along with the horizontal line segmentation loop. some1 please help to correct the code
this is the previous code:
%%horizontal histogram
H = sum(rotatedImage, 2);
darkPixels = H < 100; % Threshold
% label
[labeledRegions, numberOfRegions] = bwlabel(darkPixels);
fprintf('Number of regions = %d\n', numberOfRegions);
% Find centroids
measurements = regionprops(labeledRegions, 'Centroid');
% Get them into an array
allCentroids = [measurements.Centroid];
xCentroids = int32(allCentroids(1:2:end));
yCentroids = int32(allCentroids(2:2:end));
% Now you can just crop out some line of text you're interested in, into a separate image:
hold off;
plotLocation = 8;
for band = 1 : numberOfRegions-1
row1 = yCentroids(band);
row2 = yCentroids(band+1);
thisLine = rotatedImage(row1 : row2, :);
subplot(7, 2, plotLocation)
imshow(thisLine, [])
%% Let's compute and display the histogram.
verticalProjection = sum(thisLine, 2);
set(gcf, 'NumberTitle', 'Off')
t = verticalProjection;
t(t==0) = inf;
mayukh=min(t);
% 0 where there is background, 1 where there are letters
letterLocations = verticalProjection > mayukh;
% Find Rising and falling edges
d = diff(letterLocations);
startingRows = find(d>0);
endingRows = find(d<0);
% Extract each region
y=1;
for k = 1 : length(startingRows)
% Get sub image of just one character...
subImage = thisLine(:, startingRows(k):endingRows(k));
[L,num] = bwlabel(subImage);
for z= 1 : num
bw= ismember( L, z);
% Construct filename for this particular image.
baseFileName = sprintf('templates %d.png', y);
y=y+1;
% Prepend the folder to make the full file name.
fullFileName = fullfile('C:\Users\Omm\Downloads\', baseFileName);
% Do the write to disk.
imwrite(bw, fullFileName);
pause(2);
imshow(bw);
pause(5)
end;
y=y+2;
end;
plotLocation = plotLocation + 2;
end
but not segmenting the whole lines
Why don't you simply use regionprops with 'Image' property?
img = imread('http://i.stack.imgur.com/zpYa5.png'); %// read the image
bw = img(:,:,1) > 128; %// conver to mask
Use some minor morphological operations to handle spurious pixels
dbw = imdilate(bw, ones(3));
lb = bwlabel(dbw).*bw; %// label each character as a connected component
Now you can use regionprops to get each image
st = regionprops( lb, 'Image' );
Visualize the results
figure;
for ii=1:numel(st),
subplot(4,5,ii);
imshow(st(ii).Image,'border','tight');
title(num2str(ii));
end

Create a plane of points from a row of points

I am trying to create a "plane", so to speak, of points in MATLAB from a set of initial points. I have so far been able to create only one row of points, with the algorithm shown below:
% Generate molecular orientation and position
a = 4.309; % lattice constant in angstroms
l = 10; % number of lattices desired
placeHolder = [0 0 0 ; a/2 a/2 0; a/2 0 a/2; 0 a/2 a/2]; % centers of molecules
numMol = 4; %input('how many molecules are in the unit cell? \n # molecules = ');
numAtoms = 2; %input('how many atoms per molecule? \n # atoms per molecule = ');
atomPerUC = numMol*numAtoms; % number of atoms per unit cell
dir = zeros(numMol,3); % array for orientations
atomPosition = zeros(numAtoms*l^3,3,numMol); % array for positions of atoms
theta = zeros(numMol,1); % array for theta values
phi = zeros(numMol,1); % array for phi values
b = 1.54; % bond length in angstroms
for kk = 1:numMol % generate unit cell
% disp(['What is the molecular orientation for molecule ',num2str(kk),' ?']);
% dir(kk,1) = input('u = '); % ask for user input for molecular orientations
% dir(kk,2) = input('v = ');
% dir(kk,3) = input('w = ');
dir = [1,1,1;-1,1,1;-1,-1,1;1,-1,1];
u = dir(kk,1); % set variables for theta, phi computation
v = dir(kk,2);
w = dir(kk,3);
theta(kk) = w/sqrt(u^2+v^2+w^2); % theta value for molecule k
if v<0 % phi value for molecule k
phi(kk) = 2*pi - acos(abs(v)/sqrt(u^2+v^2+w^2));
else if v>0
phi(kk) = acos(u/sqrt(u^2+v^2+w^2));
end
end
theta = theta(kk); phi = phi(kk); % set variables for theta, phi for x,y,z computation
xp = placeHolder(kk,1); % cooridnates of center of molecule k
yp = placeHolder(kk,2);
zp = placeHolder(kk,3);
x1 = (b/2)*sin(theta)*cos(phi) + xp; % cooridnates for atoms in molecule
x2 = -(b/2)*sin(theta)*cos(phi) + xp;
y1 = (b/2)*sin(theta)*sin(phi) + yp;
y2 = -(b/2)*sin(theta)*sin(phi) + yp;
z1 = (b/2)*cos(theta) + zp;
z2 = -(b/2)*cos(theta) + zp;
atomPosition(1,:,kk) = [x1 y1 z1];
atomPosition(2,:,kk) = [x2 y2 z2];
end
for k = 1:numMol
x01 = atomPosition(1,1,k); y01 = atomPosition(1,2,k); z01 = atomPosition(1,3,k);
x02 = atomPosition(2,1,k); y02 = atomPosition(2,2,k); z02 = atomPosition(2,3,k);
for ii = 1:l-1
atomPosition(2*ii+1,:,k) = [(atomPosition(2*ii-1,1,k) + a) y01 z01];
atomPosition(2*ii+2,:,k) = [(atomPosition(2*ii,1,k) + a) y02 z02];
end
end
My problem is that I do not know how to, from here, turn this "row" of points into a "plane" of points. This can be thought of as taking the points that are known on the x-axis, and creating similar rows moving up in the y-direction to create an x-y plane of points.
Any help/suggestions would be appreciated!
Though I do not understand exactly what you are trying to do. In a simple case you can move from a row of points to a plane by adding the extra dimension.
ie.
x=[1,2,3,4,5]
y=x^2
changes to
x=[1,2,3,4,5]
y=[1,2,3,4,5]
[x,y] = meshgrid(x,y)
z=x^2+y^2