6

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!

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Gaya3
  • 155
  • 2
  • 16
  • 1
    Variance is standard deviation squared. The standard devation you can get from the function `MeanStdDev` on the Mat object. I don't know enough about `OpenCvSharp to get it working though. – Palle Due Sep 19 '19 at 08:01
  • @PalleDue I tried to use ```MeanStdDev``` but couldn't get the standard deviation value out. Tried [this code](https://stackoverflow.com/questions/36413394/opencv-variation-of-the-laplacian-java) too. But couldn't convert it into C#. – Gaya3 Sep 19 '19 at 08:15

1 Answers1

7

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;
    }
}
Palle Due
  • 5,929
  • 4
  • 17
  • 32