@shaobaobaoer
2018-10-27T15:28:39.000000Z
字数 1401
阅读 969
数字图像处理
matlab
中值滤波
************************************************************************
> File Name: 《数字图像处理》实验三 中值滤波
> Author: 罗天涵
> Student-Id: 16121141
> Mail: luotianhan@126.com
************************************************************************
编写程序,对图象进行中值滤波,并与实现相同功能的 Matlab 函数进行运算速度比较.
函数用法
B = medfilt2(A,[m n])
中值滤波是将周围像素和中心像素排序以后,取中值。可以看如下的例子
对于元素 125,其周围元素为
124 126 126
120 150 125
115 119 123
将内容排序得到长度为9的行向量。
115,119,120,123,124,125,126,127,150
则中间元素a[4]为124。此时将 150 替换为 124。对于外部的框框,需要用0填充。然后计算中值。对于 上述矩阵通过中值滤波后得到的内容是
0 124 0
119 124 123
0 119 0
由于matlab 不是很会用。所以先记录一些小技巧。
矩阵扩展
在中值滤波中,需要扩展外圈。一番学习之后,我写了个这样的padding fuction。
我们用 算法的角度思考一下。这个矩阵向上与向下扩展的数目应该是
padding(1,:) = zeros([1 2+w])
for i = 2: 3+1
padding(i,:) = [zeros(1) test(i-1,:) zeros(1)]
end
padding(3+2,:) = zeros([1 2+w])
更加复杂的矩阵扩展
算法实现
正确性校验
test =
124 126 126
120 150 125
115 119 123
>> zhongzhi(test)
ans =
0 124 0
119 124 123
0 119 0
>> medfilt2(test)
ans =
0 124 0
119 124 123
0 119 0
% 读取一张图片
>> test2 = imread('proxy.png');
>> test2 = rgb2gray(test2);
>> test2_system = medfilt2(test2);
>> test2_myfunc = zhongzhi(test2);
>> all(test2_myfunc == test2_system_double);
>> 可以发现数据都是1,验证成功
时间校验
matlab 推荐的程序时间运行函数如下所示
>> tic
%代码块
toc
%disp(['运行时间: ',num2str(toc)]);
事实证明,自己写的函数运行速度感人.
test 是一张大小为 2509KB 的rgb PNG 图片。转化成灰度图像后其他大小为 2967 * 3968 的矩阵
>> size(test)
ans =
2976 3968
>> tic
medfilt2(test);
toc
disp(['运行时间: ',num2str(toc)]);
运行时间: 0.14249
>> tic
zhongzhi(test);
toc
disp(['运行时间: ',num2str(toc)]);
运行时间: 99.2464