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.
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. :)
Related
I have folder that consists of 10 images.
I am trying to apply a gaussian filter to each of them. I read images from a folder named dd and then I want to save the altered images in newfolder. However, when I look at the image it is empty.
How can I do this in correct way , read 10 images , filter them , save altered 10 images in new folder.
Here is the code that I have so far:
for img = 1:10
a = imread(['\dd\',int2str(img),'.pgm']);
G = fspecial('gaussian',[3 3],2);
Ig = imfilter(a,G,'same');
imshow(Ig);
imwrite( Ig, 'Ig.pgm '); % does not work !!
save ([ path,'\newfolder\', 'new.pgm'],'Ig');% it save empty image !!!
end
save is not for saving images. Instead, you will want to use imwrite for that. You will also want to provide the full path to imwrite and here we use mat2gray just to ensure that your data covers the entire dynamic range of the image type. You'll also want to be sure that each output image has a unique name so that they don't overwrite one another.
output_filename = fullfile(path, 'newfolder', sprintf('%d_new.pgm', img));
imwrite(mat2gray(Ig), output_filename, 'pgm');
As a side note, you'll want to use fullfile to reliably construct your folder paths across computers and operating systems.
I have RGB museum JPG Images. most of them have image footnotes on one or more sides, and I'd like to remove them. I do that manually using paint software. now I applied the following matlab code to remove the image footnotes automatically. I get a good result for some images but for others it not remove any border. Please, can any one help me by update this code to apply it for all images?
'rgbIm = im2double(imread('A3.JPG'));
hsv=rgb2hsv(rgbIm);
m = hsv(:,:,2);
foreground = m > 0.06; % value of background
foreground = bwareaopen(foreground, 1000); % or whatever.
labeledImage = bwlabel(foreground);
measurements = regionprops(labeledImage, 'BoundingBox');
ww = measurements.BoundingBox;
croppedImage = imcrop(rgbImage, ww);'
In order to remove the boundaries you could use "imclearborder", where it checks for labelled components at boundaries and clears them. Caution! if the ROI touches the boundary, it may remove. To avoid such instance you can use "imerode" with desired "strel" -( a line or disc) before clearing the borders. The accuracy or generalizing the method to work for all images depends entirely on "threshold" which separates the foreground and background.
More generic method could be - try to extract the properties of footnotes. For instance, If they are just some texts, you can easily remove them by using a edge detection and morphology opening with line structuring element along the cols. (basic property for text detection)
Hope it helps.
I could give you a clear idea or method if you upload the image.
I am looking for advice on how to automatically register image stacks acquired at different magnifications. Specially we need to align a small z-stack (~100um) taken of several brain cells in the live brain to a large z stack(~2mm) taken of the fixed brain. We want to be able to find back the cells that were previously imaged and take high resolution images of the staining to identify pre-synaptic inputs. Both the difference in magnification and rotation need to be taken into account as well as possible shrinkage or swelling. We would like an advice on the best way to do this using ImageJ or matlab.
With ImageJ you might want to download the plugin StackReg:
http://bigwww.epfl.ch/thevenaz/stackreg/
or this nice macro code freely available:
http://www.plosone.org/article/info%3Adoi%2F10.1371%2Fjournal.pone.0053942
With matlab you are looking for imregister, imregtform and/or imwarp. Also look at the optimizer, which is used to define the type of transformation you wish to apply, for example translation, rigid body, etc. Examples on the matlab website are quite helpful. Please ask for more details if it's not clear.
EDIT:
Here is a simple code to register images stored in a sequence in a cell array with Matlab and the functions I mentionned:
clear
clc
dialog_title = 'Select the directory containing the images to be processed'; % select images
folder_name = uigetdir('',dialog_title);
addpath(folder_name);
% select current folder
cd(folder_name);
ImagesToRead = dir('*.tif');
%preallocation
ImageCell = cell(1,length(ImagesToRead));
for i=1 : length(ImagesToRead)
ImageCell{i} = imread(ImagesToRead(i).name);
end
optimizer = registration.optimizer.RegularStepGradientDescent; % here you can modify the default properties of the optimizer to suit your need/to adjust the parameters of registration.
[optimizer, metric] = imregconfig('monomodal'); % for optical microscopy you need the 'monomodal' configuration.
RegisteredCell = cell(1,length(ImagesToRead));
for p = 2:length(ImagesToRead)
moving = ImageCell{p}; % the image you want to register
fixed = ImageCell{p-1}; % the image you are registering with
movingONE = rgb2gray(moving(:,:,:)); % imregtform needs grayscale images
fixedONE = rgb2gray(fixed(:,:,:));
tform = imregtform(movingONE,fixedONE,'translation',optimizer,metric,'DisplayOptimization',true,'PyramidLevels',5);
tform = affine2d(tform.T);
RegisteredCell{p} = imwarp(moving,tform,'OutputView',imref2d(size(fixedONE))); %
end
Now all your images are stored in the cell array 'RegisteredCell' and you can access each of them individually using RegisteredCell{YouImage} for example. Hope that helps!
I'm making a GUI in MatLab that asks the user to upload a video file.
Next I want to play it in axes with a fixed window size . However, if the uploaded file is large, Matlab will expand the axes and take over most of my GUI. Is there a way to shrink the image to make it fit the axes?
Does anyone know how to solve this?
Usually Matlab axes are not supposed to change their position if the image is too big.
I can think of two possible problems:
The axes were large from the beginning, but showed small image with margins if the image is small enough
The command of showing the image that you are using is custom and it changes the axes size.
This question is old, but I stumbled across this (looking for something else) so perhaps it will help someone to see what I did.
I wanted to resize pretty large images (1024x 100k-200k pixels) so that my GUI can quickly demonstrate various color operations on a view of these large data sets. I just manually sub-sampled my data as follows (functions below).
Note that this example is an image. To spatially sub-sample a video, I have looped through the video and done something similar in the past on each frame.
[plotWidthPixels, plotHeightPixels] = getPlotAreaPixels(handles.figure1, handles.axes1);
[nSamplesPerLine nLines] = size(iqData);
colInds = decimateToNumber(nLines,plotWidthPixels);
rowInds = decimateToNumber(nSamplesPerLine,plotHeightPixels);
iqDataToPlot = iqData(rowInds,colInds);
First, I got the axis size in pixels:
function [plotWidthPixels, plotHeightPixels] = getPlotAreaPixels(figHandle, axisHandle)
set(figHandle,'Units','pixels')
figSizePix = get(figHandle,'Position');
set(axisHandle,'Units','normalized')
axSizeNorm = get(axisHandle,'Position');
axisSizePix = figSizePix.*axSizeNorm;
plotWidthPixels = ceil(axisSizePix(3)-axisSizePix(1));
plotHeightPixels = ceil(axisSizePix(4)-axisSizePix(2));
Then I used that to decimate the width and height of my image by getting sub-sets of indices that are (crudely approximately) evenly spaced:
function inds = decimateToNumber(lengthOfInitialVector, desiredVectorLength, initialIndex)
if nargin < 3
initialIndex = 1;
end
if (lengthOfInitialVector-initialIndex+1) > desiredVectorLength*2
inds = round(linspace(initialIndex,lengthOfInitialVector,desiredVectorLength));
else
inds = initialIndex:lengthOfInitialVector;
end
I was given a defined set of images (.png), I am supposed to detect each images Edges, then apply some image processing, but I have a problem.
First I an image array as follows :
imgArray = {'image_1.png','image_2.png','image_3.png'}
Then applied edging (sobel), using the MATLAB built in function edge so :
for i = 1:3
image=imread(imgArray{i});
image = edge(image,'sobel');
imgArray{i} = image;
end
based on that prvious code and my understanding, that the imageArray, now contains all 3 edged images.
Later on, I need to use the Edged images using that command image=imread(imgArray{i}); in a different place in the code, but it gives me an Error, I dont understand why does that happen ??
EDIT:
Here's the error I'm getting:
Error in ==> ImageCompare at 43 image=imread(imgArray{i});
imgArray = {'image_1.png','image_2.png','image_3.png'};
imgArrayEdged = strrep(imgArray, '.png', '_edged.png');
for i = 1 : length(imgArray)
image = imread(imgArray{i});
image = edge(image,'sobel');
imwrite(image, imgArrayEdged{i});
end
% later...
for i = 1 : length(imgArray)
if (your_condition)
image = imread(imgArray{i});
else
image = imread(imgArrayEdged{i});
end
end
Your imgArray contains file names as strings. In your loop, you are reading the image files and replacing each string in the cell array with image data.
If you absolutely require the file name strings later, you must create a second variable to hold the image data itself. If you only require the original images, just don't use imread later in the code!
Having read in an image file with imread once, there is no reason to waste time by reading the files again. It seems like you aren't quite aware of what state your data is in as it moves through your code. I suggest you use MATLAB's excellent debugger to step through and examine the type and content of the variables - you will quickly see where imread, which needs a file name, is inappropriate.