MATLAB: I use this code for averaging the neighbourhood but i got 3 time enlarged image any one help me

averaged neibconvolutionImage Processing Toolboximfilter

function [ img ] = avg_neighbourhood( image, n )
%AVG_NEIGHBOURHOOD Blurs the image by replacing each pixel by the average of its
% (2*n+1) x (2*n+1) neighbourhood. Pixels out of the image's range
clc; close all;clear all;
[F path]=uigetfile('*.jpg;*.tif;*.png;*.gif','Select an image');
F=strcat(path,F);
image= imread(F);
n=4
% 'n' must be a non-negative integer
if ( n<0 | floor(n)~=n )
error('Invalid n');
end %if
% image's size:
[rows, cols] = size(image);
% Create a matrix with the same dimensions
img = zeros(rows, cols);
% for each pixel...
for i = 1 : rows
for j = 1 : cols
% make sure its nxn neighbourhood wil not reach out
% of the image's range!
i_lower = max([1, i-n]);
i_upper = min([rows, i+n]);
j_lower = max([1, j-n]);
if true
% code
end
j_upper = min([cols, j+n]);
% Sum up all valid pixels of the nxn neighbourhood...
img(i, j) = sum( sum( image(i_lower : i_upper,j_lower : j_upper) ) );
% And divide by the number of the neighbourhood's valid pixels:
img(i, j) = img(i, j) / ((i_upper - i_lower + 1)*(j_upper - j_lower + 1));
end % for j
end % for i
% Finally round the pixels to integer values:
img = uint8( floor( img + 0.5 ) );
figure
imshow(img)
end

Best Answer

If by three times larger you mean that your result image has three times the columns (but the same number of rows), that would be because your code assumes the image is greyscale (2D matrix) but you've loaded a RGB image (3D matrix). jpg images in particular are often RGB.
To ensure you're creating an image the correct size:
[rows, cols, channels] = size(image);
img = zeros(size(image));
You need to adjust your loop to cope for cases when channels > 1.
You also probably need to adjust your code for cases when the image is indexed as averaging palette indices is meaningless. Note that GIF images, which your code explicitly accepts are always indexed.
Your code also assumes that the input image is always of type uint8. This is absolutely not guaranteed with the image types you accept.
Note that a much simpler way of averaging the pixels of an image over a sliding window is with a convolution, which requires just one line of code:
windowsize = [3 3]; %3 rows * 3 columns
img = convn(image, ones(windowsize)/prod(windowsize), 'valid'); %for greyscale images you can use conv2 instead of convn
Finally, note that you shouldn't use image as a variable name as it's already the name of a matlab function.