Calculate Average around pixel

조회 수: 3 (최근 30일)
Dani D
Dani D 2016년 3월 12일
답변: Image Analyst 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