网上的介绍太多了,但绝大多数Matlab代码应用了较多的循环,速度较慢。本代码充分应用矩阵运算,循环次数少,速度极快。
归一化到0到1之间以后,加入零均值,标准差为0.01的高斯白噪声,得到下图
设置
σ
s
=
5
,
σ
r
=
0.2
\sigma_s=5,\sigma_r=0.2
σs=5,σr=0.2,邻域边长
k
=
9
,
k=9,
k=9,得到滤波效果
笔记本CPU为i7-4710HQ,0.1秒,灰度图滤波速度很快,RGB彩色图即进行三次灰度图滤波,耗时乘3。
代码:
clear all
close all
f = imread('滤波原始图.jpg');
[row, col, depth] = size(f);
f = double(f);
f = imnoise(f / 255, 'gaussian', 0, 0.01);
figure, imshow(f);
%% 双边滤波
sigma_s = 5;
sigma_r = 0.2;
tic
result = zeros(row, col, depth);
A_sum = zeros(row, col, depth);
k = 9;
radius = floor(k / 2);
f_padded = padarray(f, [radius radius], 'symmetric');
for l = 1 : depth
for i = -radius : radius
for j = -radius : radius
moving_f = f_padded(i + radius + 1 : end + i - radius, j + radius + 1 : end + j - radius, l);
A = exp(-(i ^ 2 + j ^ 2) / (2 * sigma_s ^ 2) - (moving_f - f) .^ 2 / (2 * sigma_r ^ 2));
result(:, :, l) = result(:, :, l) + moving_f .* A;
A_sum = A_sum + A;
end
end
result(:, :, l) = result(:, :, l) ./ A_sum;
end
result = result * 255;
result = uint8(result);
toc;
figure, imshow(result);