Search code examples
c++opencvmatstandard-deviationlaplacian

Why does meanStdDev() return [nan]?


I want to calculate the standard deviation of an image using OpenCV in C++. However, I get very weird results. My code:

#include <iostream>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

int main() {
    VideoCapture cap("Sample-Video.mp4");
    Mat frame;
    ret = cap.read(frame);

    Scalar m, stdv;
    cvtColor(frame, frame, COLOR_BGR2GRAY);
    Laplacian(frame, frame, CV_64F, 3);
    meanStdDev(frame, m, stdv);

    cout << stdv << endl;
}

It outputs always:

[0, 0, 0, 0]
[nan, 0, 0, 0]
[nan, 0, 0, 0]
[-nan, 0, 0, 0]
[-nan, 0, 0, 0]
[-nan, 0, 0, 0]
[nan, 0, 0, 0]
[nan, 0, 0, 0]
[nan, 0, 0, 0]
[nan, 0, 0, 0]
[nan, 0, 0, 0]
[nan, 0, 0, 0]

and so on. Where's the problem?


Solution

  • So, by now, I figured out what the problem was myself. You are not allowed to use the same variable twice in the cvtColor() and Laplacian() functions, that means your source and destination can't be the same. Other programming languages like Python are able to deal with that problem, C++ however can not.

    Anyway, here is my correct code how to get the Laplacian variance of an image:

    #include <iostream>
    #include <cmath>
    #include <opencv2/opencv.hpp>
    using namespace std;
    using namespace cv;
    
    double give_laplacian(Mat *fr) {
        Scalar m, stdv;
        Mat gray, lap;
    
        cvtColor(*fr, gray, COLOR_BGR2GRAY);
        Laplacian(gray, lap, CV_64F);
        meanStdDev(lap, m, stdv, Mat());
    
        return pow(stdv.val[0], 2);
    }
    
    int main() {
        Mat frame;
    
        //here you get your frame, e.g. from a video with a cap etc.
    
        val = give_laplacian(&frame);
        cout << "Sharpness value: " << val << endl;
    }
    

    Hope it helps.