Java and OpenCV: Calculate Median / Mean / Stdev value of MAT (Gray-Image)
Asked Answered
A

2

6

I've got an image as grayscale image using

Mat m = Highgui.imread(path, Highgui.CV_LOAD_IMAGE_GRAYSCALE);

in Java and now I want to calculate the median value, the mean value and the standard deviation. I'n new to this and I simply don't know how to find out the calculations and stuff... Tried 2 hours of googeling, please give me some basic advise on how to do research on this. I tried keywords like "mean value java opencv" and found this:

http://docs.opencv.org/java/2.4.2/org/opencv/core/Core.html#meanStdDev

I'm now doing this:

MatOfDouble mu = new MatOfDouble();
MatOfDouble sigma = new MatOfDouble();
Core.meanStdDev(m, mu, sigma);

But HOW the hell to access the mean/stdev value as a double? Tried things like

double d = mu.get(0,0)

but there's something wrong. I can't find it out by reading the OpenCV Java docs myself unfortunately as I don't know what to look for/at.

I need mean/stdev to calculate the thresholds for the canny filter... Thanks so far in advance

Abstractionist answered 13/3, 2014 at 20:26 Comment(0)
J
8

try this:

double d = mu.get(0,0)[0]

mu.get(0,0) returns a double[], so you can just get the first element - it's equivalent to the C++ version of:

mu.val[0]

Hope it helps.

Jonniejonny answered 16/3, 2014 at 15:49 Comment(3)
is that double d is median? @JonniejonnyUllage
mu is typically the symbol for the meanJonniejonny
Note: This only gives an accurate answer for grayscale images. For color images you'll need to take the average of all the channels. Ex. double totalMu = (mu.get(0,0)[0] + mu.get(1,0)[0] + mu.get(2,0)[0]) / 3.Prevailing
S
1

Here is the corresponding code for a 3 channel color image.I've used Lab color space.It will work with BGR as well...

//compute color statistics for the source image
    List<Mat> labsrc = new ArrayList<Mat>(3);
    Core.split(src, labsrc);


    MatOfDouble meansrc= new MatOfDouble();
    MatOfDouble stdsrc= new MatOfDouble();

    Core.meanStdDev(src, meansrc, stdsrc);

    Log.d("meansrc",meansrc.dump() );

    Log.d("meanval1", String.valueOf(meansrc.get(0,0)[0]));
    Log.d("meanval2", String.valueOf(meansrc.get(1,0)[0]));
    Log.d("meanval3", String.valueOf(meansrc.get(2,0)[0]));

    double lMeanSrc = meansrc.get(0,0)[0];
    double aMeanSrc = meansrc.get(1,0)[0];
    double bMeanSrc = meansrc.get(2,0)[0];

    double lStdSrc = stdsrc.get(0,0)[0];
    double aStdSrc = stdsrc.get(1,0)[0];
    double bStdSrc = stdsrc.get(2,0)[0];
Scavenger answered 27/4, 2019 at 14:13 Comment(1)
Works fine thanks, but you don't need the first two lines since labsrc is never used.Wisecrack

© 2022 - 2024 — McMap. All rights reserved.