自編中值濾波

2021-10-14 07:44:02 字數 4639 閱讀 2046

自編乙個中值濾波函式mymedfilt2(a, [m,n]),實現matlab中的medfilt2函式的功能(邊緣採用複製的方式);對自選的灰度影象加上椒鹽雜訊,用自編的函式對其進行中值濾波。

// an highlighted block

clear;clc;

img=

imread

('rice.png');

n=3;m=4

;str=

'sample'

;%str=

'zeros'

;[img1,img2,img3]

=mymedfilt2

(img,n,m,str)

;subplot

(221),

imshow

(img)

,title

('原圖'

)subplot

(222),

imshow

(img1)

,title

('加入椒鹽雜訊後'

)subplot

(223),

imshow

(img2)

,title([

num2str

(n),

'x',

num2str

(m),

'自定中值濾波'])

subplot

(224),

imshow

(img3)

,title([

num2str

(n),

'x',

num2str

(m),

'原有中值濾波'

])

// an highlighted block

function[j

,x2,x3]

=mymedfilt2

(img, n, m, str)

% clear;clc;

% str=

'sample'

;% img=

imread

('rice.png');

% n=

3;m=3;

%if(strcmp

(str,

'sample')==

strcmp

(str,

'zeros'))

%return

% endj=

imnoise

(img,

'salt & pepper'

,0.04);

tend_img=img;

[h,w]

=size

(img);if

(mod

(n,2)~

=mod

(m,2))

%若模板行與列分別為偶數和奇數

if(strcmp

(str,

'sample'))

for i=1:

round

((n/2)

)-1%複製填充

tend_img=

[img(1

:h);tend_img]

; end

for i=

1:n/

2

tend_img=

[tend_img;

img(end,:)

];end[h,w]

=size

(tend_img)

;for i=1:

round

((m/2)

)-1

tend_img=

[tend_img(1

:h,1

),tend_img]

;end

for j=

1:m/

2

tend_img=

[tend_img,

tend_img(:

,end)];

end else

for i=1:

(n/2)-

1%零填充

tend_img=

[zeros(1

,h);tend_img]

; end

for i=

1:n/

2

tend_img=

[tend_img;

zeros(1

,h)]

; end

[h,w]

=size

(tend_img)

;for i=1:

(m/2)-

1

tend_img=

[zeros

(h,1

),tend_img]

; end

for j=

1:m/

2

tend_img=

[tend_img,

zeros

(h,1)]

; end

endelseif

(strcmp

(str,

'sample'))

%奇數 複製填充

for i=

1:n/

2

tend_img=

[img(1

,:);tend_img;

img(end,:)

];endfor j=

1:m/

2

tend_img=

[tend_img(:

,1),tend_img,

tend_img(:

,end)];

endelseif

(strcmp

(str,

'zeros'))

%奇數 零填充

for i=

1:n/

2

tend_img=

[zeros(1

,h);tend_img;

zeros(1

,h)]

; end

[r,h]

=size

(tend_img)

;for j=

1:m/

2

tend_img=

[zeros

(r,1

),tend_img,

zeros

(r,1)]

; end

end[h,w]

=size

(tend_img)

;x1=

double

(tend_img)

;for i=

1:h-n+

1for j=

1:w-m+

1 c=

x1(i:i+

(n-1

),j:j+

(m-1))

;%取模板覆蓋影象

c=c(

:);%轉變為列

mid=

median

(c);

%取中值

x2(i,j)

=round

(mid)

;%四捨五入

endendx2=

uint8

(x2)

;x3=

medfilt2

(img,

[n,m]);

%原中值濾波函式

end%

img(

1:end+

3,end+

1:end+3)

=0;% clc

%fori=

248:

256%a=

[tend_img(2

:4,i

:i+2

)]% mid=

round

(median(a

(:))

)% end

原圖:

加入雜訊後:

自定義中值濾波:

自帶中值濾波:

中值濾波測試

小白又來記個筆記 當資料讀取之後 就開始對資料進行預處理 預處理中比較重要的乙個部分就是濾波 因為實際工況下得到的訊號肯定是混有雜訊的 從簡單的開始說起 比較簡單的濾波操作是中值濾波 中值濾波對緩慢變化的訊號中由於偶然因素引起的脈衝干擾有良好的濾波效果 這裡我用了師兄給我的實驗室測得訊號 沒有雜訊 ...

中值濾波(matlab)

中值濾波 是一種非線性數字濾波器技術,用於降噪。理解 去乙個模板,可為3 3,5 5,n n 每次從影象中取出模板大小的矩陣,將所有元素排序,取中間值放入木板的中心位置,再還原到原圖中,以此類推掃瞄整個影象。可先對影象進行填充,填充函式 b padarray a,padsize,padval,dir...

Python OpenCV中值濾波

import cv2 as cv import numpy as np def rgb2gray img h img.shape 0 w img.shape 1 img1 np.zeros h,w np.uint8 for i in range h for j in range w img1 i,j...