MATLAB: How to avoid for loops or faster way for compute 3×3 avarage value of an image

blurfilterImage Processing Toolbox

I have a few pixels in an image and I want to calculate the average values ​​of a 3×3 window centred on those pixels in Matlab. It should be noted that not all over the image, just a few desired pixels.
I tried this code and it works but I prefer to avoid using for loops. Is there another way for doing that?
clc
clear
close all
img = imread('cameraman.tif');
x= [10,15,20];
y= [15,25,35];
m=-1;
n=-1;
window = zeros(3,3);
Avg = zeros(max(size(x)),1)
for k=1:max(size(x))
for i = 1:3
for j=1:3
window(i,j) = img(x(k)+m,y(k)+n);
n=n+1;
end
n=-1;
m=m+1;
end
Avg(k) = mean(window,'all')
end

Best Answer

If you're only doing it at 3 locations, don't worry about using for loops. It will be fast.
If you insist on using built-in functions to process the whole image, then...
Use imfilter():
kernel = ones(3)/9;
outputImage = imfilter(grayImage, kernel);
Or you can use conv2():
kernel = ones(3)/9;
outputImage = conv2(double(grayImage), kernel, 'same');
then you can reference outputImage(row, col) for the desired locations. Just be aware that y comes first, not x, so it's outputImage(y(1), x(1)), NOT outputImage(x(1), y(1)).
Related Question