双边滤波的matlab程序
时间: 2023-10-31 16:36:32 浏览: 36
下面是一个简单的双边滤波的Matlab程序示例:
img = imread('image.jpg');
% 设定双边滤波的参数
window_size = 5;
sigma_r = 25;
sigma_d = 10;
% 为输入图像加上噪声
noisy_img = imnoise(img,'salt & pepper',0.02);
% 双边滤波
smooth_img = bilateral_filter(noisy_img, window_size, sigma_r, sigma_d);
% 显示结果图像
figure, subplot(121), imshow(noisy_img), title('Noisy Image');
subplot(122), imshow(smooth_img), title('Smooth Image');
function [smooth_img] = bilateral_filter(img, window_size, sigma_r, sigma_d)
% 取得图像的大小
[height, width, channels] = size(img);
% 设定空间权重矩阵
[X,Y] = meshgrid(1:window_size, 1:window_size);
space_weights = exp(-(X.^2 + Y.^2)/(2*sigma_d^2));
% 对每个像素点进行双边滤波
smooth_img = zeros(height, width, channels);
for i = 1:height
for j = 1:width
% 取得当前像素点周围的窗口
row_min = max(i-window_size, 1);
row_max = min(i+window_size, height);
col_min = max(j-window_size, 1);
col_max = min(j+window_size, width);
window = img(row_min:row_max, col_min:col_max, :);
% 计算颜色权重矩阵
color_weights = exp(-(window-img(i,j,:)).^2/(2*sigma_r^2));
% 计算空间权重和颜色权重的乘积
weights = color_weights.*space_weights((row_min:row_max)-i+window_size+1, (col_min:col_max)-j+window_size+1, :);
% 对权重矩阵和图像窗口进行加权平均
sum_weights = sum(weights, [1,2]);
normalized_weights = weights./(sum_weights+eps);
weighted_window = window.*normalized_weights;
sum_weighted_window = sum(weighted_window, [1,2]);
% 将结果赋给平滑后的图像
smooth_img(i,j,:) = sum_weighted_window;
end
end
end