均值濾波器 中值濾波器


一、均值濾波。

1.取3*3的模板,取覆蓋像素的平均值。(需要賦值,所以選取奇數的模板,方便找中間的像素點)

2.將平均值,賦值給3*3模板的中間的像素值。(需要設計滑動窗口,依次遍歷並賦值)

3.處理后邊界的像素值不變。

 1 #include<opencv2\opencv.hpp>
 2 #include<iostream>
 3 
 4 using namespace cv;
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     Mat image=imread("E:/photo/17.jpg",0);
10     imshow("photo",image);
11     int r=image.rows;
12     int c=image.cols;
13     Mat image1(r, c, CV_8UC1, Scalar(0));   // 定義空圖像
14     for(int i=1;i<r-1;i++)
15     {
16         for(int j=1;j<c-1;j++)
17         {
18             uchar S[121];
19             int t=0;
20             for(int k=i-1;k<i+2;k++)
21           {
22                 for(int l=j-1;l<j+2;l++)
23                 {
24                     S[t]=image.at<uchar>(k,l);
25                     t++;
26                     //cout<<S[t]<<",,,";
27 
28                 }
29 
30                         for (t=0; t<9;t++)
31                         {
32                             if(S[t]>S[t+1])
33                             {
34                                 int temp=0;
35                                 temp = S[t];
36                                 S[t] = S[t+1];
37                                 S[t+1] = temp;
38                                 image1.at<uchar>(i,j)=S[4];
39                             }
40                          }
41             }
42 
43             }
44    }
45    imshow("Laterphoto",image1);
46    waitKey(0);
47    return 0;
48 }

二、中值濾波。

原理同上,均值是求平均值進行賦值,中值是找到像素點的中間的像素值進行賦值,需要進行排序。

 1 #include<opencv2\opencv.hpp>
 2 #include<iostream>
 3 using namespace cv;
 4 using namespace std;
 5 int main()
 6 {
 7     Mat image=imread("E:/photo/1.jpg",0);
 8     imshow("photo",image);
 9     int r=image.rows;
10     int c=image.cols;
11     int sum=0;
12     int s;
13     Mat image1(r, c, CV_8UC1, Scalar(0));   // 定義空圖像
14     for(int i=1;i<r-1;i++)
15     {
16         for(int j=1;j<c-1;j++)
17             {
18             sum=0;
19             for(int k=i-1;k<i+2;k++)
20                 {
21                 for(int l=j-1;l<j+2;l++)
22                     {
23                         sum+=image.at<uchar>(k,l);
24                         //cout<<sum<<",,";
25                         s=cvRound(sum/9);
26                     }
27                 }
28 
29             //cout<<s<<",,";
30             image1.at<uchar>(i-1,j-1)=s;
31             }
32     }
33    imshow("Laterphoto",image1);
34    waitKey(0);
35 }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM