creating a loop to save images from contour slice - matlab

I have the following code to plot a slice at any location in a fluid volume.
clc, clear all, close all
format long
%a ddpath('\\ds.leeds.ac.uk\staff\staff6\censsar\Polydisperse'); % <------Change
%% Import data
input = importdata('lci_000210.dat',' ',3);
nx = 96;
ny = 96;
nz = 49;
x = input.data(:,1);
y = input.data(:,2);
z = input.data(:,3);
Lci = input.data(:,4);
L3d = reshape(Lci,[nx,ny,nz]);
x3d = reshape(x,[nx,ny,nz]);
y3d = reshape(y,[nx,ny,nz]);
z3d = reshape(z,[nx,ny,nz]);
contourslice(y3d,x3d,z3d,L3d,[],[],[0.3]);
ax=gca;
ax.Children(1).LineStyle='none';
ax.Children(2).LineStyle='none';
ax.Children(3).LineStyle='none';
view(25,20);
colormap jet
colorbar
What I would like to do is have the contour slice in a loop so that it creates and saves a slice at each z location. I want to hopefully create a movie of the z slice moving from zero and going up the 3d axis.
I have tried something like:
Z=[0 0.1 0.5];
for S = 1:length(Z)
h = figure
contourslice(y3d,x3d,z3d,L3d,[],[],[Z],10);
saveas(h,sprintf('Fig%d.png',S));
end
but this is not working, I am not sure how to define the z axis in the loop, so it creates a slice at each point.
Here is the link to my data, it is a .dat file so it contains the data in 4 columns.

To create a set of slices in a loop you have to modify your code by replacing the last but one parameter in the call to contourslice by specifiybg the i-th element of the array Z.
Since you did not post your input data I've tested the proposed solution on an example data from MatLab contourslice help slightly modified in which
are created nine contour plots in the y-z plane, no plots in the x-z plane, and one plot in the x-y plane by specifying Sx as a vector of nine elements, Sy as an empty vector, and Sz as a scalar (from MatLab help).
Yoy have to adapt the definition of the Sx, Sy and Sz parameters to your needs.
To create a movie you can use the functions:
videowriter to create the video object
open to open the video file
getframe to capture axes or figure as movie frame
close to close and save the video file
As an alternative to the movie, you can create an animated gif by using the function imwrite
% Load input data
[X,Y,Z,V] = flow;
% Define the parameters for the set of slices
Sx = 1:9;
Sy = [];
Sz = [];
cvals = linspace(-8,2,10);
% Open the FIGURE window
figure
% Create the axes and set tehiur properties
axis([0,10,-3,3,-3,3])
hold on
daspect([1,1,1])
campos([0,-20,7])
box on
% Create the movie object
mov=VideoWriter('contour_slice_movie.avi');
% Open the movie file
open(mov);
% Define the number of frames to be captured for each slice
n_frame_x_image=33;
% Loop over the desired number of slices
for i=1:length(Sx)
contourslice(X,Y,Z,V,Sx(i),Sy,Sz,cvals)
% Capture the frames
for j=1:n_frame_x_image
FF=getframe(gcf);
writeVideo(mov,FF);
end
end
% Close the movie file
close(mov);

Related

Get pixel values in RGB images using PixelList in MATLAB

I am trying to get pixel intensity values from regions of interest in RGB images.
I segmented the image and saved the regions of interest (ROI) using regionprops 'PixelList' in MATLAB, as shown below:
In this example I am using "onion.png" image built in MATLAB. (But in reality I have hundreds of images, and each of them have several ROIs hence why I'm saving the ROIs separately.)
%SEGMENTATION PROGRAM:
a=imread('C:\Program Files\MATLAB\MATLAB Production Server\R2015a\toolbox\images\imdata\onion.png');warning('off', 'Images:initSize:adjustingMag');
figure; imshow(a,[]);
nrows = size(a,1);ncols = size(a,2);
zr=ones(nrows,ncols); %matrix of ones
r=a(:,:,1);g=a(:,:,2);b=a(:,:,3); %get RGB values
rr=double(r);gg=double(g);bb=double(b);% convert to double to avoid uint8 sums
bgd=(rr+bb)./(2*gg); %calculation RGB ratio of background
zr1=bgd>1.15; %matrix containing background as 1 and ROI as 0
% remake binary image for holes command which requires white object to fill % (this step is not relevant for this example, but it is for my data)
zr2=zr1<0.5;
zr3=imfill(zr2, 'holes');
figure;imshow(zr3); pause;
roi=regionprops(zr3,'Centroid','PixelList','Area');
ar=[roi.Area];
% find sort order , largest first
[as, ia]=sort(ar(1,:),'descend');
for w=1:length(roi); xy(w,:)=roi(w).Centroid;end
% use sort index to put cenrtoid list in same order
xy1=xy(ia,:);
%and pixel id list
for w=1:length(roi)
roi2(w).PixelList=roi(ia(w)).PixelList;
end
%extract centriod positions as two colums
%SAVE PIXEL LIST FOR EACH ROI IN A SEPARATE FILE
for ww=1:w;
k=roi2(ww).PixelList;
save('onion_PL','k');
end
How do I use this pixel list to get the intensity values in the original image? More specifically, I need to get the ratio of pixels in Green channel over Red ("grr=rdivide(gg,rr);"), but only in the region of interest labeled with PixelList. Here's my code so far:
%PL is the PixelList output we got above.
a=imread('C:\Program Files\MATLAB\MATLAB Production Server\R2015a\toolbox\images\imdata\onion.png');warning('off', 'Images:initSize:adjustingMag');
PL=dir(['*PL.mat']); %load file PixelList files. "dir" is a variable with directory path containing the pixelist files. In this example, we saved "onion_PL.mat"
for m=1:length(PL);
load(PL(m).name);
ex=[]; %empty matrix to hold the extracted values
for mm=1:length(k);
%INSERT ANSWER HERE
end
This next bit is wrong because it's based on the entire image ("a"), but it contains the calculations that I would like to perform in the ROIs
figure; imshow(a,[]);
pause;
nrows = size(a,1);ncols = size(a,2);
zr=ones(nrows,ncols); %matrix of ones
r=a(:,:,1);g=a(:,:,2);b=a(:,:,3); %get RGB values
rr=double(r);gg=double(g);bb=double(b);% convert to double to avoid uint8 sums
grr=rdivide(gg,rr);
I am brand new to MATLAB, so my code is not the greatest... Any suggestions will be greatly appreciated. Thank you in advance!
The loop you are looking for seems simple:
grr = zeros(nrows, ncols); % Initialize grr with zeros.
for mm = 1:length(k)
x = k(mm, 1); % Get the X (column) coordinate.
y = k(mm, 2); % Get the Y (row) coordinate.
grr(y, x) = gg(y, x) / rr(y, x);
end
A more efficient solution is using sub2ind for converting the x,y coordinates to linear indices:
% Convert k to linear indices.
kInd = sub2ind([nrows, ncols], k(:,2), k(:,1));
% Update only the indices in the PixelList.
grr(kInd) = rdivide(gg(kInd), rr(kInd));
In your given code sample there are 5 PixelLists.
I don't know how do you want to "arrange" the result.
In my code sample, I am saving the 5 results to 5 mat files.
Here is an executable code sample:
close all
%SEGMENTATION PROGRAM:
a=imread('onion.png');warning('off', 'Images:initSize:adjustingMag');
figure; imshow(a,[]);
nrows = size(a,1);ncols = size(a,2);
zr=ones(nrows,ncols); %matrix of ones
r=a(:,:,1);g=a(:,:,2);b=a(:,:,3); %get RGB values
rr=double(r);gg=double(g);bb=double(b);% convert to double to avoid uint8 sums
bgd=(rr+bb)./(2*gg); %calculation RGB ratio of background
zr1=bgd>1.15; %matrix containing background as 1 and ROI as 0
% remake binary image for holes command which requires white object to fill % (this step is not relevant for this example, but it is for my data)
zr2=zr1<0.5;
zr3=imfill(zr2, 'holes');
figure;imshow(zr3); %pause;
roi=regionprops(zr3,'Centroid','PixelList','Area');
ar=[roi.Area];
% find sort order , largest first
[as, ia]=sort(ar(1,:),'descend');
for w=1:length(roi); xy(w,:)=roi(w).Centroid;end
% use sort index to put cenrtoid list in same order
xy1=xy(ia,:);
%and pixel id list
for w=1:length(roi)
roi2(w).PixelList=roi(ia(w)).PixelList;
end
%extract centroid positions as two columns
%SAVE PIXEL LIST FOR EACH ROI IN A SEPARATE FILE
for ww=1:w
k=roi2(ww).PixelList;
%save('onion_PL', 'k');
save(['onion', num2str(ww), '_PL'], 'k'); % Store in multiple files - onion1_PL.mat, onion2_PL.mat, ... onion5_PL.mat
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear % Use clear for testing - the variables are going to be read from the mat file.
%PL is the PixelList output we got above.
a=imread('onion.png');warning('off', 'Images:initSize:adjustingMag');
nrows = size(a,1);ncols = size(a,2);
zr=ones(nrows,ncols); %matrix of ones
r=a(:,:,1);g=a(:,:,2);b=a(:,:,3); %get RGB values
rr=double(r);gg=double(g);bb=double(b);% convert to double to avoid uint8 sums
grr=rdivide(gg,rr);
PL=dir('*PL.mat'); %load file PixelList files. "dir" is a variable with directory path containing the pixelist files. In this example, we saved "onion_PL.mat"
for m = 1:length(PL)
load(PL(m).name);
ex=[]; %empty matrix to hold the extracted values
%for mm=1:length(k)
%INSERT ANSWER HERE
grr = zeros(nrows, ncols); % Initialize grr with zeros.
for mm = 1:length(k)
x = k(mm, 1); % Get the X (column) coordinate.
y = k(mm, 2); % Get the Y (row) coordinate.
grr(y, x) = gg(y, x) / rr(y, x);
end
% Instead of using a loop, it's more efficient to use sub2ind
if false
% Convert k to linear indices.
kInd = sub2ind([nrows, ncols], k(:,2), k(:,1));
% Update only the indices in the PixelList.
grr(kInd) = rdivide(gg(kInd), rr(kInd));
end
figure;imshow(grr);title(['grr of m=', num2str(m)]) % Show grr for testing.
save(['grr', num2str(m)], 'grr'); % Save grr for testing.
imwrite(imadjust(grr, stretchlim(grr)), ['grr', num2str(m), '.png']); % Store grr as image for testing
end
First two grr matrices as images (used for testing):
grr1.png:
grr2.png:

Enlarging models in MATLAB

Im trying to create a project in MATLAB where i project a heat map matrix on to a cylinder in MATLAB but i'm bumping in to all kinds of issues.
Im using MATLAB version R2019b(Latest version).
Now my first issue id like to adress is is the modells being absolutely tiny even when i zoom in to the max.
Is there any way to make these models larger or to display them in a separate window ??
Also my second question is the regarding the scaling. As you can see the scale on the Z-axis of the cylinder goes to 512. any way to get a larger more detailed image where i can see each point on that scale?
clear vars
filename =
['/Users/gomer/Documents/Datavisualisering/Projekt/data/day/filenames.txt'];
%This line simply gives us a table of all filenames in this file.
T = readtable(filename);
tsize = size(T);
%extracts the content of the table as a categorical array.
%%
%
% {rownumber,variablenumber}. {100,1} = row 100, variable 1.
%converts the categorical array into a string array.
%joins the string array across the column.
%string(T{100:105,1}); implies from row 100 to row 105 and use variable 1.
%This line simply adds the name of the file at row 100 to the path of the
%file. Hnece we get a full filepath.
filename = strcat('/Users/gomer/Documents/Datavisualisering/Projekt/data/day/', string(T{100,1}));
map100 = getHeatMap(filename);
%%
%
filename = strcat('/Users/gomer/Documents/Datavisualisering/Projekt/data/day/', string(T{1000,1}));
map1000 = getHeatMap(filename);
%creates a image
k=imshow(map100);
%creates a colormap.
%gca returns the current axes (or standalone visualization) in the current figure.
%hence the command just works top down and affects last image displayed.
colormap(gca, 'jet');
k=imshow(map1000);
colormap(gca, "jet");
function heat = getHeatMap(filename)
%Returns a struct with info about the file.
s = dir(filename);
%Opens a file for reading, hence the 'r'.
fin=fopen(filename,'r');
%A = fread(fileID,sizeA,precision)
%reads file data into an array, A, with dimensions, sizeA, and positions the file pointer after the last value read.
%fread populates A in column order.
I=fread(fin,s.bytes,'uint8=>uint8');
%The uint16 function converts a Input array, specified as a scalar, vector, matrix, or multidimensional array.
%Converts the values in to type uint16 and creates a Matrix with the values.
%Looks more like we are just calculating the size of values to be
%deducted from matrix size (no idea why).
w = uint16(I(1))+256*uint16(I(2));
h = uint16(I(3))+256*uint16(I(4));
skip = s.bytes - w*h + 1;
IN = I(skip:1:s.bytes);
%reshape(A,sz) reshapes A using the size vector, sz, to define size(B). For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix.
%sz must contain at least 2 elements, and prod(sz) must be the same as numel(A).
%single(X) converts the values in X to single precision.
Z=single(reshape(IN,w,h));
%Interpolate the values.
%telling the system which points to interpolate in between.
Z=griddedInterpolant(Z');
y_range = linspace(1.0,single(h),360);
x_range = linspace(1.0,single(w),512);
%Used to apecify the query points (points in between which we want
%interpolation) as vectors (this is to get a more continues image).
%specifies the query points as grid vectors.
%Use this syntax to conserve memory when you want to query a large grid of points.
heat = uint8(Z({y_range, x_range}));
end
Thank you
Resizing Figure Window
Copying your script to a .m and running it instead of a live .mlx file will automatically create all the figures in a separate window by default. To adjust the size of the figures the following the position property can be modified. To adjust the scale functions xticks(), yticks() and zticks() can be used. These three scale functions take in an array representing all the line markers along the respective axis/scale.
Test Plot Script:
X_Position = 10;
Y_Position = 10;
Width = 1000;
Height = 500;
%Configuring the figure settings%
figure('Position', [X_Position Y_Position Width Height])
%Test plot (replace with your plot)%
Data = [1 2 3 4 5 6];
plot(Data);
Plotting Heatmaps on a Cylindrical Surfaces
Method 1: Using warp() Function
Haven't delved into which orientation the data should be set as but this is an option to use the warp() function to wrap the heatmap around a cylinder. They're most likely other 3D plotting options if specific points are of interest. The points of the cylinder to be plotted are generated using the cylinder() function which returns the xyz-coordinates of the cylinder's wireframe. The fourth input argument into the warp() function serves and a colormap in this case it is proportional to the heatmap values.
load('HeatMapMatrix.mat');
%Setting up the figure%
clf;
close all;
figure('Position', [10 10 1000 500])
%Creating the cylinder%
Cylinder_Radius = 360;
Cylinder_Height = 512;
[X,Y,Z] = cylinder(Cylinder_Radius,Cylinder_Height-1);
%Warping the heatmap along the cylinder%
subplot(1,2,1); warp(X,Y,Cylinder_Height.*Z,map100');
colormap(gca,'jet');
subplot(1,2,2); warp(X,Y,Cylinder_Height.*Z,map100);
colormap(gca,'jet');
Method 2: Plotting All Points and Using surf() Function:
In this case, the coordinates for a cylinder are generated by first finding the coordinates of the circumference of the cylinder. This is done by using the sin() and cos() relationships:
X-Points = Radius × cos(𝜃)
Y-Points = Radius × sin(𝜃)
This results in the xy-coordinates of the cylinder's circle. These xy-coordinates need to be duplicated using repmat() to be later used for the varying heights. The process can be described best with a diagram as follows:
Four matrices above are created to plot each Heat Data point corresponding to an xyz-coordinate. The x and y coordinates are repeated in every row of matrices X-Points and Y_Points since those are constant for the repeating circles. The columns of the matrix Z-Points are also duplicates of each other since the heights should be constant for each row corresponding to each circle.
load('HeatMapMatrix.mat');
Radius = 20;
Number_Of_Data_Points = 360;
Theta = linspace(0,2*pi,Number_Of_Data_Points);
%The xy values according to radius and number of points%
X_Points = Radius*cos(Theta);
Y_Points = Radius*sin(Theta);
map100 = rot90(map100);
Sample_Range = 255 - 0;
Temperature_Range = 450 - 50;
Multiplier = Temperature_Range/Sample_Range;
map100 = map100.*Multiplier + 50;
Height = 512;
X_Points = repmat(X_Points,Height,1);
Y_Points = repmat(Y_Points,Height,1);
Z_Points = (1:512)';
Z_Points = repmat(Z_Points,1,Number_Of_Data_Points);
clf;
close;
figure('Position', [10 10 800 500])
Offset = 200;
subplot(1,3,1:2); Surface = surf(Y_Points,X_Points,Z_Points,'Cdata',map100);
title("3D Heatmap Plot");
zlabel("Height");
shading interp
colorbar
% direction = [0 1 0];
% rotate(Surface,direction,90)
Maximum_Value = 450;
Minimum_Value = 50;
caxis([Minimum_Value Maximum_Value]);
subplot(1,3,3); imshow(rot90(rot90(map100)));
colormap(gca, 'default');
title("Flat Heatmap Plot");
caxis([Minimum_Value Maximum_Value]);
colorbar;
Ran using MATLAB R2019b

How can I reduce the number of mesh lines shown in a surface plot?

I've found this answer, but I can't complete my work. I wanted to plot more precisely the functions I am studying, without overcoloring my function with black ink... meaning reducing the number of mesh lines. I precise that the functions are complex.
I tried to add to my already existing code the work written at the link above.
This is what I've done:
r = (0:0.35:15)'; % create a matrix of complex inputs
theta = pi*(-2:0.04:2);
z = r*exp(1i*theta);
w = z.^2;
figure('Name','Graphique complexe','units','normalized','outerposition',[0.08 0.1 0.8 0.55]);
s = surf(real(z),imag(z),imag(w),real(w)); % visualize the complex function using surf
s.EdgeColor = 'none';
x=s.XData;
y=s.YData;
z=s.ZData;
x=x(1,:);
y=y(:,1);
% Divide the lengths by the number of lines needed
xnumlines = 10; % 10 lines
ynumlines = 10; % 10 partitions
xspacing = round(length(x)/xnumlines);
yspacing = round(length(y)/ynumlines);
hold on
for i = 1:yspacing:length(y)
Y1 = y(i)*ones(size(x)); % a constant vector
Z1 = z(i,:);
plot3(x,Y1,Z1,'-k');
end
% Plotting lines in the Y-Z plane
for i = 1:xspacing:length(x)
X2 = x(i)*ones(size(y)); % a constant vector
Z2 = z(:,i);
plot3(X2,y,Z2,'-k');
end
hold off
But the problem is that the mesh is still invisible. How to fix this? Where is the problem?
And maybe, instead of drawing a grid, perhaps it is possible to draw circles and radiuses like originally on the graph?
I found an old script of mine where I did more or less what you're looking for. I adapted it to the radial plot you have here.
There are two tricks in this script:
The surface plot contains all the data, but because there is no mesh drawn, it is hard to see the details in this surface (your data is quite smooth, this is particularly true for a more bumpy surface, so I added some noise to the data to show this off). To improve the visibility, we use interpolation for the color, and add a light source.
The mesh drawn is a subsampled version of the original data. Because the original data is radial, the XData and YData properties are not a rectangular grid, and therefore one cannot just take the first row and column of these arrays. Instead, we use the full matrices, but subsample rows for drawing the circles and subsample columns for drawing the radii.
% create a matrix of complex inputs
% (similar to OP, but with more data points)
r = linspace(0,15,101).';
theta = linspace(-pi,pi,101);
z = r * exp(1i*theta);
w = z.^2;
figure, hold on
% visualize the complex function using surf
% (similar to OP, but with a little bit of noise added to Z)
s = surf(real(z),imag(z),imag(w)+5*rand(size(w)),real(w));
s.EdgeColor = 'none';
s.FaceColor = 'interp';
% get data back from figure
x = s.XData;
y = s.YData;
z = s.ZData;
% draw circles -- loop written to make sure the outer circle is drawn
for ii=size(x,1):-10:1
plot3(x(ii,:),y(ii,:),z(ii,:),'k-');
end
% draw radii
for ii=1:5:size(x,2)
plot3(x(:,ii),y(:,ii),z(:,ii),'k-');
end
% set axis properties for better 3D viewing of data
set(gca,'box','on','projection','perspective')
set(gca,'DataAspectRatio',[1,1,40])
view(-10,26)
% add lighting
h = camlight('left');
lighting gouraud
material dull
How about this approach?
[X,Y,Z] = peaks(500) ;
surf(X,Y,Z) ;
shading interp ;
colorbar
hold on
miss = 10 ; % enter the number of lines you want to miss
plot3(X(1:miss:end,1:miss:end),Y(1:miss:end,1:miss:end),Z(1:miss:end,1:miss:end),'k') ;
plot3(X(1:miss:end,1:miss:end)',Y(1:miss:end,1:miss:end)',Z(1:miss:end,1:miss:end)','k') ;

How to draw a line between two coordinates of an image permanently in Matlab? [duplicate]

This question already has answers here:
MATLAB: Drawing a line over a black and white image
(5 answers)
Closed 4 years ago.
I have a set of points that I want to connect sequentially. Suppose the points are (A1,A2,A3,...A9); I want to connect A1 to A2, A2 to A3 and so on and finally connect A9 to A1.
All I need is to know a function that would help me connect A1 to A2, I could do the rest using for loops.
I know connecting two points is a question that has been asked here several times before but I couldn't find the answer I required. Several of the solutions suggest using "plot" and "line" but these functions overlay the results on the image and don't actually make any changes to the original image.
I did try them out and managed to save the resulting figure using the "saveas" and "print" functions but the image doesn't get saved in the proper format and there are a lot of problems using the parameters for these functions. Besides, I don't really want to save the image, it's just an unnecessary overhead I was willing to add if I could get the desired image with the lines.
I've also tried "imline" to draw lines but it seems to be interactive.
This particular question reflects my problem perfectly but when I ran the code snippets given as solutions, all of them gave a set of dots in the resulting image.
I tried the above mentioned codes in the link with this image that I found here.
A dotted line was an output for all three code snippets in the link above.
For example, I ran the first code like this:
I = imread('berries_copy.png');
grayImage=rgb2gray(I);
img =false(size(grayImage,1), size(grayImage,2));
I wrote the above piece of code just to get a black image for the following operations:
x = [500 470]; % x coordinates
y = [300 310]; % y coordinates
nPoints = max(abs(diff(x)), abs(diff(y)))+1; % Number of points in line
rIndex = round(linspace(y(1), y(2), nPoints)); % Row indices
cIndex = round(linspace(x(1), x(2), nPoints)); % Column indices
index = sub2ind(size(img), rIndex, cIndex); % Linear indices
img(index) = 255; % Set the line points to white
imshow(img); % Display the image
This is the resulting image for the above code as well as the other two, which as you can see, is just a few points on a black background which isn't the desired output.
I changed the code and used the "plot" function for the same to get this output which is what I want. Is there anyway I can change the dotted output into a solid line?
Or if could anyone suggest a simple function or a method that would draw a line from A1 to A2 and would actually make a change in the input image, I'd be grateful. (I really hope this is just me being a novice rather than Matlab not having a simple function to draw a line in an image.)
P.S. I don't have the Computer Vision toolbox and if possible, I'd like to find a solution that doesn't involve it.
Your first problem is that you are creating a blank image the same size as the image you load with this line:
img =false(size(grayImage,1), size(grayImage,2));
When you add the line to it, you get a black image with a white line on it, as expected.
Your second problem is that you are trying to apply a solution for grayscale intensity images to an RGB (Truecolor) image, which requires you to modify the data at the given indices for all three color planes (red, green, and blue). Here's how you can modify the grayscale solution from my other answer:
img = imread('berries_copy.png'); % Load image
[R, C, D] = size(img); % Get dimension sizes, D should be 3
x = [500 470]; % x coordinates
y = [300 310]; % y coordinates
nPoints = max(abs(diff(x)), abs(diff(y)))+1; % Number of points in line
rIndex = round(linspace(y(1), y(2), nPoints)); % Row indices
cIndex = round(linspace(x(1), x(2), nPoints)); % Column indices
index = sub2ind([R C], rIndex, cIndex); % Linear indices
img(index) = 255; % Modify red plane
img(index+R*C) = 255; % Modify green plane
img(index+2*R*C) = 255; % Modify blue plane
imshow(img); % Display image
imwrite(img, 'berries_line.png'); % Save image, if desired
And the resulting image (note the white line above the berry in the bottom right corner):
You can use the Bresenham Algorithm. Of course it has been implemented and you can find it here: Bresenham optimized for Matlab. This algorithm selects the pixels approximating a line.
A simple example, using your variable name could be:
I = rgb2gray(imread('peppers.png'));
A1 = [1 1];
A2 = [40 40];
[x y] = bresenham(A1(1),A1(2),A2(1),A2(2));
ind = sub2ind(size(I),x,y);
I(ind) = 255;
imshow(I)
You can use imshow to display a image and then use plot to plot lines and save the figure. Check the below code:
I = imread('peppers.png') ;
imshow(I)
hold on
[m,n,p] = size(I) ;
%% Get random points A1, A2,..A10
N = 9 ;
x = (n-1)*rand(1,N)+1 ;
y = (m-1)*rand(1,N)+1 ;
P = [x; y]; % coordinates / points
c = mean(P,2); % mean/ central point
d = P-c ; % vectors connecting the central point and the given points
th = atan2(d(2,:),d(1,:)); % angle above x axis
[th, idx] = sort(th); % sorting the angles
P = P(:,idx); % sorting the given points
P = [P P(:,1)]; % add the first at the end to close the polygon
plot( P(1,:), P(2,:), 'k');
saveas(gcf,'image.png')

Getting video from image sequence of figures with subplots in MATLAB

I have a sequence of MATLAB figures which I want to convert to a video. The figures are composed of 2 subplots, such that each subplot contains an imshow with 2 different plots (red and green) overlayed on it, like the following:
How do I get an image of all the data contained inside each figure, so that next I can convert the sequence of images to a video with VideoWriter?
The key is:
im = frame2im(getframe(h));
Where h is the handle to your plot or axis
You can also pass an optional argument 'rect' to getframe to specify the area to capture.
Here is an example from the MathWorks on how to use getframe in a loop to record the frames. For more information type doc getframe
Z = peaks;
surf(Z)
axis tight manual
ax = gca;
ax.NextPlot = 'replaceChildren';
loops = 40;
F(loops) = struct('cdata',[],'colormap',[]);
for j = 1:loops
X = sin(j*pi/10)*Z;
surf(X,Z)
drawnow
F(j) = getframe(gcf);
end
% Play back the movie two times.
fig = figure;
movie(fig,F,2)