C++实现gabor滤波
时间: 2023-07-11 16:35:00 浏览: 114
下面是一个简单的C++实现Gabor滤波器的示例代码:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <cmath>
using namespace cv;
using namespace std;
Mat gaborFilter(int kernelSize, double sigma, double theta, double lambda, double gamma)
{
int halfSize = kernelSize / 2;
double sigmaX = sigma;
double sigmaY = sigma / gamma;
Mat kernel(kernelSize, kernelSize, CV_32F);
double sum = 0.0;
for (int i = -halfSize; i <= halfSize; i++) {
for (int j = -halfSize; j <= halfSize; j++) {
double x = (double)j * cos(theta) + (double)i * sin(theta);
double y = (double)-j * sin(theta) + (double)i * cos(theta);
double expX = exp(-0.5 * pow(x / sigmaX, 2.0));
double expY = exp(-0.5 * pow(y / sigmaY, 2.0));
double cosXY = cos(2 * M_PI * x / lambda);
kernel.at<float>(i + halfSize, j + halfSize) = expX * expY * cosXY;
sum += kernel.at<float>(i + halfSize, j + halfSize);
}
}
kernel /= sum;
return kernel;
}
int main()
{
Mat src = imread("lena.jpg", IMREAD_GRAYSCALE);
if (src.empty()) {
cout << "Could not read the image: " << endl;
return -1;
}
Mat kernel = gaborFilter(21, 5.0, CV_PI / 4.0, 10.0, 0.5);
Mat dst;
filter2D(src, dst, -1, kernel);
imshow("src", src);
imshow("dst", dst);
waitKey(0);
return 0;
}
```
在这个示例中, `gaborFilter()` 函数返回一个指定参数的Gabor滤波器核。然后使用OpenCV的 `filter2D()` 函数将该核应用于输入图像。请注意,Gabor滤波器的参数可以根据应用程序中的要求进行修改。
阅读全文