我已将图像分成多个子图像。现在我想比较每个子图像与其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
答案 0 :(得分:1)
为您提供每个元素的最近邻居索引的解决方案:
%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
}