Skip to content

Instantly share code, notes, and snippets.

@Seanmatthews
Last active November 6, 2023 12:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Seanmatthews/35ae726c877da47d5c3175bedcede0eb to your computer and use it in GitHub Desktop.
Save Seanmatthews/35ae726c877da47d5c3175bedcede0eb to your computer and use it in GitHub Desktop.
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