Search code examples
matlabvectorizationcellcell-array

How do I move an image into a cell in matlab?


I built a 1*5 cell named N and need to copy an image (img)matrix into each entry in it what should I do? This is what I came up with but it doesn't work.... I'm trying to avoid for loops so my code will be faster.

function newImgs = imresizenew(img,scale)  %scale is an array contains the scaling factors to be upplied originaly an entry in a 16*1 cell
    N = (cell(length(scale)-1,1))'; %scale is a 1*6 vector array
      N(:,:) = mat2cell(img,size(img),1); %Now every entry in N must contain img, but it fails
    newImgs =cellfun(@imresize,N,scale,'UniformOutput', false); %newImgs must contain the new resized imgs 
end

Solution

  • From what I've understood from your question, and agreeing with Cris Luengo on the loop part, here is what I would suggest. I assume, that scale(1) = 1 or something like that, because you initialize N = (cell(length(scale) - 1, 1))', so I guess one of the values in scale is not important.

    function newImgs = imresizenew(img, scale)
    
      % Initialize cell array.
      newImgs = cell(numel(scale) - 1, 1);
    
      % Avoid copying of img and using cellfun by directly filling 
      % newImgs with properly resized images.
      for k = 1:numel(newImgs)
        newImgs(k) = imresize(img, scale(k + 1));
      end
    
    end
    

    A small test script:

    % Input
    img = rand(600);
    scale = [1, 1.23, 1.04, 0.84, 0.5, 0.1];
    
    % Call own function.
    newImgs = imresizenew(img, scale);
    
    % Output dimensions.
    for k = 1:numel(newImgs)
      size(newImgs{k})
    end
    

    Output:

    ans =
       738   738
    
    ans =
       624   624
    
    ans =
       504   504
    
    ans =
       300   300
    
    ans =
       60   60