Reputation: 87
This could be very simple, but I have been looking for the proper answer for hours.
I am working on a visual task for primates and am using the PsychToolbox in MATLAB. What I am currently trying to do is randomize the photo that the subject has to decide on. There are many code examples for randomly picking images from a directory, but the images I am using have already been imported because they were previously used.
For reference here is the code that I have used to import the images randomly from the directory on my computer:
% Get the image files for the experiment
imageFolder = [cd '/ALSAMultiracial/'];
imgList = dir(fullfile(imageFolder, '*.jpg'));
numImages = length(imgList);
numTrials = numImages;
% Generate a random number between 1 and the number of images
randomNumber = randperm(numImages, 1);
% Get corresponding name of the image
randomImage = imgList(randomNumber).name;
% Now load the image
theImage = imread([imageFolder randomImage]);
% Make the image into a texture
tex = Screen('MakeTexture', window, theImage);
% Draw the texture
Screen('DrawTexture', window, tex, [], [], 0);
In this task, I flip between two images: theImage and theImage2. After I do that, I want to choose a random image to show: theImage or theImage2. What I was thinking is that I could make a list or an array and do something similar to what I did previously, but the problem is that I have unsuccessfully tried to make a list and array of these images to repeat the process, but it has not worked. For reference, all of the images in question are jpg and the same size.
Your help is very appreciated.
Upvotes: 1
Views: 1423
Reputation: 474
If you're just trying to load up a whole directory of pictures into an array, I'd suggest using a for loop over your imgList to read all of your images into an array. That way, when you generate your random number, you can just reference an array index.
Something to keep in mind with this. when imread is called, it's going to return a 3D array (red green blue values) So when you read in multiple images, you're going to have a 4D array.
You can do something like:
clear pictureData;
clear imgList;
for imgList = dir(fullfile(imageFolder, '*.jpg'))
pictureData(i, :, :, :) = imread([imageFolder imgList]);
end
to read in all of your pictures. Then when you grab a random number, you can grab the specific jpeg data you want with
pictureData(randomNumber,:,:,:)
Let me know if this is clear or not, I can try to explain further if you have specific questions, or if I've missed the mark completely.
Welcome to Stack Overflow. :)
Upvotes: 1