How to maintain 100% magnification using imshow( ) in a number of iterations? - matlab

I am trying to display a set of images in the same figure window, at 100% magnification. At the same time, I would like to apply an annotation object onto each image.
Assuming that my input image does not exceed the screen size, this is what I have done :
imagedata = imread('cameraman.tif');
hFig = figure;
hAnnot = [];
for n = 1 : 10 % repeat ten times
% show and annotate image
imshow(imagedata, 'InitialMagnification', 100, 'border', 'tight');
if(isempty(hAnnot) || ~ishandle(hAnnot))
hAnnot = annotation('arrow', 'color', 'b');
end
set(gca, 'units', 'pixels');
gcapos = get(gca, 'Position');
% add label to display no of loop
text(10, 10, [' Loop : ', num2str(n)], 'Color', 'c')
pause(1); % pause one second to view
if(ishandle(hAnnot))
% remove hAnnot to prevent reappearance in next loop
delete(hAnnot);
% check if annotation object is successfully removed
if(~ishandle(hAnnot))
hAnnot = [];
else
sprintf('hAnnot is not cleared in loop #%d', n);
end
end
end
The results shows that only the first imshow() -ed image is shown at 100% magnification. and gca's position returned at [ 1 1 256 256 ], which is what I wanted.
The subsequent images (from loop 2 to 10) were zoom-ed out, and the position is now returned at [34.2800 29.1600 198.4000 208.6400].
Could anyone help to explain why does it behave in such a way?
I also looked into hFig's properties in every loop to find out if there is any changes. The only difference I have observed is the value of 'NextPlot' - in which 1st loop is 'replacechildren', while it is 'add' in the subsequent loops.

I don't know why it's happening, but a quick fix would be to get the position in the first iteration and set it in the others:
if (n==1)
gcapos=get(gca,'position');
else
set(gca,'position',gcapos);
end

Related

How to make previous inputs progressively fade out in a Matlab plot when I add new inputs

Let's say I have this very simple loop
for i=1:10
[xO, yO, xA, yA, xB, yB, xC, yC] = DoSomething(i);
line([xO,xA,xB,xC],[yO,yA,yB,yC]);
pause(0.1);
end
The coordinates that I am plotting correspond to the joints of a multibody system, and I am simulating their positions over time (please see a sample of the plot here):
Since some of the links move in a periodic way, it gets confusing to keep track visually of the movement. For this reason, now comes the question: how can I plot the lines in a way that, when a new line is plotted, the previous lines are faded progressively? In other words, so that I have a gradient from the most recently plotted data (most opaque) to the oldest data (increasingly transparent until it completely fades out).
This way when a new line is drawn in the same position as very old data, I will notice that it is a new one.
You can do this by modifying the 4th Color attribute of past lines.
Here's a demo resulting gif, where I faded out 10% of the transparency each frame, so only the most recent 10 lines are visible.
Here is the code, see my comments for details:
% Set up some demo values for plotting around a circle
a = 0:0.1:2*pi; n = numel(a);
[x,y] = pol2cart( a, ones(1,n) );
% Initialise the figure, set up axes etc
f = figure(1); clf; xlim([-1,1]); ylim([-1,1]);
% Array of graphics objects to store the lines. Could use a cell array.
lines = gobjects( 1, n );
% "Buffer" size, number of historic lines to keep, and governs the
% corresponding fade increments.
nFade = 10;
% Main plotting loop
for ii = 1:n
% Plot the line
lines(ii) = line( [0,x(ii)], [0,y(ii)] );
% Loop over past lines.
% Note that we only need to go back as far as ii-nFade, earlier lines
% will already by transparent with this method!
for ip = max(1,ii-nFade):ii
% Set the 4th Color attribute value (the alpha) as a percentage
% from the current index. Could do this various ways.
lines(ip).Color(4) = max( 0, 1 - (ii-ip)/nFade );
end
% Delay for animation
pause(0.1);
end
You may want to do some plot/memory management if you've got many lines. You can delete transparent lines by adding something like
if lines(ii).Color(4) < 0.01
delete(lines(ii));
end
Within the loop. This way your figure won't have loads of transparent remnants.
Notes:
I generated the actual gif using imwrite in case that's of interest too.
Apparently the 4th Color value 'feature' has been depreciated in R2018b (not sure it was ever officially documented).
Got enough upvotes to motivate making a slightly more fun demo...
Solution for Matlab 2018a or later (or earlier, later than 2012a at least)
Since the fourth color parameter as alpha value is no longer supported in Matlab 2018a (and apparently was never supposed to as Cris Luengo pointed out), here a solution that works in Matlab 2018a using the patchline function from the file exchange (credits to Brett Shoelson).
% init the figure
figure(); axes();
hold on; xlim([-1 0.5]); ylim([0 1]);
% set fraction of alpha value to take
alpha_fraction = 0.7;
n_iterations = 200;
% looping variable to prevent deleting and calling already deleted lines
% i.e. to keep track of which lines are already deleted
delete_from = 1;
for i=1:n_iterations
% your x, y data
[x, y] = doSomething(i);
% create line with transparency using patchline
p(i) = patchline(x,y, 'linewidth', 1, 'edgecolor', 'k');
% set alpha of line to fraction of previous alpha value
% only do when first line is already plotted
if i > 1
% loop over all the previous created lines up till this iteration
% when it still exists (delete from that index)
for j = delete_from:i-1
% Update the alpha to be a fraction of the previous alpha value
p(j).EdgeAlpha = p(j).EdgeAlpha*alpha_fraction;
% delete barely visible lines
if p(j).EdgeAlpha < 0.01 && delete_from > j
delete(p(j));
% exclude deleted line from loop, so edgealpha is not
% called again
delete_from = j;
end
end
end
% pause and behold your mechanism
pause(0.1);
end
I included the deletion of barely visible lines, as suggested by #Wolfie (my own, perhaps less elegant implementation)
And here a demonstration of a quick release mechanism:
I'm adding a 2nd answer to clearly separate two completely different approaches. My 1st answer uses the undocumented (and as of 2018b, depreciated) transparency option for lines.
This answer offers a different approach for line drawing which has no compatibility issues (these two 'features' could be implemented independently):
Create a fixed n lines and update their position, rather than creating a growing number of lines.
Recolour the lines, fading to white, rather than changing transparency.
Here is the code, see comments for details:
% "Buffer" size, number of historic lines to keep, and governs the
% corresponding fade increments.
nFade = 100;
% Set up some demo values for plotting around a circle
dt = 0.05; a = 0:dt:2*pi+(dt*nFade); n = numel(a); b = a.*4;
[x1,y1] = pol2cart( a, ones(1,n) ); [x2,y2] = pol2cart( b, 0.4*ones(1,n) );
x = [zeros(1,n); x1; x1+x2]; y = [zeros(1,n); y1; y1+y2];
% Initialise the figure, set up axes etc
f = figure(1); clf; xlim([-1.5,1.5]); ylim([-1.5,1.5]);
% Draw all of the lines, initially not showing because NaN vs NaN
lines = arrayfun( #(x)line(NaN,NaN), 1:nFade, 'uni', 0 );
% Set up shorthand for recolouring all the lines
recolour = #(lines) arrayfun( #(x) set( lines{x},'Color',ones(1,3)*(x/nFade) ), 1:nFade );
for ii = 1:n
% Shift the lines around so newest is at the start
lines = [ lines(end), lines(1:end-1) ];
% Overwrite x/y data for oldest line to be newest line
set( lines{1}, 'XData', x(:,ii), 'YData', y(:,ii) );
% Update all colours
recolour( lines );
% Pause for animation
pause(0.01);
end
Result:

Although I used 'drawnow' and 'hold on', last plot still appears in animation - MATLAB

I read a lot of answers here, but for some reason my animation still doesn't work as expected.
The axis range should vary from frame to frame. The 'Hurricane Center' caption should remain in the center all the time, but the captions from the previous frames must be erased. Also, I'm afraid that some of the data from previous parts remain.
I used hold on and draw now but it still happens.
The animation can be seen here:
Code:
v = VideoWriter('test_video.avi');
v.FrameRate = 4;
v.open()
hold on
for i=1:length(relevant(1,1,:))
if isempty(relevant) == 0
title('Lightning around Hurricane Jerry')
grid on
ylim([Interp_Jerry(i,2)-Radius Interp_Jerry(i,2)+Radius])
xlim([Interp_Jerry(i,3)-Radius Interp_Jerry(i,3)+Radius])
ylabel('latitude')
xlabel('longitude')
text(Interp_Jerry(i,3),Interp_Jerry(i,2),txt1);
scatter(relevant(:,3,i),relevant(:,2,i),'.');
drawnow
pause(0.1);
v.writeVideo(getframe(fig));
end
end
v.close()
The best of the two worlds:
v = VideoWriter('test_video.avi');
v.FrameRate = 4;
v.open()
hold on;
for i=1:length(relevant(1,1,:))
if ~isempty(relevant) % Corrected
if i == 1
% Prepare first plot and save handles of graphical objects
ht = text(Interp_Jerry(i,3),Interp_Jerry(i,2),txt1);
hold on;
hs = scatter(relevant(:,3,i),relevant(:,2,i),'.');
ylabel('latitude')
xlabel('longitude')
title('Lightning around Hurricane Jerry')
grid on
else
% Update graphical objects
set(ht, 'position', [Interp_Jerry(i,3), Interp_Jerry(i,2)]);
set(hs, 'XData', relevant(:,3,i) , 'YData' , relevant(:,2,i));
end
ylim([Interp_Jerry(i,2)-Radius Interp_Jerry(i,2)+Radius])
xlim([Interp_Jerry(i,3)-Radius Interp_Jerry(i,3)+Radius])
drawnow
pause(0.1);
v.writeVideo(getframe(fig));
end
end
v.close()
Instead of writing the text every time, just modify its position in the loop. Create a text object out side of the loop
t = text(position1, position2, txt);
in the loop change the position and if necessary the text
set(t, 'position', [new_position1, new_position2]);
If you don't want the previous data to remain, then you shouldn't use hold on... I think you should revise your code as follows:
v = VideoWriter('test_video.avi');
v.FrameRate = 4;
v.open();
fg = figure();
% Do not hold on, so that data is not retained frame-to-frame
for i=1:length(relevant(1,1,:))
% You don't need to test if 'relevant' is empty, since you're looping to its length!
% New plot
scatter(relevant(:,3,i),relevant(:,2,i),'.');
% Customise plot (labels / axes / text / ...)
title('Lightning around Hurricane Jerry')
ylabel('latitude')
xlabel('longitude')
ylim([Interp_Jerry(i,2)-Radius Interp_Jerry(i,2)+Radius]);
xlim([Interp_Jerry(i,3)-Radius Interp_Jerry(i,3)+Radius]);
text(Interp_Jerry(i,3),Interp_Jerry(i,2),txt1);
grid on;
drawnow;
% You don't need to pause whilst plotting, you already set the video framerate.
% pause(0.1);
v.writeVideo(getframe(fg));
end
v.close()

How to use subplot, imshow, or figure in a loop, to show all the images?

Basically, I want to loop over all frames of video, subtract each frame from background image and display the result i.e subtractedImg either using subplot or figure.
vidObj = VideoReader('test3.mp4');
width = vidObj.Width;
height = vidObj.Height;
subtractedImg = zeros([width height 3]);
videoFrames = [];
k = 1;
while hasFrame(vidObj)
f = readFrame(vidObj);
f=uint8(f);
videoFrames = cat(numel(size(f)) + 1, videoFrames, f);
k = k+1;
end
backgroundImg = median(videoFrames,4);
i=1;
Problem here subplot which I have used here, in this loop does not show output. Only one figure is displayed with title "last one".
while hasFrame(vidObj)
frame = readFrame(vidObj);
subtractedImg=imabsdiff(frame,backgroundImg);
figure(i); imshow(subtractedImg);
% subplot(5,5,i),imshow(subtractedImg);
%uncommenting above line does not work, subplot not shown
if(i < 20)
i= i+1;
end
end %end while
subplot(1,2,1),imshow(subtractedImg),title('last one');
How do I show each image using subplot? For example using 5x5 subplot, If I want to display 25 subtracted images, why subplot(5,5,i),imshow(subtractedImg); is not working?
This should make one figure and a new subplot for each frame:
figure(1);clf;
for ct = 1:size(videoFrames,4)
subtractedImg=imabsdiff(videoFrames(:,:,:,ct),backgroundImg);
subplot(5,5,ct);imshow(subtractedImg);
if(ct == 25)
break
end
end
The first thing to do here is to remove the call for figure inside the loop. Just one call to the figure before the loop is fine. You can use clf at each iteration to clear the current figure's content.
Then, you may want to add a drawnow command after the plot commands to refresh the figure at each iteration.
Finally, you may (or not) want to add a pause to wait for user input between frames. Note that if you use pause then drawnow is not required.

Copy of polygon created in matlab figure despite using same figure handle throughout

figure;
poly = fill(sq(:,1), sq(:,2), 'b');
%% create cell "p" consisting of 5600 arrays of same size as sq
for i=1:5600
hold on
set(poly, 'X', p{i}(:,1),...
'Y', p{i}(:,2));
hold off
drawnow;
end
%% again create cell "q" consisting of 8700 arrays of same size as sq
for i=1:8700
hold on
set(poly, 'X', q{i}(:,1),...
'Y', q{i}(:,2));
hold off
drawnow;
end
I create a blue-filled polygon in first line and then move it all over the figure. When i run the above code, first section moves a polygon as controlled by p from initial point x0 to x1. Then i make another cell q in second section of code and use it to move blue-filled polygon again from x1 to x2. But this time a copy of the polygon is created at x1 which moves so that the previous polygon is still at x1 while this new polygon is moving to x2. Why is this happening?
I tried to write what you describe, using a little different code (more efficient), and made up the parts you didn't add. It's working, so if this is what you look for you can either adopt this code or compare it with yours and look for the problem.
My code:
% define some parameters and auxilary function:
sq_size = 3;
makeSq = #(xy) [xy(1) xy(2)
xy(1)+sq_size xy(2)
xy(1)+sq_size xy(2)+sq_size
xy(1) xy(2)+sq_size];
% create the first object:
sq = makeSq([1 1]);
poly = fill(sq(:,1), sq(:,2), 'b');
% setting the limmits for a constant view:
xlim([0 50+sq_size])
ylim([0 50+sq_size])
% first loop:
p = randi(50,10,2); % no need for cell here...
for k = 1:size(p,1)
temp_sq = makeSq(p(k,:));
set(poly, 'X', temp_sq(:,1),'Y',temp_sq(:,2));
drawnow;
pause(0.1)
end
% second loop:
q = randi(50,20,2); % no need for cell here...
set(poly,'FaceColor','g') % change to green to see we are in the second loop
for k = 1:size(q,1)
temp_sq = makeSq(q(k,:));
set(poly,'X',temp_sq(:,1),'Y',temp_sq(:,2));
drawnow;
pause(0.1)
end
The pause is only so you see the animation, it's not really needed.

How to plot a real time signal in MATLAB?

I'm building a smile detection system, and I need to plot the probability of smile (from video input) like the graphs on the right in this video.
How can I do this in MATLAB?
Notes
I'm currently displaying the video frames with OpenCV & IntraFace default code, which looks something like this :
cf = 0; % Current Frame.
% create a figure to draw upon
S.fh = figure('units','pixels',...
'position',[100 150 frame_w frame_h],...
'menubar','none',...
'name','Smile Detector',...
'numbertitle','off',...
'resize','off',...
'renderer','painters');
% create axes
S.ax = axes('units','pixels',...
'position',[1 1 frame_w frame_h],...
'drawmode','fast');
set(S.fh,'KeyPressFcn',#pb_kpf);
S.im_h = imshow(zeros(frame_h,frame_w,3,'uint8'));
hold on;
S.frame_h = text(50,frame_h-50,['Frame ' int2str(cf)] , 'fontsize', 15, 'Color' , 'c');
while true && ~stop_pressed
tic;
im = cap.read;
cf = cf + 1;
if isempty(im),
warning('EOF');
break ;
end
set(S.im_h,'cdata',im); % update frame
set(S.frame_h , 'string' ,['Frame ' int2str(cf)]);
do_something_with_frame(im);
if isempty(output.pred) % if lost/no face, delete all drawings
if drawed, delete_handlers(); end
else % face found
update_GUI();
end
drawnow;
end
close;
end
And I want to add a live / moving graph like in the video. The graph will display a single value (a probability) between 0 and 1. And it should be updated with every new frame, therefore the plot should "flow" as the video flows.
What Have I Tried
I tried creating a new figure just like S in the code. But I cannot plot into it. I am also ok with adding the live graph in the same figure (S.fh), preferrably under the scene.
Using linkdata and refreshdata will refresh a graph plot as you have new data.
%some pretend data
pX1 = rand;
pX2 = 1-pX1;
p = [pX1,pX2];
bar(p)
%link the data to the plot
linkdata on
for i=1:100
pX1 = rand;
pX2 = 1-pX1;
p = [pX1,pX2];
%refresh the linked data and draw
refreshdata
drawnow
end
http://www.mathworks.co.uk/help/matlab/ref/linkdata.html
Hope it helps...