#include<stdlib.h> #include<opencv2/opencv.hpp> #include<opencv2/core/core.hpp> #include<iostream> #define LINEAR_X 0 #define SIZE 5 #define PI 3.1415926 usingnamespace cv; voidthreshold(Mat input,Mat &output,int var) { int rows = output.rows; int cols = output.cols; for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) { int p=input.at<uchar>(i,j); if(p>var) output.at<uchar>(i,j)=255; else output.at<uchar>(i,j)=0; } } } //////////////////////滤波////////////////// // 空域高斯滤波器函数 voidGaussian(Mat input, Mat &output, double sigma){ double weight;//权重 double sum = 0; double Gaussian_Temp[SIZE][SIZE] = {0};//模板 weight = (2*PI*sigma*sigma); for(int i =0;i <SIZE;i++) { for(int j = 0;j < SIZE;j++) { int x = i - SIZE/2; int y = j - SIZE/2; Gaussian_Temp[i][j] =exp(-(x*x+y*y)/(2.0*sigma*sigma))/weight; sum += Gaussian_Temp[i][j]; } }
for(int i = 0; i < SIZE;i++) { for(int j = 0;j < SIZE;j++) { Gaussian_Temp[i][j] = Gaussian_Temp[i][j]/sum;//归一化处理 } } //卷积 int rows = output.rows; int cols = output.cols; for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) { for(int k=0;k<SIZE;k++) for(int t=0;t<SIZE;t++) { int x=i+k-SIZE/2; int y=j+t-SIZE/2; if(x<0||y<0||x>=rows||y>=cols)continue; int p=input.at<uchar>(x,y); output.at<uchar>(i,j)+=p*Gaussian_Temp[k][t]; } if(output.at<uchar>(i,j)>255)output.at<uchar>(i,j)=255; if(output.at<uchar>(i,j)<0)output.at<uchar>(i,j)=0; } }
} // 膨胀函数 voidDilate(Mat Src, Mat Tem, Mat Dst){ int rows = Dst.rows; int cols = Dst.cols; int t_rows = Tem.rows; int t_cols = Tem.cols; for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) { int p = Src.at<uchar>(i,j); if(p == 0)continue; for(int k=0;k<t_rows;k++) for(int t=0;t<t_cols;t++) { int x=i+k; int y=j+t; if(x<0||y<0||x>=rows||y>=cols)continue; if(Tem.at<uchar>(k,t) == 1) Dst.at<uchar>(x,y)=255; } } } } // 腐蚀函数 voidErode(Mat Src, Mat Tem, Mat Dst){ int rows = Dst.rows; int cols = Dst.cols; int t_rows = Tem.rows; int t_cols = Tem.cols; for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) { int sum = 0; for(int k=0;k<t_rows;k++) for(int t=0;t<t_cols;t++) { int x=i+k-t_rows/2; int y=j+t-t_cols/2; if(x<0||y<0||x>=rows||y>=cols)continue; sum +=Tem.at<uchar>(k,t)*Src.at<uchar>(x,y); } if(sum == 13*255)Dst.at<uchar>(i,j)=255; } } } intmain(int argc,char **argv){ //读取原始图像 Mat src=imread(argv[1],IMREAD_UNCHANGED); //检查是否读取图像 if(src.empty()){ std::cout<<"Error! Input image cannot be read...\n"; return-1; } imshow("src",src); cvtColor(src,src,COLOR_BGR2GRAY);
Mat dst1=Mat::zeros(src.size(),CV_8UC1); Mat dst2=Mat::zeros(src.size(),CV_8UC1); Mat dst3=Mat::zeros(src.size(),CV_8UC1); Mat Thimg=Mat::zeros(src.size(),CV_8UC1); threshold(src,Thimg,255/2);