Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the variance of Laplacian in C#

Simply, I am trying to calculate the sharpness of an image as a part of a function in C# using OpenCVSharp.

As the 1st try, I used Laplacian Filter like this:

int kernel_size = 3;
int scale = 1;
int delta = 0;
int ddepth = image.Type().Depth;

Mat sharpenedImage = image.Laplacian(ddepth, kernel_size, scale, delta);

\* calculate the variance of the laplacian*\

Finally, I want the variance of this sharpenedImage.

I have tried that easily in Python:

def variance_of_laplacian(image):
    lap_val = cv2.Laplacian(image, cv2.CV_8UC1)
    return lap_val.var()

So is there any equivalent of lap_val.var() in C#?

I couldn't find any matching article regarding this. Thank you!

like image 455
Gaya3 Avatar asked Oct 16 '22 11:10

Gaya3


1 Answers

Variance is the standard deviation squared, so you should be able to use that. The following code compiles with OpenCvSharp4 and OpenCvSharp4.runtime.win, but I don't know if it does what you want. Try it out.

static double Variance(Mat image)
{
    using (var laplacian = new Mat())
    {
        int kernel_size = 3;
        int scale = 1;
        int delta = 0;
        int ddepth = image.Type().Depth;
        Cv2.Laplacian(image, laplacian, ddepth, kernel_size, scale, delta);
        Cv2.MeanStdDev(laplacian, out var mean, out var stddev);
        return stddev.Val0 * stddev.Val0;
    }
}
like image 73
Palle Due Avatar answered Nov 01 '22 11:11

Palle Due