Matlab:矩阵邻域提取
我有大量的图像,我已经将它们分解成若干段,使它们的矩阵看起来像:Matlab:矩阵邻域提取,matlab,image-processing,matrix,Matlab,Image Processing,Matrix,我有大量的图像,我已经将它们分解成若干段,使它们的矩阵看起来像: 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,依此类推 我已将所有区域提取到单独的单元格中
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,依此类推
我已将所有区域提取到单独的单元格中,并获得统计数据(均值、方差等),我计划使用这些数据将区域与特定公差内的统计数据合并。我正在努力寻找一种有效的方法,以获得每个地区的邻国,从而实现合并
我有一个可怕的解决方案,即使是一张图片也需要很长时间:
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
我想知道这是否是解决这个问题的最好方法。我知道最后一个循环是主要的问题,但我想不出其他合理的方法来写这个,除非我递归并检查已知邻居的邻居
如有任何帮助或推动方向正确,将不胜感激;谢谢 一个简单(但可能不是最有效)的解决方案是放大每个区域遮罩以拾取邻居:
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
您的代码不能正常运行。您应该定义所有变量,以便我们可以将其粘贴到Matlab命令窗口并获得结果。或者:对于您的示例
img
,准确地说出所需的输出be@SeanTheStudent:我相信您使用的方法与我相同,但您以某种方式检查每个像素的邻居,而查看区域的邻居则更快。太棒了!每个图像从几分钟过渡到20秒左右;巨大的差异,非常感谢!我对Matlab及其向量/矩阵方法有点陌生,因此感谢您的帮助@乔纳斯,很好!对于每个超像素,不仅要考虑最近的邻居(比如说k=1
),还要考虑邻居的邻居(k=2
)。@Tin:1
的邻居是唯一的(cat(1,邻居{neights{1}])
。使用邻居数组查看邻居的邻居。@Jonas,谢谢!因此,如果我想考虑<代码> k=3 < /COD>(邻居邻居的邻居)或更高,那么我可以使用递归函数<代码>唯一(CAT(1,邻居{ {II}}))< /C> >,其中代码> II< /COD>是邻居。你认为有更快的方法吗?