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

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 main(){
    Mat img,img_gray,img_output,img_output2;
    img = imread("/home/v/home.png");

    if (img.empty()){
        cout<<"can not load image"<<endl;
        return -1;
    }

    cvtColor(img,img_gray,COLOR_BGR2GRAY);
    Salt(img_gray,5000);  
    imshow("img_gray",img_gray);

    // 自定义滤波
    int filter_size = 7;
    myfilter(filter_size,img_gray,img_output);

    // opencv 自带滤波
    blur(img_gray,img_output2,Size(filter_size,filter_size));

    imshow("img out 1",img_output);
    imshow("img out 2",img_output2);

    waitKey(0);
    return 0;
}

// 盒式滤波
void myfilter(int filter_size,Mat& img_input,Mat& img_output){
    img_output = img_input.clone();

    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 sum = 0;
            for (int m = -k;m<k+1;m++){
                for (int n=-k;n<k+1;n++)
                {
                    sum += img_input.at<uchar>(i+m,j+n);
                }
            }
            img_output.at<uchar>(i,j) = sum/(filter_size*filter_size);
        }
    }
}

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

你可能感兴趣的:(c++,opencv,c++,opencv,均值算法)