【c++|opencv】二、灰度变换和空间滤波---5.中值滤波

every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog

0. 前言

1. 中值滤波

#include
#include
#include"Salt.h"


using namespace cv;
using namespace std;

void myfilter(int filter_size,Mat& img_input,Mat& img_output);
int mysort(Mat& sortarray,int filter_size);


int main(){
    Mat img,img_gray,img_output,img_output2;
    img = imread("/home/v/home.png");
    if (img.empty()){
        cout<<"could not load image"<<endl;
        return -1;
    }
 
    imshow("img",img);
    cvtColor(img,img_gray,COLOR_BGR2GRAY);
    Salt(img_gray,1000);
    imshow("img gray",img_gray);

    //OpenCV自带滤波器
    int a=7;
    medianBlur(img_gray,img_output,a);
    imshow("medianBlur",img_output);

    // 自编函数
    myfilter(a,img_gray,img_output2);
    imshow("myfilter",img_output2);

    waitKey(0);
    return 0;
}

void myfilter(int filter_size,Mat& img_input,Mat& img_output){
    img_output = img_input.clone();
    Mat sortarray(1,filter_size*filter_size,CV_8U);
    int k = (filter_size-1)/2;

    for (int i=k;i<img_input.rows-k;i++){
        for (int j=k;j<img_input.cols-k;j++){
            int h = 0;
            for (int m=-k;m<=k;m++){
                for (int n=-k;n<=k;n++){
                    sortarray.at<uchar>(h) = img_input.at<uchar>(i+m,j+n);
                    h++;
                }
            }
            img_output.at<uchar>(i,j) = mysort(sortarray,filter_size*filter_size);
        }
    }
}

// 找中值
int mysort(Mat& sortarray,int filter_size){

    int exchange;
    int m;
    for (int i=1;i<=filter_size-1;i++){
        for (int j=1;j<filter_size-1;j++){
            if (sortarray.at<uchar>(j-1) > sortarray.at<uchar>(j)){
                exchange = sortarray.at<uchar>(j-1);
                sortarray.at<uchar>(j-1) = sortarray.at<uchar>(j);
                sortarray.at<uchar>(j) = exchange;
            }
        }
    }
    return sortarray.at<uchar>((filter_size+1)/2);
}

【c++|opencv】二、灰度变换和空间滤波---5.中值滤波_第1张图片

你可能感兴趣的:(c++,opencv,c++,opencv,开发语言)