Matlab while loop screenshot reload - matlab

I want to take a screenshot of my screen every second and then save it.
I want to use this to play a game, where there is a counter. I thought a while loop would keep refreshing the imshow(screenshot) however, it does not. Here is my code:
i = 1;
while i > 0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Screenshot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
imshow(screenshot)
robo = java.awt.Robot;
t = java.awt.Toolkit.getDefaultToolkit();
%# Set the capture area as the size for the screen
rectangle = java.awt.Rectangle(t.getScreenSize());
%# Get the capture
image = robo.createScreenCapture(rectangle);
%# Save it to file
filehandle = java.io.File(sprintf('capture%d.jpg', 1));
javax.imageio.ImageIO.write(image,'jpg',filehandle);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load screen
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
screenshot = imread('capture1.jpg'); % is using as a test
screenshot = imcrop(screenshot,[360 205 520 423]);
end

Have you tried using drawnow to update the current figure: http://www.mathworks.com/help/matlab/ref/drawnow.html?refresh=true

Related

How to save all sequentially captured image in MATLAB?

I need to save all the captured images in MATLAB but I am able to save one picture at a time.
mycam = webcam();
img = snapshot(mycam);
imwrite(img,'img.jpg');
If somebody knows how to save all the pictures taken at a time in MATLAB, please help me with the code.
I would save the images as a movie and then access the frames later. This is untested but it would work like this.
mycam = webcam();
% if you know the number of images use that here
% a movie is just a collection of frames
% if not then just don't initialize F
F(nFrames) = struct('cdata', [], 'colormap, []);
for i = 1:nFrames
F(i) = im2frame(snapshot(mycam));
end
% save F
movie2avi(F, 'MyMovie.avi', 'compression', 'None');
Then you can load the movie and look at the frames. This example uses the older movie2avi but VideoWriter is also an option
v = VideoWriter('MyMovie.avi');
open(v);
for i = 1:nFrames
writeVideo(v, snapshot(mycam));
end
close(v);
Again untested as I don't have a webcam attached to this computer. But it works for animated graphs. See doc readFrame for the way to read frames
As they have already told you, you should use a for loop with the sprintf function in order to not overwrite the previous images. Try with the following command:
%capture the frames
for i =1:n;% n is the number of frames you want to capture
frames{i} = getsnapshot(mycam);
end
%save in the current folder
for i = 1:n;
imwrite(frames{i}, sprintf('imageName%d.jpg',i))
end
You will have all the captured frames saved in the Current Folder.

Repeating trials in MatLab

i'm am very new to Matlab but really want improve. For my experiment i want to show a picture which the participant response yes/no to, using two different keys (f&g) and then the next picture is presented and it repeats so onward.
Presenting the picture, using the keys works for far, but i can't get it to repeat the trial. Thus my question is how can i get the program to repeat/loop my trial?
Is there something wrong in my code so far or is there additional coding i should use?
this is my code so far
function try1_6()
cleanupObj= onCleanup(#() myCleanupFxn);
% PRETEST
% Initialize screen with black background
winID = Screen('openWindow',0, [0 0 0]);
%Parameter
backcol=255;
textcol=0;
% Load image file(s)
structimages= [];
TheImagesdir = dir('theImagesdir/*.jpg');
for i=1: length(TheImagesdir);
TheImages = imread(['theImagesdir/' TheImagesdir(i).name], 'JPEG');
% Get width and height
imageX = size(TheImages,2);
imageY = size(TheImages,1);
% Convert to texture
myTexture = Screen('MakeTexture', winID, TheImages);
% Set destination rectangle
destRect = [50 100 50+imageX 100+imageY];
%save to structure
structimages(end+1).filename=TheImagesdir(i).name;
structimages(end).destRect= destRect;
structimages(end).texture= myTexture;
end
%Make triallist
numberOfItems= [5]; %list of all possible items
Nrepeats=4;
Response=0;
TrialList=HH_mkTrialList({numberOfItems Response},Nrepeats);
%PRESENTATION
for trialnum=1:size(TrialList,1)
nitems = TrialList(trialnum,1);
Screen('FillRect', winID,backcol); % makes the screen blank
%displays text
DrawFormattedText(winID,'dkjfghaslkdfglksdjgfh','center','center',textcol);
Screen('Flip', winID)
HH_waitForKeyPress({'space'}); % waits for spacebar to be pressed
Screen('FillRect',winID,backcol);
Screen('Flip',winID);
WaitSecs(1);
%display picture
whichTheImages= randi(length(TheImagesdir)); % randomly selects image for directory
Screen('FillRect',winID,backcol);
Screen('DrawTexture', winID, myTexture, [], destRect);
Screen('Flip', winID);
HH_waitForKeyPress({'f','j'},5)
if resp==-1
break
end
TrialList(trialnum,4)= response; %records response
end
end
function myCleanupFxn()
Screen('CloseAll')
end
There are a number of problems with you code that you need to address. First of all, TrialList is used before it is declared/initialized. The Make triallist block of code seems out of place in the body of the for loop, and should probably be placed before you loop TrialList.
Your second problem is the inner for loop that loads images. Right now, it loads every image found in the directory, on every trial! There is no reason for you to be doing this, and you should be placing this for loop outside the trial loop as well. Furthermore, your original code never worked as intended, because you never save the loaded texture anywhere; myTexture is overwritten by the last image in your folder and that's the only texture you're ever gonna get. So in addition to pre-loading the images before the loop, you need to save them in a data structure so that you can use them later in your trial loop. A simple struct will work nicely here:
structImages = [];
TheImagesdir = dir('theImagesdir/*.jpg');
for i = 1:length(TheImagesdir);
TheImages = imread(['theImagesdir/' TheImagesdir(i).name], 'JPEG');
% Get width and height
imageX = size(TheImages,2);
imageY = size(TheImages,1);
% Convert to texture
myTexture = Screen('MakeTexture', winID, TheImages);
% Set destination rectangle
destRect = [50 100 50+imageX 100+imageY];
%save to structure
structImages(end+1).filename = TheImagesdir(i).name;
structImages(end).destRect = destRect;
structImages(end).texture = myTexture;
end
There are other inconsistencies in your code:
whichTheIamges is defined but not used
resp is used in the comparison if resp==-1 but is not defined
response is saved into TrialList before it is defined
Finally, the biggest problem is Screen('CloseAll', winID); is inside the trial loop, so you tear down your whole presentation platform after the first trial.
FYI, as noted in my comment wrapping your entire script in a try block is really poor practice. I suspect you do this because you want to be able to Ctrl+C mid-task, but there's a better way to do this. If you make your entire script a function then you can use the onCleanup method to execute code whenever your function exits (whether normally, by error, or by interruption). The method goes like this:
function myScript()
%//make your script a function. There is an additional advantages to doing this:
%//function performance is better than script performance.
%//blah-blah-blah
%//setup the cleanup object before opening screen
cleanupObj = onCleanup(#() myCleanupFxn);
%//open the screen
winID = Screen('openWindow',0, [0 0 0]);
%//blah-blah-blah
end
function myCleanupFxn()
%//local function, not visible outside of this file
Screen('CloseAll');
end

Matlab how to display snapshots?

vido = videoinput('winvideo',1);
vido.FrameGrabInterval = 10;
start(vido)
while(vido.FramesAcquired<=30)
data = getsnapshot(vido);
imshow(data);
flushdata(vido);
end
Hi.I have the code above.It is working but taking place from memory for every snapshot.For example it stars 600mb,610,620...Why ? how can I prevent this?
You are most likely not removing the video object when you're done. You keep creating video objects every time you run this code, even though you grab 30 frames from the source and stop capturing after that point. As such, make sure you remove the video object when the while loop finishes by delete.
In addition, you have stated that imshow is the reason why you keep getting an increase in memory. It actually shouldn't, but if you're really that concerned, you can spawn a blank figure and then grab a handle to the imshow window. Next, you can simply update the window for each frame you read in... so:
hAxes = subplot(1,1,1); % //Create a blank window and get the axes handle
%// First frame flag
firstFrame = true;
vido = videoinput('winvideo',1);
vido.FrameGrabInterval = 10;
start(vido);
while(vido.FramesAcquired<=30)
data = getsnapshot(vido);
if firstFrame % //If first frame, show the image and get a handle to the window
hImage = imshow(data, 'Parent', hAxes);
firstFrame = false;
else
%// Simply update the window after the first frame
set(hImage, 'CData', data);
end
flushdata(vido);
end
delete(vido); %// IMPORTANT

MATLAB: Print contents of uipanel to PNG image

I don't know how to accomplish the following in MATLAB. I have a figure which looks like this:
In the figure, I have a panel with many subplots and a scrollbar that allows me to view a portion of the panel.
I want to save the whole contents of the panel to a PNG image file (not just the visible portion), i.e. I want to have a file which is a tall rectangle, and doesn't require scrolling.
The code for generating the figure is as follows:
function draw(obj)
figure;
panel1 = uipanel('Parent',1);
panel2 = uipanel('Parent',panel1);
panelheight = obj.nIterations / 2;
set(panel1,'Position',[0 0 0.97 1]);
set(panel2,'Position',[0 1-panelheight 1 panelheight]); %%
nPlot = 1;
for i=1:obj.nIterations
models = obj.iterations{i};
for nModel=1:length(models)
subplot(obj.nIterations,length(models)*2,nPlot);
nPlot = nPlot + 1;
drawTransitions(models{nModel});
set(gca,'Parent',panel2);
subplot(obj.nIterations,length(models)*2,nPlot);
nPlot = nPlot + 1;
drawRewards(models{nModel});
set(gca,'Parent',panel2);
end
end
s = uicontrol('Style','Slider','Parent',1,...
'Units','normalized','Position',[0.97 0 0.03 1],...
'Value',1,'Callback',{#slider_callback1,panel2,panelheight});
end
I have tried the following, without success.
The saveas funstion saves the whole figure, not just the panel. Also, it clips the invisible portion of the panel.
export_fig(panel2.'file.png') gives just a solid gray image.
Why don't you just scroll your panel and grab the frames and concatenate them all together? Here's some code that will basically do that. I would have posted am image, but I guess I don't have enough points for that. You may need to fiddle with the scrolling, and maybe making the slider invisible, but it works.
function printPanel(pnl,filename)
fig = figure(ancestor(pnl,'figure'));
pnl_units = get(pnl,'units');
fig_units = get(fig,'units');
set(pnl,'units','pixels')
set(fig,'units','pixels')
pnl_rect = getpixelposition(pnl);
fig_rect = getpixelposition(fig);
pnl_height = pnl_rect(4);
fig_height = fig_rect(4);
pnl_rect(2) = -pnl_height;
set(pnl,'position',pnl_rect)
N = ceil(pnl_height/fig_height);
CDATA = cell(N,1);
for i = 1:N
F = getframe(fig);
CDATA{i} = F.cdata;
pnl_rect(2) = pnl_rect(2)+fig_height;
set(pnl,'position',pnl_rect)
drawnow
end
set(pnl,'units',pnl_units)
set(fig,'units',fig_units)
imwrite(cat(1,CDATA{:}),filename)
end
You could get rid of the ui elements and just make a figure with all the subplots, and then export that one, using e.g. print -dpng ....
saveas takes a handle as a first argument. Maybe this does not have to be a figure or model handle, but could be a reference to the contents of the panel.

getsnapshot returns a cyan screen

I run this code in MATLAB but it returns a Cyan frame
obj = videoinput('winvideo', 1);
% Select the source to use for acquisition.
set(obj, 'SelectedSourceName', 'input1')
% View the properties for the selected video source object.
src_obj = getselectedsource(obj);
get(src_obj)
% Acquire and display a single image frame.
frame = getsnapshot(obj);
image(frame);
% Remove video input object from memory.
delete(obj);
But preview video works well.
Perhaps the problem is with the input to image command.
Try to run
class(frame)
max(frame(:))
min(frame(:))
And see what the results are.
Double values should be between [0-1], whereas uint8 should be in the range of [0-255].
Adding obj.ReturnedColorSpace = 'rgb'; in the second line solved it.