3x3 matlab中的平均过滤器 [英] 3x3 Average filter in matlab
问题描述
我编写了使用3x3平均滤波器来平滑图像的代码,但是输出很奇怪,几乎都是黑色的。这是我的代码。
I've written code to smooth an image using a 3x3 averaging filter, however the output is strange, it is almost all black. Here's my code.
function [filtered_img] = average_filter(noisy_img)
[m,n] = size(noisy_img);
filtered_img = zeros(m,n);
for i = 1:m-2
for j = 1:n-2
sum = 0;
for k = i:i+2
for l = j:j+2
sum = sum+noisy_img(k,l);
end
end
filtered_img(i+1,j+1) = sum/9.0;
end
end
end
我调用函数如下:
img=imread('img.bmp');
filtered = average_filter(img);
imshow(uint8(filtered));
到目前为止我在代码逻辑中看不到任何错误,如果有人,我会很感激可以发现问题。
I can't see anything wrong in the code logic so far, I'd appreciate it if someone can spot the problem.
推荐答案
假设你正在使用灰度图像,你应该用以下内容替换内部的两个for循环: / p>
Assuming you're working with grayscal images, you should replace the inner two for loops with :
filtered_img(i+1,j+1) = mean2(noisy_img(i:i+2,j:j+2));
它会改变什么吗?
编辑:别忘了将它重新转换为uint8 !!
don't forget to reconvert it to uint8!!
filtered_img = uint8(filtered_img);
编辑2:你的代码无效的原因是因为总和
的饱和度为255,即uint8的上限。 mean
似乎可以防止发生这种情况
Edit 2: the reason why it's not working in your code is because sum
is saturating at 255, the upper limit of uint8. mean
seems to prevent that from happening
这篇关于3x3 matlab中的平均过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!