Calculate Average around pixel
3 次查看(过去 30 天)
显示 更早的评论
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);
0 个评论
回答(2 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!