7X7的双边滤波matlab代码
时间: 2024-02-07 17:02:43 浏览: 56
bf.zip_双边滤波
下面是一个7x7的双边滤波的MATLAB代码示例:
```matlab
% 读取图像
img = imread('lena.jpg');
% 双边滤波参数
sigma_r = 50; % 范围标准差
sigma_d = 10; % 像素距离标准差
% 图像双边滤波
filtered_img = bilateral_filter(img, 7, sigma_r, sigma_d);
% 显示结果
subplot(1,2,1), imshow(img), title('原始图像');
subplot(1,2,2), imshow(filtered_img), title('双边滤波后图像');
% 双边滤波函数
function [filtered_img] = bilateral_filter(img, window_size, sigma_r, sigma_d)
% 填充边缘
img = padarray(img, [floor(window_size/2) floor(window_size/2)], 'symmetric');
[m, n] = size(img);
filtered_img = zeros(m, n);
% 计算距离权重矩阵
[X,Y] = meshgrid(-floor(window_size/2):floor(window_size/2), -floor(window_size/2):floor(window_size/2));
G = exp(-(X.^2+Y.^2)/(2*sigma_d^2));
for i = 1+floor(window_size/2):m-floor(window_size/2)
for j = 1+floor(window_size/2):n-floor(window_size/2)
% 取出窗口
window = img(i-floor(window_size/2):i+floor(window_size/2), j-floor(window_size/2):j+floor(window_size/2));
% 计算强度权重矩阵
H = exp(-(window-img(i,j)).^2/(2*sigma_r^2));
% 计算双边滤波结果
filtered_img(i,j) = sum(sum(H.*G.*window))/sum(sum(H.*G));
end
end
% 去除边缘填充
filtered_img = filtered_img(1+floor(window_size/2):m-floor(window_size/2), 1+floor(window_size/2):n-floor(window_size/2));
end
```
在上面的代码中,我们首先读取一个图像,并设置双边滤波参数。然后,我们调用一个名为“bilateral_filter”的函数,该函数将图像作为输入,以及窗口大小、范围标准差和像素距离标准差。该函数使用两个高斯权重矩阵来计算像素之间的权重,然后根据这些权重计算出每个像素的双边滤波结果。最后,我们显示原始图像和双边滤波后的图像。
阅读全文