检查最近的8个邻居之间的有效索引



我已将一个图像划分为若干个子图像。现在我想比较每个子图像和它的8个相邻图像的平均强度。但在某些点上,邻居数少于8个。例如,对于第一个块(i=1,J=1),左上角的块(i-1, J -1)不存在。我如何检查这个并跳转到下一个有效的?

file='myimg.bmp';
I=imread(file);
blockSizeR = 128; % Rows in block.
blockSizeC = 128; % Columns in block.
wholeBlockRows = floor(rows / blockSizeR);
blockVectorR = [blockSizeR * ones(1, wholeBlockRows), rem(rows, blockSizeR)];
wholeBlockCols = floor(columns / blockSizeC);
blockVectorC = [blockSizeC * ones(1, wholeBlockCols), rem(columns, blockSizeC)];
ca = mat2cell(I, blockVectorR, blockVectorC);
%get the mean value of each cell
meanValues = cellfun(@(x) mean(x(:)),ca);

for j=1:size(ca(2))
    for i=1:size(ca(1))
        currentSlice = ca(i,j);
        MeanOfCurrentSlice =  cellfun(@(x) mean(x(:)),currentSlice);
        %here I want to minus the 8 neighbors average grayscale intensity from the currentSlice average grayscale inensity and take the absolute sum 
    end
end

给出每个元素最近邻居的索引的解决方案:

%creation of the index matrix (here a 3x3 matrix)
M = reshape([1:9],3,3);
%subdivide the matrix into 3x3 array
IND = nlfilter(M,[3 3],@(x){x(:)});
%elimination of the value where IND == 0 or IND == index value of the element
for ii = 1:size(M,1)
    for jj = 1:size(M,2)
        IND{ii,jj}(IND{ii,jj}==0|IND{ii,jj}==sub2ind(size(M),ii,jj)) = [];
    end
end

PS: nlfilter是图像处理工具箱的一部分,但是很容易创建自己的类似函数。

步骤1:

M =
   1   4   7
   2   5   8
   3   6   9

步骤2:

IND = 
{
  [1,1] = 
     0   0   0   0   1   2   0   4   5
  [2,1] =
     0   0   0   1   2   3   4   5   6
  [3,1] =
     0   0   0   2   3   0   5   6   0
  [1,2] =
     0   1   2   0   4   5   0   7   8
  [2,2] =
     1   2   3   4   5   6   7   8   9
  [3,2] =
     2   3   0   5   6   0   8   9   0
  [1,3] =
     0   4   5   0   7   8   0   0   0
  [2,3] =
     4   5   6   7   8   9   0   0   0
  [3,3] =
     5   6   0   8   9   0   0   0   0
}

步骤3:

IND =
{
  [1,1] = %neighbors of the value M[1,1] 
     2   4   5
  [2,1] =
     1   3   4   5   6
  [3,1] =
     2   5   6
  [1,2] =
     1   2   5   7   8
  [2,2] =
     1   2   3   4   6   7   8   9
  [3,2] =
     2   3   5   8   9
  [1,3] =
     4   5   8
  [2,3] =
     4   5   6   7   9
  [3,3] =
     5   6   8
}

最新更新