Calculate Average around pixel
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Image Analyst
am 12 Mär. 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.
0 Kommentare
Walter Roberson
am 12 Mär. 2016
do not name a variable "sum"
You should learn to use conv2()
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!