Calculate Average around pixel

11 visualizaciones (últimos 30 días)
Dani D
Dani D el 12 de Mzo. de 2016
Respondida: Image Analyst el 12 de Mzo. de 2016
Hello, I want calculate average 3*3 around a pixel. but in my code i have a problem. Please view code and help me . Thanks
clear all;
close all;
clc
I=imread('cameraman.tif');
[m , n] = size(I);
newI= uint8(ones(size(I)));
figure;
for i = 1:m
for j = 1:n
p = 0;
sum = 0;
x = i ; y= j;
if (x-1 >= 1 && y-1 >= 1)
p = p+1;
sum = sum + I(x-1,y-1);
end
if (x-1 >=1 )
p = p +1;
sum = sum + I(x-1,y);
end
if (x-1 >=1 && y+1 <=n)
p = p +1;
sum = sum + I(x-1,y+1);
end
if ( y-1 >=1)
p = p +1;
sum = sum + I(x,y-1);
end
if ( y+1 <=n)
p = p +1;
sum = sum + I(x,y+1);
end
if (x+1 <=m && y-1 >=1)
p = p +1;
sum = sum + I(x+1,y-1);
end
if (x+1 <=m )
p = p +1;
sum = sum + I(x+1,y);
f = I(x+1,y);
end
if (x+1 <=m && y+1 <=n)
p = p +1;
sum = sum + I(x+1,y+1);
end
newI(i,j) = uint8(sum/p);
end
p = 0;
sum = 0;
end
imshow(newI);

Respuestas (2)

Image Analyst
Image Analyst el 12 de Mzo. de 2016
Yes, that's a mess. Like Walter said, use conv2(), or imfilter():
windowSize = 3;
kernel = ones(windowSize);
kernel = kernel / sum(kernel(:));
localAverageImage = conv2(double(grayImage), kernel, 'same');
Now just index any location to get the mean in a square window there. If you want non-square windows, then make some of the elements in the kernel zero to achieve whatever shape you want, like a circle or cross of whatever, but do that before you divide by the sum of kernel otherwise you'll be shifting the average to some other level.

Walter Roberson
Walter Roberson el 12 de Mzo. de 2016
do not name a variable "sum"
You should learn to use conv2()

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by