Calculate Average around pixel

3 次查看(过去 30 天)
Dani D
Dani D 2016-3-12
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);

回答(2 个)

Image Analyst
Image Analyst 2016-3-12
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 2016-3-12
do not name a variable "sum"
You should learn to use conv2()

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by