下面的示例以仅考虑图像内部像素的方式处理边缘像素。例如,当程序使用内核计算左上角的平均值时dy = (-1:1)
,dx = (-1:1)
它只考虑左上角及其紧邻的 3 个邻居(右、右下、右),并对这 4 个像素进行平均。
我强烈建议您在 Matlab 的命令窗口中分别测试每一行以查看其行为!
% find image size
imsz = size( myimage );
% initialize output image
imavg = zeros( imsz );
% iterate over pixels
for yy = 1 : imsz(1)
for xx = 1 : imsz(2)
% define rectangle-kernel width
dy = (-1:1); % 1 up, to 1 down and ...
dx = (-1:1); % 1 left, to 1 right from current pixel
% get indexes of image
indy = yy + dy;
indx = xx + dx;
% [!!!] keep indexes that are inside image
indy = indy( indy>0 & indy<=imsz(1) );
indx = indx( indx>0 & indx<=imsz(2) );
% create all the pairings of chosen indexes
[ IY, IX ] = meshgrid( indy, indx );
% take all values of chosen pixels
pixs = myimage( sub2ind(imsz,IY(:),IX(:)) );
% save mean of chosen pixels to the given location
imavg(yy,xx) = mean( pixs );
end
end
您可以从上面的代码中创建函数,并mean_filter.m
使用以下内容创建文件:
function imagv = mean_filter( myimage )
% code from above ...
您可以通过将自己定位在它所在的目录中并执行来从命令窗口调用函数filtered = mean_filter( myimage );
。
您可以使用以下方法重复过滤相同的图像:
filtered_3_times = myimage;
for ii = 1 : 3
filtered_3_times = mean_filter( filtered_3_times );
end