Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compute Laplace of Gaussian kernel for a size and sigma using OpenCV
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <assert.h>
// Calculates Laplace of Gaussian kernel
cv::Mat createLOGKernel(int ksize, double sigma)
{
using namespace cv;
using namespace std;
assert(1 == ksize%2);
Mat kernel(ksize, ksize, CV_64F);
Mat X(ksize, ksize, CV_64F);
Mat Y(ksize, ksize, CV_64F);
int siz = (ksize-1)/2;
double std2 = sigma*sigma;
vector<double> seq(ksize);
iota(begin(seq), end(seq), -siz);
Mat seqX(1, ksize, CV_64F, seq.data());
Mat seqY(ksize, 1, CV_64F, seq.data());
repeat(seqX, ksize, 1, X);
repeat(seqY, 1, ksize, Y);
Mat XX, YY;
multiply(X, X, XX);
multiply(Y, Y, YY);
Mat H = -(XX + YY) / (2.*std2);
exp(H, H);
double minVal, maxVal;
minMaxIdx(H, &minVal, &maxVal);
Mat mask = H < numeric_limits<double>::epsilon()*maxVal;
H.setTo(0, mask);
double sumh = sum(H)[0];
if (sumh != 0) H /= sumh;
Mat H1;
multiply(H, (XX + YY - 2*std2) / (std2*std2), H1);
H = H1 - sum(H1)[0] / (ksize*ksize);
return H;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment