Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

image processing - 3x3 Average filter in matlab

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

I call the function as follows:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

Does it change anything?

EDIT: don't forget to reconvert it to uint8!!

filtered_img = uint8(filtered_img);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...