数字图像处理 中值滤波 均值滤波 C++ opencv

  • Z9_226147
    了解作者
  • 29.1MB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-05-08 10:22
    上传日期
数字图像处理,用C++语言,自己编写了中值滤波器以及均值滤波器,并和opencv自带函数对比,可直接运行。
lvboqi1.zip
内容介绍
#include<iostream> #include<opencv2/imgproc.hpp> #include<opencv2/highgui.hpp> #include<ctime> using namespace cv; using namespace std; //椒盐噪声 void salt(Mat &input, int num) { int i, j; srand(time(NULL)); for (int x=0;x<num;++x) { i = rand() % input.rows; j = rand() % input.cols; input.at<uchar>(i, j) = 255; } } //均值滤波 void junzhi(const Mat &input, Mat &output) { //访问像素点 for (int i=1;i<input.rows; ++i) for (int j=1;j<input.cols;++j) { if ( (i-1>= 0) && (j-1)>= 0 &&(i+1)<input.rows &&(j+1)<input.cols ) {//边缘不处理 output.at<uchar>(i, j) = (input.at<uchar>(i, j) + input.at<uchar>(i - 1, j - 1) + input.at<uchar>(i - 1, j) + input.at<uchar>(i, j - 1) + input.at<uchar>(i - 1, j + 1) + input.at<uchar>(i + 1, j - 1) + input.at<uchar>(i + 1, j + 1) + input.at<uchar>(i, j + 1) + input.at<uchar>(i + 1, j)) / 9; } else {//边缘 output.at<uchar>(i, j) = input.at<uchar>(i, j) ; } } } //求九个数的中值 uchar Median(uchar n1,uchar n2, uchar n3, uchar n4, uchar n5, uchar n6, uchar n7, uchar n8, uchar n9) { uchar arr[9]; arr[0] = n1; arr[1] = n2; arr[2] = n3; arr[3] = n4; arr[4] = n5; arr[5] = n6; arr[6] = n7; arr[7] = n8; arr[8] = n9; for (int gap = 9 / 2; gap > 0; gap /= 2) for (int i = gap; i < 9; ++i) for (int j = i - gap; j >= 0 && arr[j] > arr[j + gap]; j -= gap) swap(arr[j], arr[j + gap]); return arr[4]; } //中值滤波 void zhongzhi(const Mat &input, Mat &output) { Mat out(input.size(), input.type()); for (int i = 0; i < input.rows; ++i) for (int j = 0; j < input.cols; ++j) { if ((i - 1) > 0 && (i + 1) < input.rows && (j - 1) > 0 && (j + 1) < input.cols) { out.at<uchar>(i, j) = Median( input.at<uchar>(i, j), input.at<uchar>(i + 1, j + 1),input.at<uchar>(i + 1, j), input.at<uchar>(i, j + 1), input.at<uchar>(i + 1, j - 1),input.at<uchar>(i - 1, j + 1), input.at<uchar>(i - 1, j), input.at<uchar>(i, j - 1),input.at<uchar>(i - 1, j - 1) ); } else out.at<uchar>(i, j) = input.at<uchar>(i, j); } out.copyTo(output); } int main() { Mat img = imread("picture2.jpg"); imshow("彩色",img); cvtColor(img, img, COLOR_BGR2GRAY); imshow("原图", img); //加噪声 Mat salt_img; img.copyTo(salt_img); salt(salt_img, 1000); imshow("噪声图像",salt_img); Mat img1(img.size(), img.type()); Mat img2 , img3, img4; junzhi(salt_img, img1); imshow("自编均值滤波", img1); blur(salt_img, img2, Size(3, 3)); imshow("openCV自带的均值滤波", img2); zhongzhi(salt_img, img3); imshow("自编中值滤波处理后", img3); medianBlur(salt_img,img4, 3); imshow("openCV自带的中值滤波", img4); waitKey(0); return 0; }
评论
    相关推荐