I want to calculate the mean of the neighbors of the pixels in an image. I want to do it for all pixels not only the internal ones. That means for example that I want to calculate the mean of neighbors of the pixels (1,1) or (1,size(image,2)) or (size(image,1),size(image,2)) which means I cannot use a matrix divided by 8 as a kernel for all these pixels because for example neighbors of (1,1) are only 3 not 8. Does anyone have an idea how to do it without using 8 ifs?
Neeta Dsouza answered .
2025-11-20
Let A be your matrix.
% use the help of a bigger matrix
B=nan(size(A)+2);
B(2:end-1,2:end-1)=A;
% pre-define memory for result
result = 0*A;
% calculate!
for i=2:size(A,1)+1,
for j=2:size(A,2)+1,
tmp=B(i-1:i+1,j-1:j+1);
tmp(2,2)=nan;
result(i-1,j-1)=mean(tmp(~isnan(tmp)));
end
end