【问题标题】:How do I move an image into a cell in matlab?matlab如何将图像移动到单元格中?
【发布时间】:2019-03-11 19:28:38
【问题描述】:

我构建了一个名为 N 的 1*5 单元格,需要将一个图像 (img) 矩阵复制到其中的每个条目中,我该怎么办?这是我想出的,但它不起作用...... 我试图避免 for 循环,所以我的代码会更快。

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

【问题讨论】:

  • 1: 在编写循环代码并发现它太慢之前,不要避免循环。 MATLAB 的循环不再慢,并且您应用于图像的任何过程都将花费更多的时间来循环遍历单元阵列中的一组图像。 2: cellfun 是一个 M 文件函数,它使用 for 循环,因此您不会避免循环。 3:更重要的是你的代码可读性和可维护性,除非你不满足时间要求,否则很快忘记(例如:我需要3年后毕业,这段代码需要5年才能完成)。

标签: matlab vectorization cell cell-array


【解决方案1】:

根据我从您的问题中了解到的情况,并同意 Cris Luengo 在循环部分的观点,这就是我的建议。我假设scale(1) = 1 或类似的东西,因为您初始化了N = (cell(length(scale) - 1, 1))',所以我猜scale 中的值之一并不重要。

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

一个小测试脚本:

% 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

输出:

ans =
   738   738

ans =
   624   624

ans =
   504   504

ans =
   300   300

ans =
   60   60

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多