# 【中值滤波和最邻近插值(matlab)】

Author:HanDi

CSDN@这可真是难为我了

``````%此程序用于练习xls文件读写，中值滤波原理，最临近法插值原理，图像显示
clc
clear
[gray] = xlsread('image_gray.xlsx');  %读入excel数据
%gray = uint8(gray);
[height,weight] = size(gray);  % 读取灰度图像矩阵的维度

%图像矩阵中随机引入高斯噪声
rng('default')
for i = 1:height
for j = 1:weight
gray(i,j) = gray(i,j) + randn;
if gray(i,j) > 255
gray(i,j) = 255;
end
if gray(i,j) <0
gray(i,j) = 0;
end
end
end

%进行中值滤波
result = zeros(height, weight); %生成的结果
prompt = '输入滤波模板尺寸(1到7之间的奇数)： ';
x = input(prompt);
kernel_size = x; % 模板尺寸
expand_size = floor(kernel_size / 2); % 扩展尺寸
kernel = ones(kernel_size, kernel_size); %模板生成
expand_img = double(wextend('2D','zpd', gray, expand_size)); % 在原矩阵的外围填充0，使得中值模板运算后不改变图像大小
for i=1:height
for j=1:weight
mat = expand_img(i:i+kernel_size-1,j:j+kernel_size-1) .* kernel; %取出原矩阵中从(i,j)开始的n行n列元素与模板进行矩阵相乘
mat = mat(:); %展成一维数据
mat = sort(mat); %排序
if mod(kernel_size, 2)==1 %若为奇数 取排序后的中值
result(i,j) = mat((kernel_size*kernel_size+1)/2);
else % 为偶数 取排序后中间两数的均值
result(i,j) = (mat(kernel_size*kernel_size/2) + mat(kernel_size*kernel_size/2+1))/2;
end
end
end

%对图像矩阵进行最邻近插值 扩展为512x512大小
final_result = zeros(512, 512);
alpha_h = height / 512;
alpha_w = weight / 512;
for i = 1:512
for j = 1:512
src_x = round(i * alpha_h);
src_y = round(j * alpha_w);
final_result(i,j) = result(src_x, src_y);
end
end

%将double数据转化为uint8格式
final_result = uint8(final_result);
figure()
subplot(121)
imshow(gray,[]);axis on
title('原始图像')
subplot(122)
imshow(final_result);axis on
title('滤波并插值后512×512后的图像')
%写入excel文件
xlswrite('result.xlsx', final_result);
%存储jpg格式图像
imwrite(final_result,'result.jpg');
``````

THE END