dimanche 22 février 2015

OpenCV gabor filtering producing different results than Matlab code with same exact kernel


I've created a Gabor filter with the following code:



Mat gabor(double sigma, double theta) {

int nstds = 3;
int kernel_size = nstds * sigma * 2 - 1;

if(!kernel_size % 2) {
kernel_size++;
}

int hks = (kernel_size - 1) / 2;

theta = theta * CV_PI / 180;
sigma = sigma;

double x_theta;
double y_theta;
double gamma = 1;
double del_phi = 0.8;
double v = sqrt(2 * log(2)) * ((pow(2, del_phi) + 1) / (pow(2, del_phi) - 1));
double psi = -exp(-0.5 * pow(v, 2));
double fs = (1 / (CV_PI * sigma)) * sqrt(0.5 * log(2)) * ((pow(2, del_phi) + 1) / (pow(2, del_phi) - 1));
double lambda = 1 / fs;
double p = gamma / (2 * CV_PI * pow(sigma, 2));

Mat kernel(kernel_size, kernel_size, CV_32F);

for(int y = -hks; y <= hks; y++) {
for(int x = -hks; x <= hks; x++) {

x_theta = x * cos(theta) + y * sin(theta);
y_theta = -x * sin(theta) + y * cos(theta);

kernel.at<float>(hks+y, hks+x) =
(float)
exp(-0.5 * (pow(x_theta, 2.0) + pow(y_theta, 2.0)) / pow(sigma, 2.0)) *
cos(2.0 * CV_PI * x_theta / lambda + psi);
}
}

return kernel;
}


The code above creates a gabor kernel that is identical to my kernel created in Matlab. I apply the gabor filter with the conv2 function in Matlab and filter2D in OpenCV. I understand that filter2D isn't strictly convolution, but when I flip the kernels and change the anchor, etc, nothing helps. The Matlab output looks good but the OpenCV output looks bad. Why?


Matlab (Good):


enter image description here


OpenCV (Bad):


enter image description here


I'm using filter2D(preproc, filtered, CV_64FC1, kernel); to produce the OpenCV output. How come the OpenCV looks all zebra-stripy and the Matlab looks like what I want? Again, the kernel Mat values are exactly the same (I ported the OpenCV kernel into Matlab and compared and they are 99.99% similar).




Aucun commentaire:

Enregistrer un commentaire