Gabor滤波器

Gabor的核函数参考的wiki

Gabor滤波器_第1张图片

使用实数Real的公式计算核函数代码:

Mat getGaborFilter(float lambda, float theta, 
	float sigma2,float gamma, 
	float psi = 0.0f){
		if(abs(lambda-0.0f)<1e-6){
			lambda = 1.0f;
		} 
		float sigma_x = sigma2;
		float sigma_y = sigma2/(gamma*gamma);
		int nstds = 3;
		float sqrt_sigma_x = sqrt(sigma_x);
		float sqrt_sigma_y = sqrt(sigma_y);
		int xmax = max(abs(nstds*sqrt_sigma_x*cos(theta)),abs(nstds*sqrt_sigma_y*sin(theta)));
		int ymax = max(abs(nstds*sqrt_sigma_x*sin(theta)),abs(nstds*sqrt_sigma_y*cos(theta)));
		int half_filter_size = xmax>ymax ? xmax:ymax;
		int filter_size = 2*half_filter_size+1;
		Mat gaber = Mat::zeros(filter_size,filter_size,CV_32F);
		for(int i=0;i<filter_size;i++){
			float* f = gaber.ptr<float>(i);
			for(int j=0;j<filter_size;j++){
				int x = j-half_filter_size;
				int y = i-half_filter_size;
				float x_theta=x*cos(theta)+y*sin(theta);
				float y_theta=-x*sin(theta)+y*cos(theta);
				f[x] = exp(-.5*(x_theta*x_theta/sigma_x+y_theta*y_theta/sigma_y));
				f[x] = f[x]*cos(2*PI*x_theta/lambda+psi);
			};
		}
		return gaber;
}

使用得到的Gabor核对一副图像进行卷积的函数:

Mat gaborFilter(Mat& img, Mat& filter){
	int half_filter_size = (max(filter.rows,filter.cols)-1)/2;
	Mat filtered_img(img.rows,img.cols,CV_32F);
	for(int i=0;i<img.rows;i++){
		uchar* img_p = img.ptr<uchar>(i);
		float* img_f = filtered_img.ptr<float>(i);
		for(int j=0;j<img.cols;j++){
			float filter_value = 0.0f;
			for(int fi=0;fi<filter.rows;fi++){
				float* f = filter.ptr<float>(fi);
				int img_i = i+fi-half_filter_size;
				img_i = img_i < 0 ? 0 : img_i;
				img_i = img_i >= img.rows ? (img.rows-1) : img_i;
				uchar* p = img.ptr<uchar>(img_i);
				for(int fj=0;fj<filter.cols;fj++){
					int img_j = j+fj-half_filter_size;
					img_j = img_j < 0 ? 0 : img_j;
					img_j = (img_j >= img.cols) ? (img.cols-1) : img_j;
					float tmp = (float)p[img_j]*f[fj];
					filter_value += tmp;
				}
			}
			img_f[j] = filter_value;
		}
	}
	return filtered_img;
}

对一幅图使用如下核卷积:

Mat gaber = getGaborFilter(0.3,0,4,2);
效果如下:

Gabor滤波器_第2张图片

Gabor算子卷积之后得到很多负值(不知道有没有问题),后面的图是归一化之后显示出来的。

Mat normalizeFilterShow(Mat gaber){
	Mat gaber_show = Mat::zeros(gaber.rows,gaber.cols,CV_8UC1);
	float gaber_max = FLT_MIN;
	float gaber_min = FLT_MAX;
	for(int i=0;i<gaber.rows;i++){
		float* f = gaber.ptr<float>(i);
		for(int j=0;j<gaber.cols;j++){
			if(f[j]>gaber_max){
				gaber_max = f[j];
			}
			if(f[j]<gaber_min){
				gaber_min = f[j];
			}
		}
	}
	float gaber_max_min = gaber_max-gaber_min;
	for(int i=0;i<gaber_show.rows;i++){
		uchar* p = gaber_show.ptr<uchar>(i);
		float* f = gaber.ptr<float>(i);
		for(int j=0;j<gaber_show.cols;j++){
			if(gaber_max_min!=0.0f){
				float tmp = (f[j]-gaber_min)*255.0f/gaber_max_min;
				p[j] = (uchar)tmp;
			}
			else{
				p[j] = 255;
			}
		}
	}
	return gaber_show;
}

你可能感兴趣的:(Gabor滤波器)