matlab图像多种滤波程序代码
时间: 2023-08-11 21:08:45 浏览: 99
基于Matlab的各种图像滤波算法代码
以下是 MATLAB 中常用的几种图像滤波程序代码:
1. 均值滤波:
```matlab
function [filtered_img] = meanFilter(img, mask_size)
% img: 输入图像
% mask_size: 滤波器大小
% filtered_img: 输出图像
% 均值滤波器
mask = ones(mask_size) / (mask_size * mask_size);
% 填充边界
img = padarray(img,[floor(mask_size/2) floor(mask_size/2)],'replicate');
% 滤波
[rows, cols] = size(img);
filtered_img = zeros(rows, cols);
for i = 1:rows-mask_size+1
for j = 1:cols-mask_size+1
temp = img(i:i+mask_size-1, j:j+mask_size-1);
filtered_img(i+floor(mask_size/2), j+floor(mask_size/2)) = sum(sum(temp .* mask));
end
end
% 截断
filtered_img = uint8(filtered_img(floor(mask_size/2):end-floor(mask_size/2), floor(mask_size/2):end-floor(mask_size/2)));
end
```
2. 中值滤波:
```matlab
function [filtered_img] = medianFilter(img, mask_size)
% img: 输入图像
% mask_size: 滤波器大小
% filtered_img: 输出图像
% 填充边界
img = padarray(img,[floor(mask_size/2) floor(mask_size/2)],'replicate');
% 滤波
[rows, cols] = size(img);
filtered_img = zeros(rows, cols);
for i = 1:rows-mask_size+1
for j = 1:cols-mask_size+1
temp = img(i:i+mask_size-1, j:j+mask_size-1);
filtered_img(i+floor(mask_size/2), j+floor(mask_size/2)) = median(temp(:));
end
end
% 截断
filtered_img = uint8(filtered_img(floor(mask_size/2):end-floor(mask_size/2), floor(mask_size/2):end-floor(mask_size/2)));
end
```
3. 高斯滤波:
```matlab
function [filtered_img] = gaussianFilter(img, sigma)
% img: 输入图像
% sigma: 高斯核标准差
% filtered_img: 输出图像
% 构造高斯核
mask_size = 2 * ceil(3 * sigma) + 1;
[x, y] = meshgrid(-(mask_size-1)/2:(mask_size-1)/2, -(mask_size-1)/2:(mask_size-1)/2);
mask = exp(-(x.^2+y.^2)/(2*sigma^2));
mask = mask / sum(mask(:));
% 填充边界
img = padarray(img,[floor(mask_size/2) floor(mask_size/2)],'replicate');
% 滤波
[rows, cols] = size(img);
filtered_img = zeros(rows, cols);
for i = 1:rows-mask_size+1
for j = 1:cols-mask_size+1
temp = img(i:i+mask_size-1, j:j+mask_size-1);
filtered_img(i+floor(mask_size/2), j+floor(mask_size/2)) = sum(sum(temp .* mask));
end
end
% 截断
filtered_img = uint8(filtered_img(floor(mask_size/2):end-floor(mask_size/2), floor(mask_size/2):end-floor(mask_size/2)));
end
```
阅读全文