【问题标题】:Average filter Matlab平均滤波器 Matlab
【发布时间】:2018-11-15 17:39:07
【问题描述】:

我已经编写了 3x3 平均滤波器。它工作正常,但它显示相同的输出图像三次而不是一次。如何解决问题?

代码是

function [filtr_image] = avgFilter(noisy_image)

    [x,y] = size(noisy_image);
    filtr_image = zeros(x,y);
    for i = 2:x-1
        for j =2:y-1
            sum = 0;
            for k = i-1:i+1
                for l = j-1:j+1
                    sum = sum+noisy_image(k,l);
                end
            end
            filtr_image(i,j) = sum/9.0;
           filtr_image = uint8(filtr_image);

        end
    end

end

提前致谢

【问题讨论】:

标签: matlab image-processing


【解决方案1】:

最有可能发生的情况是,当代码专门用于灰度时,您提供的是 彩色 图像。你看到“三”的原因是因为当你这样做是为了分配你的输出过滤图像:

[x,y] = size(noisy_image)

如果您有 3D 矩阵,size 报告的列数将为y = size(noisy_image,2)*size(noisy_image,3);。因此,当您遍历图像中的每个像素时,按列主要顺序,每个平面将彼此并排放置。您应该做的是将图像从 RGB 转换为灰度或分别过滤每个平面。

此外,您在循环中执行了不必要的强制转换。只需在循环之外执行一次即可。

选项 #1 - 按平面过滤

function [filtr_image] = avgFilter(noisy_image)
[x,y,z] = size(noisy_image);
filtr_image = zeros(x,y,z,'uint8');
for a = 1 : z
    for i = 2:x-1
        for j =2:y-1
            sum = 0;
            for k = i-1:i+1
                for l = j-1:j+1
                    sum = sum+noisy_image(k,l,a);
                end
            end
            filtr_image(i,j,a) = sum/9.0;
        end
    end
 end
end

然后你可以这样称呼它:

filtr_image = avgFilter(noisy_image);

选项 #2 - 转换为灰度

filtr_image = avgFilter(rgb2gray(noisy_image));

小提示

您正在使用sum 作为变量。 sum 是 MATLAB 中的一个实际函数,你会用你的变量掩盖这个函数。如果您以后有其他依赖于sum 的函数,这将产生意想不到的后果。

【讨论】:

    【解决方案2】:

    我不明白为什么您的代码会重复该图像(除非它是由整数溢出引起的模式:/),但这里有一些建议:

    如果你想使用循环,至少去掉内部循环:

    [x,y] = size(noisy_image);
    filtr_image = zeros(x,y);
    for i = 2:x-1
        for j =2:y-1
            % // you could do this in 1 line if you use mean2(...) instead
            sub = noisy_image(i-1:i+1, j-1:j+1);
            filtr_image = uint8(mean(sub(:))); 
        end
    end
    

    但是你知道卷积吗? Matlab 有一个内置函数:

    filter = ones(3)/9;
    filtr_image = uint8(conv2(noisy_image, filter, 'same'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多