3×3邻域滤波器matlab实现代码
时间: 2023-08-12 17:10:26 浏览: 69
以下是一个基于 MATLAB 的 3x3 邻域滤波器的实现代码:
```matlab
function output = neighbor_filter(input)
% input: 输入图像
% output: 输出图像
% 获取输入图像的大小
[m, n] = size(input);
% 初始化输出图像
output = zeros(m, n);
% 循环遍历图像像素
for i = 2:m-1
for j = 2:n-1
% 获取3x3邻域
neighbor = input(i-1:i+1, j-1:j+1);
% 对邻域求平均值
avg_neighbor = mean(neighbor(:));
% 将平均值赋值给输出图像对应位置
output(i, j) = avg_neighbor;
end
end
end
```
使用方法:
将以上代码保存为 `neighbor_filter.m` 文件,并在 MATLAB 中运行以下代码:
```matlab
% 读取输入图像
input = imread('input.jpg');
% 灰度化处理
input_gray = rgb2gray(input);
% 调用 3x3 邻域滤波器
output = neighbor_filter(input_gray);
% 显示输出图像
imshow(output, [])
```
其中 `input.jpg` 是你需要进行滤波的原始图像。
相关问题
中点滤波器matlab代码
以下是中点滤波器的 Matlab 代码:
```matlab
function [outputImage] = medianFilter(inputImage, kernelSize)
% Convert the input image to double for image processing operations
inputImage = im2double(inputImage);
% Get the dimensions of the input image
[rows, cols] = size(inputImage);
% Create an output image of the same size as the input image
outputImage = zeros(rows,cols);
% Calculate the padding required for the given kernel size
padSize = floor(kernelSize/2);
% Pad the input image with zeros on all sides
paddedImage = padarray(inputImage,[padSize padSize],0);
% Loop through each pixel in the input image
for i = 1:rows
for j = 1:cols
% Extract the neighborhood around the current pixel
neighborhood = paddedImage(i:i+2*padSize, j:j+2*padSize);
% Convert the neighborhood into a vector and sort it
neighborhoodVec = neighborhood(:);
sortedVec = sort(neighborhoodVec);
% Get the median value of the sorted vector
medianVal = sortedVec(floor(length(sortedVec)/2)+1);
% Store the median value in the output image
outputImage(i,j) = medianVal;
end
end
% Convert the output image back to the original class of the input image
outputImage = cast(outputImage, class(inputImage));
end
```
这个函数实现了一个中点滤波器,它可以应用于任何大小的输入图像和卷积核。该函数首先将输入图像转换为 double 类型,然后对每个像素执行以下操作:
- 提取围绕当前像素的邻域
- 将邻域转换为向量并对其进行排序
- 获取排序向量的中位数,并将其存储在输出图像中
最后,输出图像被转换回与输入图像相同的类型。
双边滤波器 matlab代码
function output = bilateralFilter(input, sigma_s, sigma_r)
% 双边滤波器函数
% input: 输入图像
% sigma_s: 空间域标准差
% sigma_r: 强度域标准差
% output: 输出图像
[m, n] = size(input);
output = zeros(m, n);
% 计算空间域权值
[X, Y] = meshgrid(1:n, 1:m);
G = exp(-((X - Y).^2 + (X - Y).^2) / (2 * sigma_s^2));
for i = 1:m
for j = 1:n
% 计算强度域权值
% 以(i, j)为中心,取邻域
i_min = max(i - 2 * sigma_s, 1);
i_max = min(i + 2 * sigma_s, m);
j_min = max(j - 2 * sigma_s, 1);
j_max = min(j + 2 * sigma_s, n);
patch = input(i_min:i_max, j_min:j_max);
H = exp(-(patch - input(i, j)).^2 / (2 * sigma_r^2));
% 计算滤波后的灰度值
W = G(i_min:i_max, j_min:j_max) .* H;
output(i, j) = sum(W(:) .* patch(:)) / sum(W(:));
end
end
end