0

我有点困惑,非常感谢一些帮助。

我已经阅读了许多有关查找相邻像素的帖子,这非常有帮助:

http://blogs.mathworks.com/steve/2008/02/25/neighbor-indexing-2/

但是,我无法将其应用于大小(A)=[8 340 340 15] 的 4D 矩阵(A)。它代表 8 组 3D 图像(每组 15 个切片),我想获取其中的邻居。我不确定要使用哪个大小来计算偏移量。这是我尝试过的代码,但我认为它不起作用,因为偏移量应该适用于 4 维?没有循环怎么办?

%A is a 4D matrix with 0 or 1 values
Aidx = find(A); 

% loop here? 
[~,M,~,~] =size(A);
neighbor_offsets = [-1, M, 1, -M]';

neighbors_idx = bsxfun(@plus, Aidx', neighbor_offsets(:));
neighbors = B(neighbors_idx);

谢谢,齐格

4

3 回答 3

2

不确定我是否理解你的问题,但这种方法怎么样:

如果你的矩阵是一维的:

M = rand(10,1);
N = M(k-1:k+1); %//immediate neighbours of k

但是,如果k在边界处,这可能会出错。max使用and很容易解决这个问题min

N = M(max(k-1,1):min(k+1,size(M,1))

现在让我们添加一个维度:

M = rand(10,10);
N = M(max(k1-1,1):min(k1+1,size(M,1), max(k2-1,1):min(k2+1,size(M,2))

这很简单,您所要做的就是重复相同的索引,从而对使用size(M,2)边界进行微小的更改(我也更改kk1and k2,您可能会发现使用数组 fork而不是单独的k1k2变量效果更好,即k(1)and k(2)

好的,现在让我们跳到 4 个维度:

M = rand(10,10,10,10);
N = M(max(k(1)-1,1):min(k(1)+1,size(M,1)), ...
      max(k(2)-1,1):min(k(2)+1,size(M,2)), ...
      max(k(3)-1,1):min(k(3)+1,size(M,3)), ...
      max(k(4)-1,1):min(k(4)+1,size(M,4)));  %// Also you can replace all the `size(M,i)` with `end` if you like

我知道你说你不想要一个循环,但是一个非常短的循环只是为了重构一点并使其通用化:

n=ndims(M);
ind{n} = 0;
for dim = 1:n
    ind{dim} = max(k(dim)-1,1):min(k(dim)+1,size(M,dim));
end
N = M(ind{:});
于 2014-06-23T08:14:50.963 回答
2

你考虑过使用convn吗?

msk = [0 1 0; 1 0 1; 0 1 0];
msk4d = permute( msk, [3 1 2 4] ); % make it 1-3-3-1 mask
neighbors_idx = find( convn( A, msk4d, 'same' ) > 0 ); 

您可能会发现以一般方式conndef定义基本要素很有用。msk

于 2014-06-23T08:20:09.477 回答
0

这是沿第二维获取邻居的方法

sz = size( A );
ndims = numel(sz); % number of dimensions
[d{1:ndims}] = ind2sub( sz, find( A ) );
alongD = 2; % work along this dim
np = d{alongD} + 1;
sel = np <= sz( alongD ); % discard neighbors that fall outside image boundary
nm = d{alongD} - 1;
sel = sel & nm > 0; % discard neighbors that fall outside image boundary
d = cellfun( @(x) x(sel), d, 'uni', 0 ); 
neighbors = cat( 1, ...
                 ind2sub( sz, d{1:alongD-1}, np(sel), d{alongD+1:end} ),...
                 ind2sub( sz, d{1:alongD-1}, nm(sel), d{alongD+1:end} ) );
于 2014-06-23T08:15:29.523 回答