Search code examples
arraysimagematlabcell

storing images into to a cell in matlab


I understand that similar questions have been asked before but I have tried the other solutions and had no luck. Would really appreciate some help!

I want to 1.load a file of images, 2.read them with imread, 3.put that in a cell, 4.run my function stepwise on each array in the cell.

here is my function for 1 image/file

function sym_file(filename) %this calls for the image file name
j=im2double(rgb2gray(imread(filename)));
%reads the image, turns int into grayscale and double

if rem(size(j,2),2)~=0,j(:,1)=[];
if rem(size(j,1),2)~=0,j(1,:)=[];
end
end                                      
%this made sure the rows and columns are even

jr=fliplr(j);
left=(j(:,1:size(j,2)/2));
right=(jr(:,1:size(j,2)/2));
t=sum(left,2);
u=sum(right,2);
symmetry= (left-right)./255;
symmetry2=reshape(symmetry,1,(numel(symmetry)));
imbalance=mean(symmetry2)
asymmetry=sqrt(mean(symmetry2.^2))

%runs calculations on image

figure('Name',num2str(filename),'NumberTitle','off')
subplot(3,2,1)
histogram(symmetry2,200)
title(['symmetry:' num2str(asymmetry)])
subplot(3,2,2)
imshow(j)
title(['imbalance:' num2str(imbalance)])
subplot(3,2,3)
imshow(left) 
title('left')
subplot(3,2,4)
imshow(fliplr(right)) 
title('right')
impixelinfo;
subplot(3,2,5)
plot(1:length(t),t,'-r',1:length(u),u,'-b')
title('results,red=left/blue=right')

%printing results in a figure

So I would like to do this with a file of images rather than doing it file by file. What's the best way? Also, if someone knows how to store the data/figures in files that would be a bonus also.


Solution

  • Let me see if I got this straight: you have a set of images and you store them in a cell. You then want to apply a function to each image (in other words: to each element of the cell).

    If so, just use cellfun()

    Example:

    X = imread('http://sipi.usc.edu/database/preview/aerials/3.2.25.png','png');
    Y = imread('http://sipi.usc.edu/database/preview/misc/5.3.01.png','png');
    
    my_cell{1} = X;
    my_cell{2} = Y;
    
    my_fftcell = cellfun(@fft2,my_cell,'UniformOutput', false)
    

    In this case I loaded 2 images X and Y and stored them into my_cell (the brackets {} indicate to MATLAB/Octave that it is a cell). I then created another cell called my_fftcell which is the fft2 applied over each image.

    To get many files from a folder/directory, you can just loop over each file in that directory and store it into the cell. Something like this:

    Loading multiple images in MATLAB