【问题标题】:Matlab - Cropping 2d image maps in a loop and storing in a single variableMatlab - 在循环中裁剪二维图像映射并存储在单个变量中
【发布时间】:2013-11-26 11:35:54
【问题描述】:

我有一个代码来裁剪输入图像的连接组件 input,方法是从二进制图像的标记图 labelledmap ([labelledmap , labelcount] = bwlabel(hvedged, 8);)

我是 matlab 新手,所以这听起来可能很愚蠢.. 问题是,我无法将不同的裁剪图像存储在同一个变量中,因为 matlab 似乎合并了现有图像和新裁剪图像的末端,即它存储了两个裁剪图像之间的完整映射,我的看法:/

这是使用不同变量存储裁剪图像的输出(我想要的输出类型) Output Using different variables for storing cropped image

这是我通过将裁剪后的图像存储在同一个变量中得到的输出(没有帮助) Output when storing cropped image in the same varible

我尝试使用一个大小等于产生的标签总数的数组,但它给出了相同的结果。我还尝试了 clearvars 来清除输出令牌图像,ltoken,在循环的每次迭代之后,但它没有帮助

那么,是否有任何可能的方式来显示单个裁剪图像.. 裁剪图像的数量可能是数千,所以我想使用循环来编码它们的裁剪机制

这是附加的代码的一部分..在此先感谢;)

for h=1:labelcount
    for i=1:r
        for j=1:c

             if labelledmap(i,j)==h
                    if i<ltop
                        ltop=i;
                    end
                    if i>lbottom
                        lbottom=i;
                    end
                    if j<lleft
                        lleft=j;
                    end
                    if j>lright
                        lright=j;
                    end
             end

        end
    end

    if ltop>5
        ltop=ltop-5;
    end
    if lbottom<r-5
        lbottom=lbottom+5;
    end
    if lleft>5
        lleft=lleft-5;
    end
    if lright<c-5
        lright=lright+5;
    end

    lwidth=lright-lleft;
    lheight=lbottom-ltop;

    ltoken=imcrop(input,[lleft ltop lwidth lheight]);
    figure('Name', 'Cropped Token'), imshow(ltoken);
    clearvars ltoken;
end

【问题讨论】:

  • 尝试使用元胞数组。用imlist={}初始化,用imlist{end+1}=...追加一个新图像
  • @DanielR 在这种情况下,他提前知道 imlist 中的元素数量 - 他应该预先分配而不是在循环中使 imlist gors - 这是不好的做法。
  • 你是对的。 imlist=cell(labelcount,1) 进行初始化,imlist{h}=... 进行写入。由于某种原因,我错过了外循环。

标签: arrays matlab image-processing


【解决方案1】:
  1. 你需要为标签h的每次迭代初始化ltoplbottomlleftlright。我认为这就是您将裁剪后的图像“粘合”在一起的原因。

  2. 遍历每个标签的所有像素是非常低效的。尤其是当您需要有很多标签时。
    使用regionprops 获取每个标签的'BoundingBox' 属性。

这是一个例子

st = regionprops( labelledmap, 'BoundingBox' );
imlist = cell( 1, numel(st) ); % pre-allocate
for ii=1:numel(st)
    r = st(ii).BoundingBox;
    % I understand you want to increase the BB by 5 pixels at each side:
    r(1:2) = r(1:2) - 5;  % start point moves -5
    r(3:4) = r(3:4) + 10; % width and height increases by 10
    imlist{ii} = imcrop( input, r );
end

我仍然对您的代码感到有些震惊,该代码明确地循环遍历所有像素只是为了找到边界框。这不是 matlab 的做事方式。
如果您坚持不使用regionprops,这里有一种更类似于 Matlab 的方式来查找ii-th 边界框:

imsk = (labeledmap == ii); % create a binary map with True for ii-th region
xFlat = any(imsk,1); % "flattening" imsk on the x-axis
lleft = find( xFlat, 1, 'first' );
lright = find( xFlat, 1, 'last' );
yFlat = any(imsk, 2);
ltop = find( yFlat, 1, 'first' );
lbottom = find( yFlat, 1, 'last' );

图像坐标上没有循环。

【讨论】:

    猜你喜欢
    • 2014-03-27
    • 2013-12-26
    • 2016-12-05
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多