Example usage for org.opencv.core Core meanStdDev

List of usage examples for org.opencv.core Core meanStdDev

Introduction

In this page you can find the example usage for org.opencv.core Core meanStdDev.

Prototype

public static void meanStdDev(Mat src, MatOfDouble mean, MatOfDouble stddev) 

Source Link

Usage

From source file:com.shootoff.camera.Camera.java

License:Open Source License

public static Mat colorTransfer(Mat source, Mat target) {
    Mat src = new Mat();
    Mat dst = new Mat();

    Imgproc.cvtColor(source, src, Imgproc.COLOR_BGR2Lab);
    Imgproc.cvtColor(target, dst, Imgproc.COLOR_BGR2Lab);

    ArrayList<Mat> src_channels = new ArrayList<Mat>();
    ArrayList<Mat> dst_channels = new ArrayList<Mat>();
    Core.split(src, src_channels);//from ww w.  j a va2 s.c o  m
    Core.split(dst, dst_channels);

    for (int i = 0; i < 3; i++) {
        MatOfDouble src_mean = new MatOfDouble(), src_std = new MatOfDouble();
        MatOfDouble dst_mean = new MatOfDouble(), dst_std = new MatOfDouble();
        Core.meanStdDev(src_channels.get(i), src_mean, src_std);
        Core.meanStdDev(dst_channels.get(i), dst_mean, dst_std);

        dst_channels.get(i).convertTo(dst_channels.get(i), CvType.CV_64FC1);
        Core.subtract(dst_channels.get(i), dst_mean, dst_channels.get(i));
        Core.divide(dst_std, src_std, dst_std);
        Core.multiply(dst_channels.get(i), dst_std, dst_channels.get(i));
        Core.add(dst_channels.get(i), src_mean, dst_channels.get(i));
        dst_channels.get(i).convertTo(dst_channels.get(i), CvType.CV_8UC1);
    }

    Core.merge(dst_channels, dst);

    Imgproc.cvtColor(dst, dst, Imgproc.COLOR_Lab2BGR);

    return dst;
}

From source file:com.sikulix.api.Image.java

License:Open Source License

private void checkProbe() {
    resizeFactor = Math.min(((double) content.width()) / resizeMinDownSample,
            ((double) content.height()) / resizeMinDownSample);
    resizeFactor = Math.max(1.0, resizeFactor);

    MatOfDouble pMean = new MatOfDouble();
    MatOfDouble pStdDev = new MatOfDouble();
    Core.meanStdDev(content, pMean, pStdDev);
    double min = 1.0E-5;
    plainColor = false;/*from   w  w  w.j  av  a  2s .co  m*/
    double sum = 0.0;
    double[] arr = pStdDev.toArray();
    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    if (sum < min) {
        plainColor = true;
    }
    sum = 0.0;
    arr = pMean.toArray();
    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    if (sum < min && plainColor) {
        blackColor = true;
    }
}

From source file:com.sikulix.api.Picture.java

License:Open Source License

private void setAttributes() {
    if (!hasContent()) {
        return;//w w w  .  jav a2 s .  c o m
    }
    plainColor = false;
    blackColor = false;
    resizeFactor = Math.min(((double) getContent().width()) / resizeMinDownSample,
            ((double) getContent().height()) / resizeMinDownSample);
    resizeFactor = Math.max(1.0, resizeFactor);
    MatOfDouble pMean = new MatOfDouble();
    MatOfDouble pStdDev = new MatOfDouble();
    Core.meanStdDev(getContent(), pMean, pStdDev);
    double sum = 0.0;
    double[] arr = pStdDev.toArray();
    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    if (sum < minThreshhold) {
        plainColor = true;
    }
    sum = 0.0;
    arr = pMean.toArray();
    meanColor = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        meanColor[i] = (int) arr[i];
        sum += arr[i];
    }
    if (sum < minThreshhold && plainColor) {
        blackColor = true;
    }

    whiteColor = isMeanColorEqual(Color.WHITE);
}

From source file:com.trandi.opentld.tld.Tld.java

License:Apache License

public void init(Mat frame1, Rect trackedBox) {
    // get Bounding boxes
    if (Math.min(trackedBox.width, trackedBox.height) < _params.min_win) {
        throw new IllegalArgumentException(
                "Provided trackedBox: " + trackedBox + " is too small (min " + _params.min_win + ")");
    }/* ww w .  j ava  2  s.c o  m*/
    _grid = new Grid(frame1, trackedBox, _params.min_win);
    Log.i(Util.TAG, "Init Created " + _grid.getSize() + " bounding boxes.");
    _grid.updateGoodBadBoxes(trackedBox, _params.num_closest_init);

    _iiRows = frame1.rows();
    _iiCols = frame1.cols();
    _iisum.create(_iiRows, _iiCols, CvType.CV_32F);
    _iisqsum.create(_iiRows, _iiCols, CvType.CV_64F);

    // correct bounding box
    _lastbox = _grid.getBestBox();

    _classifierFern.init(_grid.getTrackedBoxScales(), _rng);

    // generate DATA
    // generate POSITIVE DATA
    generatePositiveData(frame1, _params.num_warps_init, _grid);

    // Set variance threshold
    MatOfDouble stddev = new MatOfDouble();
    Core.meanStdDev(frame1.submat(_grid.getBestBox()), new MatOfDouble(), stddev);
    updateIntegralImgs(frame1);
    // this is directly half of the variance of the initial box, which will be used the the 1st stage of the classifier
    _var = (float) Math.pow(stddev.toArray()[0], 2d) * 0.5f;
    // check variance
    final double checkVar = Util.getVar(_grid.getBestBox(), _iisumJava, _iisqsumJava, _iiCols) * 0.5;
    Log.i(Util.TAG, "Variance: " + _var + " / Check variance: " + checkVar);

    // generate NEGATIVE DATA
    final Pair<List<Pair<int[], Boolean>>, List<Mat>> negData = generateNegativeData(frame1);

    // Split Negative Ferns <features, labels=false> into Training and Testing sets (they are already shuffled)
    final int nFernsSize = negData.first.size();
    final List<Pair<int[], Boolean>> nFernsTest = new ArrayList<Pair<int[], Boolean>>(
            negData.first.subList(0, nFernsSize / 2));
    final List<Pair<int[], Boolean>> nFerns = new ArrayList<Pair<int[], Boolean>>(
            negData.first.subList(nFernsSize / 2, nFernsSize));

    // Split Negative NN Examples into Training and Testing sets
    final int nExSize = negData.second.size();
    final List<Mat> nExamplesTest = new ArrayList<Mat>(negData.second.subList(0, nExSize / 2));
    _nExamples = new ArrayList<Mat>(negData.second.subList(nExSize / 2, nExSize));

    //MERGE Negative Data with Positive Data and shuffle it
    final List<Pair<int[], Boolean>> fernsData = new ArrayList<Pair<int[], Boolean>>(_pFerns);
    fernsData.addAll(nFerns);
    Collections.shuffle(fernsData);

    // TRAINING
    Log.i(Util.TAG, "Init Start Training with " + fernsData.size() + " ferns, " + _nExamples.size()
            + " nExamples, " + nFernsTest.size() + " nFernsTest, " + nExamplesTest.size() + " nExamplesTest");
    _classifierFern.trainF(fernsData, 10);
    _classifierNN.trainNN(_pExample, _nExamples);
    // Threshold evaluation on testing sets
    _classifierFern.evaluateThreshold(nFernsTest);
    _classifierNN.evaluateThreshold(nExamplesTest);
}

From source file:com.trandi.opentld.tld.Tld.java

License:Apache License

/**
 * Output: resized zero-mean patch/pattern
 * @param inImg INPUT, outPattern OUTPUT
 * @return stdev/*from  www. j  av  a2  s  . co m*/
 */
private static double resizeZeroMeanStdev(final Mat inImg, Mat outPattern, int patternSize) {
    if (inImg == null || outPattern == null) {
        return -1;
    }

    Imgproc.resize(inImg, outPattern, new Size(patternSize, patternSize));
    final MatOfDouble mean = new MatOfDouble();
    final MatOfDouble stdev = new MatOfDouble();
    Core.meanStdDev(outPattern, mean, stdev);
    outPattern.convertTo(outPattern, CvType.CV_32F);
    Core.subtract(outPattern, new Scalar(mean.toArray()[0]), outPattern);

    return stdev.toArray()[0];
}

From source file:org.sikuli.script.ImageFind.java

License:MIT License

private void checkProbe() {
    MatOfDouble pMean = new MatOfDouble();
    MatOfDouble pStdDev = new MatOfDouble();
    Core.meanStdDev(probe, pMean, pStdDev);
    double min = 0.00001;
    isPlainColor = false;/*from  w w w.  j  a  v a 2 s.  co  m*/
    double sum = 0.0;
    double arr[] = pStdDev.toArray();
    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    if (sum < min) {
        isPlainColor = true;
    }
    sum = 0.0;
    arr = pMean.toArray();
    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    if (sum < min && isPlainColor) {
        isBlack = true;
    }
    resizeFactor = Math.min(((double) probe.width()) / resizeMinDownSample,
            ((double) probe.height()) / resizeMinDownSample);
    resizeFactor = Math.max(1.0, resizeFactor);
}

From source file:qupath.opencv.tools.WandToolCV.java

License:Open Source License

@Override
protected Shape createShape(double x, double y, boolean useTiles) {

    if (mat == null)
        mat = new Mat(w, w, CvType.CV_8UC3);
    if (matMask == null)
        matMask = new Mat(w + 2, w + 2, CvType.CV_8U);

    if (pLast != null && pLast.distanceSq(x, y) < 4)
        return new Path2D.Float();

    long startTime = System.currentTimeMillis();

    QuPathViewer viewer = getViewer();/*from  ww  w  .  j a v  a2 s  .c  om*/
    if (viewer == null)
        return new Path2D.Float();

    double downsample = viewer.getDownsampleFactor();

    DefaultImageRegionStore regionStore = viewer.getImageRegionStore();

    // Paint the image as it is currently being viewed
    Graphics2D g2d = imgTemp.createGraphics();
    g2d.setColor(Color.BLACK);
    g2d.fillRect(0, 0, w, w);
    bounds.setFrame(x - w * downsample * .5, y - w * downsample * .5, w * downsample, w * downsample);
    g2d.scale(1.0 / downsample, 1.0 / downsample);
    g2d.translate(-bounds.getX(), -bounds.getY());
    regionStore.paintRegionCompletely(viewer.getServer(), g2d, bounds, viewer.getZPosition(),
            viewer.getTPosition(), viewer.getDownsampleFactor(), null, viewer.getImageDisplay(), 250);
    g2d.dispose();

    // Put pixels into an OpenCV image
    byte[] buffer = ((DataBufferByte) imgTemp.getRaster().getDataBuffer()).getData();
    mat.put(0, 0, buffer);

    //      Imgproc.cvtColor(mat, mat, Imgproc.COLOR_BGR2Lab);
    //      blurSigma = 4;

    double blurSigma = Math.max(0.5, getWandSigmaPixels());
    double size = Math.ceil(blurSigma * 2) * 2 + 1;
    blurSize.width = size;
    blurSize.height = size;

    // Smooth a little
    Imgproc.GaussianBlur(mat, mat, blurSize, blurSigma);

    //      Imgproc.cvtColor(mat, mat, Imgproc.COLOR_RGB2Lab);

    MatOfDouble mean = new MatOfDouble();
    MatOfDouble stddev = new MatOfDouble();
    Core.meanStdDev(mat, mean, stddev);
    //      logger.trace(stddev.dump());

    double[] stddev2 = stddev.toArray();
    double scale = .4;
    for (int i = 0; i < stddev2.length; i++)
        stddev2[i] = stddev2[i] * scale;
    threshold.set(stddev2);

    mean.release();
    stddev.release();

    matMask.setTo(zero);
    Imgproc.circle(matMask, seed, w / 2, one);
    Imgproc.floodFill(mat, matMask, seed, one, null, threshold, threshold,
            4 | (2 << 8) | Imgproc.FLOODFILL_MASK_ONLY | Imgproc.FLOODFILL_FIXED_RANGE);
    Core.subtract(matMask, one, matMask);

    if (strel == null)
        strel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
    Imgproc.morphologyEx(matMask, matMask, Imgproc.MORPH_CLOSE, strel);
    ////      Imgproc.morphologyEx(matMask, matMask, Imgproc.MORPH_OPEN, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, size));
    //      
    ////      threshold = new Scalar(10, 10, 10);
    //      double[] stddev2 = stddev.toArray();
    //      double scale = .5;
    //      threshold = new Scalar(stddev2[0]*scale, stddev2[1]*scale, stddev2[2]*scale);

    contours.clear();
    if (contourHierarchy == null)
        contourHierarchy = new Mat();
    Imgproc.findContours(matMask, contours, contourHierarchy, Imgproc.RETR_EXTERNAL,
            Imgproc.CHAIN_APPROX_SIMPLE);
    //      logger.trace("Contours: " + contours.size());

    Path2D path = new Path2D.Float();
    boolean isOpen = false;
    for (MatOfPoint contour : contours) {

        // Discard single pixels / lines
        if (contour.size().height <= 2)
            continue;

        // Create a polygon ROI
        boolean firstPoint = true;
        for (Point p : contour.toArray()) {
            double xx = (p.x - w / 2 - 1) * downsample + x;
            double yy = (p.y - w / 2 - 1) * downsample + y;
            if (firstPoint) {
                path.moveTo(xx, yy);
                firstPoint = false;
                isOpen = true;
            } else
                path.lineTo(xx, yy);
        }
    }
    if (isOpen)
        path.closePath();

    long endTime = System.currentTimeMillis();
    logger.trace(getClass().getSimpleName() + " time: " + (endTime - startTime));

    if (pLast == null)
        pLast = new Point2D.Double(x, y);
    else
        pLast.setLocation(x, y);

    return path;

}

From source file:syncleus.dann.data.video.Tld.java

License:Apache License

public void init(Mat frame1, Rect trackedBox) {
    // get Bounding boxes
    if (Math.min(trackedBox.width, trackedBox.height) < _params.min_win) {
        throw new IllegalArgumentException(
                "Provided trackedBox: " + trackedBox + " is too small (min " + _params.min_win + ")");
    }//ww w .jav  a 2  s  .co m
    _grid = new Grid(frame1, trackedBox, _params.min_win);
    System.out.println("Init Created " + _grid.getSize() + " bounding boxes.");
    _grid.updateGoodBadBoxes(trackedBox, _params.num_closest_init);

    _iiRows = frame1.rows();
    _iiCols = frame1.cols();
    _iisum.create(_iiRows, _iiCols, CvType.CV_32F);
    _iisqsum.create(_iiRows, _iiCols, CvType.CV_64F);

    // correct bounding box
    _lastbox = _grid.getBestBox();

    _classifierFern.init(_grid.getTrackedBoxScales(), _rng);

    // generate DATA
    // generate POSITIVE DATA
    generatePositiveData(frame1, _params.num_warps_init, _grid);

    // Set variance threshold
    MatOfDouble stddev = new MatOfDouble();
    Core.meanStdDev(frame1.submat(_grid.getBestBox()), new MatOfDouble(), stddev);
    updateIntegralImgs(frame1);
    // this is directly half of the variance of the initial box, which will be used the the 1st stage of the classifier
    _var = (float) Math.pow(stddev.toArray()[0], 2d) * 0.5f;
    // check variance
    final double checkVar = TLDUtil.getVar(_grid.getBestBox(), _iisumJava, _iisqsumJava, _iiCols) * 0.5;
    System.out.println("Variance: " + _var + " / Check variance: " + checkVar);

    // generate NEGATIVE DATA
    final Pair<List<Pair<int[], Boolean>>, List<Mat>> negData = generateNegativeData(frame1);

    // Split Negative Ferns <features, labels=false> into Training and Testing sets (they are already shuffled)
    final int nFernsSize = negData.first.size();
    final List<Pair<int[], Boolean>> nFernsTest = new ArrayList<Pair<int[], Boolean>>(
            negData.first.subList(0, nFernsSize / 2));
    final List<Pair<int[], Boolean>> nFerns = new ArrayList<Pair<int[], Boolean>>(
            negData.first.subList(nFernsSize / 2, nFernsSize));

    // Split Negative NN Examples into Training and Testing sets
    final int nExSize = negData.second.size();
    final List<Mat> nExamplesTest = new ArrayList<Mat>(negData.second.subList(0, nExSize / 2));
    _nExamples = new ArrayList<Mat>(negData.second.subList(nExSize / 2, nExSize));

    //MERGE Negative Data with Positive Data and shuffle it
    final List<Pair<int[], Boolean>> fernsData = new ArrayList<Pair<int[], Boolean>>(_pFerns);
    fernsData.addAll(nFerns);
    Collections.shuffle(fernsData);

    // TRAINING
    System.out.println("Init Start Training with " + fernsData.size() + " ferns, " + _nExamples.size()
            + " nExamples, " + nFernsTest.size() + " nFernsTest, " + nExamplesTest.size() + " nExamplesTest");
    _classifierFern.trainF(fernsData, 10);
    _classifierNN.trainNN(_pExample, _nExamples);
    // Threshold evaluation on testing sets
    _classifierFern.evaluateThreshold(nFernsTest);
    _classifierNN.evaluateThreshold(nExamplesTest);
}

From source file:uk.ac.horizon.artcodes.process.BlurDetectionFilter.java

License:Open Source License

@Override
public void process(ImageBuffers buffers) {
    Mat greyImage = buffers.getImageInGrey();

    Mat dst = new Mat();

    long start = System.currentTimeMillis();

    int roiSize = Math.min(greyImage.rows(), greyImage.cols()) / 2;
    Imgproc.Laplacian(greyImage.submat(/*from www .j a va  2s .  c om*/
            new Rect((greyImage.cols() - roiSize) / 2, (greyImage.rows() - roiSize) / 2, roiSize, roiSize)),
            dst, CvType.CV_16S);
    MatOfDouble mean = new MatOfDouble();
    MatOfDouble stdDev = new MatOfDouble();
    Core.meanStdDev(dst, mean, stdDev);

    long end = System.currentTimeMillis();

    //Log.i("STDDEV", "StdDev: "+Math.pow(stdDev.get(0,0)[0],2)+ " (took: " + (end-start) + "ms)");

    double blurScore = Math.pow(stdDev.get(0, 0)[0], 2);

    /*
    Mat overlay = buffers.getOverlay();
    String text = "b.score: " + (int)blurScore + " ("+(end-start)+"ms)";
    int y = overlay.rows()-50;
    int x = 50;
    Imgproc.putText(overlay, text, new Point(x,y), Core.FONT_HERSHEY_SIMPLEX, 1, new Scalar(0,0,0,0), 5);
    Imgproc.putText(overlay, text, new Point(x,y), Core.FONT_HERSHEY_SIMPLEX, 1, new Scalar(255,255,255,255), 3);
    */

    // if image is blurry
    if (blurScore <= 100) {
        // tell camera to focus
        Log.i("FOCUS", "Blur detector requesting auto focus with b.score of " + (int) blurScore);
        this.cameraFocusControl.focus(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

}