首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Matlab:矩阵邻域提取

Matlab:矩阵邻域提取
EN

Stack Overflow用户
提问于 2014-08-25 13:32:05
回答 1查看 1K关注 0票数 3

我有大量的图像,我把它们分解成几个片段,它们的矩阵看起来像:

代码语言:javascript
复制
img = [ 1 1 1 1 1 2 2 2 3 3 3 3  
        1 1 1 1 2 2 2 2 2 3 3 3  
        1 1 1 4 4 4 2 2 2 3 3 3  
        5 5 5 5 5 5 5 2 2 3 3 3 ];

其中每个数字代表不同的区域,每个区域都是任意形状的。因此,在这种情况下,区域1有邻2,4和5,区域2有邻1,3和4等等。

我已经将所有区域提取到单独的单元中,并获得了统计数据(均值、方差等),我计划使用这些统计数据在一定的容限范围内将区域与统计数据合并。我正努力想出一种有效的方法来获得每个地区的邻居,从而允许这种合并发生。

我有一个可怕的解决方案,甚至一张图片都要花很长时间:

代码语言:javascript
复制
referenceImage = [ 1 1 1 1 1 2 2 2 3 3 3 3;
                    1 1 1 1 2 2 2 2 2 3 3 3;
                    1 1 1 4 4 4 2 2 2 3 3 3;
                    5 5 5 5 5 5 5 2 2 3 3 3];

% Wish to extract each region into a separate cell
lastSP = 5;
sps = 1:lastSP;
% Could be a way to vectorise the below loop but it escapes me
superPixels(lastSP) = struct('Indices', 0, 'Neighbours', 0);
% Split data into separate cells
parfor a = 1 : lastSP
    inds = find(referenceImage == sps(a));
    superPixels(a).Indices = inds;
end

szs = size(referenceImage); % Sizes of RGB Image
for a = 1 : lastSP + 1
    mask = zeros(szs(1), szs(2)); % Just bin mask wanted
    mask(superPixels(a).Indices) = 1; % Mark the region pixels as one
    mask = xor(bwmorph(mask, 'thicken'), mask); % Obtain the outlying regions

    inds = find(mask ==1); % Fetch the external region indices

    neighbours = []; % Have to dynamically grow neighbours matrix
    neigh = 1;  

    for b = 1 : length(inds)
        found = false;
        if ~isempty(neighbours) % Check neighbours first
            for c = 1 : length(neighbours)
                if any(superPixels(neighbours(c)).Indices == inds(b))
                    found = true;
                    break;
                end
            end
        end

        if ~found
           for c = 1 : lastSP + 1 % Check every other region
               if any(superPixels(c).Indices == inds(b))
                    neighbours(neigh) = c;
                    neigh = neigh + 1;
                    break;
                end
           end
        end            
    end  
    superPixels(a).Neighbours = neighbours;
end

我想知道这是否是解决这个问题的最佳方法。我知道最后一个循环是主要的问题,但我想不出另一种合理的方法来写这篇文章,除非我回溯和检查已知邻居的邻居。

任何帮助或推动正确的方向将是非常感谢的,谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-25 14:53:02

一个简单的(但可能不是最有效的)解决方案是扩展每个区域掩码以选择邻居:

代码语言:javascript
复制
labels = unique(img);
nLabels = length(labels);
neighbors = cell(nLabels,1);

for iLabel = 1:nLabels
   msk = img == labels(iLabel);
   adjacentPixelMask = imdilate(msk,true(3)) & ~msk;
   neighbors{iLabel} = unique(img(adjacentPixelMask));
end

neighbors{1}
ans =
     2
     4
     5
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25487090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档