中值滤波matlab代码图像增强
时间: 2024-04-23 15:20:00 浏览: 123
中值滤波是一种常用的图像增强方法,它可以有效地去除图像中的椒盐噪声。下面是一个简单的中值滤波的Matlab代码示例:
```matlab
% 读取原始图像
originalImage = imread('原始图像路径');
% 将图像转换为灰度图像
grayImage = rgb2gray(originalImage);
% 添加椒盐噪声
noisyImage = imnoise(grayImage, 'salt & pepper', 0.05);
% 中值滤波
filteredImage = medfilt2(noisyImage);
% 显示结果
subplot(1, 2, 1);
imshow(noisyImage);
title('添加噪声的图像');
subplot(1, 2, 2);
imshow(filteredImage);
title('中值滤波后的图像');
```
上述代码首先读取原始图像,然后将其转换为灰度图像。接下来,使用`imnoise`函数向灰度图像中添加椒盐噪声,其中`0.05`表示噪声密度为5%。然后,使用`medfilt2`函数对带有噪声的图像进行中值滤波处理。最后,通过`imshow`函数显示添加噪声的图像和中值滤波后的图像。
相关问题
中值滤波 matlab代码
以下是中值滤波的 Matlab 代码:
function [output_image] = median_filter(input_image, filter_size)
%中值滤波函数
%input_image: 输入图像
%filter_size: 滤波器大小
%output_image: 输出图像
%获取输入图像的大小
[row, col] = size(input_image);
%计算滤波器的半径
radius = floor(filter_size / 2);
%初始化输出图像
output_image = zeros(row, col);
%遍历输入图像的每个像素
for i = 1:row
for j = 1:col
%获取当前像素周围的像素值
neighbor_pixels = [];
for m = i-radius:i+radius
for n = j-radius:j+radius
%判断是否越界
if m>=1 && m<=row && n>=1 && n<=col
neighbor_pixels = [neighbor_pixels, input_image(m,n)];
end
end
end
%对邻域像素进行排序
sorted_pixels = sort(neighbor_pixels);
%取中间值作为当前像素的值
output_image(i,j) = sorted_pixels(floor(length(sorted_pixels)/2)+1);
end
end
%将输出图像转换为 uint8 类型
output_image = uint8(output_image);
end
图像二值化中值滤波matlab代码
图像二值化中值滤波是一种常用的图像处理方法,可以有效地去除噪声,提高图像的质量。Matlab中可以使用medfilt2函数实现中值滤波,下面是一个示例代码:
```
I = imread('lena.png'); % 读取图像
I_gray = rgb2gray(I); % 转为灰度图像
I_median = medfilt2(I_gray); % 中值滤波
I_bw = imbinarize(I_median); % 二值化处理
imshow(I_bw); % 显示结果
```
以上代码中,首先通过imread函数读取图像,然后通过rgb2gray函数将图像转为灰度图像。接着使用medfilt2函数对灰度图像进行中值滤波处理,最后使用imbinarize函数将中值滤波后的图像进行二值化处理。最终结果可以使用imshow函数显示。
阅读全文
相关推荐













