Example usage for org.opencv.core MatOfDouble toArray

List of usage examples for org.opencv.core MatOfDouble toArray

Introduction

In this page you can find the example usage for org.opencv.core MatOfDouble toArray.

Prototype

public double[] toArray() 

Source Link

Usage

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;// www .  j av a  2s  .com
    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;/*www.j  a  va  2  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.PatchGenerator.java

License:Apache License

/**
 * //www .  j a v a  2s .  com
 * @param srcCenter
 * @param dstCenter
 * @param transform OUTPUT
 * @param inverse
 */
private void generateRandomTransform(Point srcCenter, Point dstCenter, Mat transform, boolean inverse) {
    MatOfDouble tempRand = new MatOfDouble(0d, 0d);
    Core.randu(tempRand, lambdaMin, lambdaMax);
    final double[] rands = tempRand.toArray();
    final double lambda1 = rands[0];
    final double lambda2 = rands[1];
    Core.randu(tempRand, thetaMin, thetaMax);
    final double theta = tempRand.toArray()[0];
    Core.randu(tempRand, phiMin, phiMax);
    final double phi = tempRand.toArray()[0];

    // Calculate random parameterized affine transformation A,
    // A = T(patch center) * R(theta) * R(phi)' * S(lambda1, lambda2) * R(phi) * T(-pt)
    final double st = Math.sin(theta);
    final double ct = Math.cos(theta);
    final double sp = Math.sin(phi);
    final double cp = Math.cos(phi);
    final double c2p = cp * cp;
    final double s2p = sp * sp;

    final double A = lambda1 * c2p + lambda2 * s2p;
    final double B = (lambda2 - lambda1) * sp * cp;
    final double C = lambda1 * s2p + lambda2 * c2p;

    final double Ax_plus_By = A * srcCenter.x + B * srcCenter.y;
    final double Bx_plus_Cy = B * srcCenter.x + C * srcCenter.y;

    transform.create(2, 3, CvType.CV_64F);
    transform.put(0, 0, A * ct - B * st);
    transform.put(0, 1, B * ct - C * st);
    transform.put(0, 2, -ct * Ax_plus_By + st * Bx_plus_Cy + dstCenter.x);
    transform.put(1, 0, A * st + B * ct);
    transform.put(1, 1, B * st + C * ct);
    transform.put(1, 2, -st * Ax_plus_By - ct * Bx_plus_Cy + dstCenter.y);

    if (inverse) {
        Imgproc.invertAffineTransform(transform, transform);
    }
}

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 + ")");
    }/*www.  ja  va2s.  c om*/
    _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 ww w .  j  a  v  a  2s. c  om
 */
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 ww  .j  a  va2 s.  com
    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 av a2 s  .  co m*/
    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 + ")");
    }/*  w  w  w.j ava2 s .c o 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);
}