我提出了一个解决方案,它结合了
Divakar和
teng的答案,以及我自己的修改,并将其推广到2D或3D案例.
为了提高效率,我应该预先分配r和c,但在此期间,这是运行时:
>对于尺寸为117x159x126和32000个独立区域的3D图像:0.79秒
>对于上面的2D示例:使用此解决方案为0.004671s,使用Divakar解决方案为0.002136s,使用teng解决方案为0.03995s.
不过,我没有尝试将获胜者(Divakar)扩展到3D案例!
noDims = length(size(Im));
validim = ones(size(Im))>0;
labels = unique(Im);
if noDims == 3
Im = padarray(Im,[1 1 1],'replicate', 'post');
shifts = {[-1 0 0] [0 -1 0] [0 0 -1]};
elseif noDims == 2
Im = padarray(Im,[1 1],'replicate', 'post');
shifts = {[-1 0] [0 -1]};
end
% get value of the neighbors for each pixel
% by shifting the image in each direction
r=[]; c=[];
for i = 1:numel(shifts)
tmp = circshift(Im,shifts{i});
r = [r ; Im(validim)];
c = [c ; tmp(validim)];
end
A = sparse(r,c,ones(size(r)), numel(labels), numel(labels) );
% make symmetric, delete diagonal
A = (A+A')>0;
A(1:size(A,1)+1:end)=0;
谢谢您的帮助!