【问题标题】:Canonical Way to Aggregate Structures into a Vector将结构聚合成向量的规范方法
【发布时间】:2014-05-15 06:13:18
【问题描述】:

即使不得不问这个问题我也觉得很愚蠢,它真的应该很简单,但是作为 MatLab 的新手,我想知道一个更有经验的人会怎么做。

简单的问题;我需要在多幅图像中找到一些区域,按位置关联它们,保存这些感兴趣的区域,并在以后使用它们。一种方法是将区域存储在向量中。

%% pseudo code
regions = [];
for i = some_vector_of_images
  % segment, get mask
  % find regions
  cc = bwconncomp(mask);
  stats = regionprops(cc, 'all');
  % correlate against known x/y
  % save for later
  regions[index++] = stats;
end
% use 'regions'

但是,数组声明是有问题的。它的默认类型是 double,所以这不起作用(不能将结构分配给元素)。我试过struct.empty,但数组不可调整大小。我尝试了一个单元格数组,但我收到了类似的错误 (Conversion to cell from struct is not possible.)

真的,我只需要一种方法来在循环之前声明一些集合,以保存这些结构的实例。再一次,非常愚蠢的问题,在这里有点尴尬......请怜悯。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    看看使用 struct2cell 是否可以帮助您解决这个问题。试试这个pseudo-code -

    regions = cell(num_of_images,1) %// This will be before the loop starts
    ...
    
    regions[index++] = {struct2cell(stats)} %// Inside the loop
    

    请不要说这是pseudo-code,所以square brackets++ 将不起作用。

    因此,伪代码的完整版本将是 -

    %%// ---  pseudo code
    
    %// Without this pre-allocation you would get the error - 
    %%// "Conversion to cell from struct is not possible"
    regions = cell(numel(some_vector_of_images),1) 
    
    for i = some_vector_of_images
      % segment, get mask
      % find regions
      cc = bwconncomp(mask);
      stats = regionprops(cc, 'all');
      % correlate against known x/y
      % save for later
      regions(i) = {struct2cell(stats)}
    end
    

    【讨论】:

      【解决方案2】:

      您可以通过附加结构将空数组转换为结构数组。将regions[index++] = stats; 替换为

      regions = [regions, stats];
      

      这一行将继续在循环内构建数组。这个习语在 MATLAB 中通常不受欢迎,因为每个循环都需要创建一个新数组。

      另一种方法是使用模板结构预分配数组,使用 repmat。

      stats = some_operations_on(some_vector_of_images(1));
      regions = repmat(stats, numel(some_vector_of_images), 1);
      

      在循环中,赋值为

      regions(i) = stats;
      

      【讨论】:

      • 我很欣赏这个答案,也很欣赏你描述的串联方法。两个答案都有效,所以我只选择了第一个。不过还是谢谢。
      【解决方案3】:

      在这种情况下,通常我根本不预先分配,或者使用 cell-cat 模式。

      未初始化

      这个没有初始化结构数组,但工作正常。在这种情况下,请确保 i 是每个元素的索引。

      for i = 1:numel(some_vector_of_images)
        % mask = outcome of some_vector_of_images(i)
        cc = bwconncomp(mask);
        regions(i) = regionprops(cc, 'all');
      end
      

      细胞猫模式

      这个捕获结果是一个单元格数组,并在最后连接所有元素。

      regions = cell(numel(some_vector_of_images), 1);
      index = 1;
      for i = some_vector_of_images
        % mask = outcome of i
        cc = bwconncomp(mask);
        regions{index} = regionprops(cc, 'all');
        index = index + 1;
      end
      regions = cat(1, regions{:});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 2013-02-16
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多