Example usage for org.opencv.core Mat release

List of usage examples for org.opencv.core Mat release

Introduction

In this page you can find the example usage for org.opencv.core Mat release.

Prototype

public void release() 

Source Link

Usage

From source file:org.lasarobotics.vision.util.color.Color.java

License:Open Source License

/**
 * Convert this color to a different colorspace and return a scalar
 *
 * @param to Colorspace to convert to/*w  ww .  j a v  a2 s .c om*/
 * @return Scalar in other colorspace
 */
public Scalar convertColorScalar(ColorSpace to) {
    if (getColorSpace() == to)
        return getScalar();
    if (!getColorSpace().canConvertTo(to))
        throw new IllegalArgumentException("Cannot convert color to the desired color space.");

    Scalar output = this.getScalar();

    try {
        for (int i = 0; i < getColorSpace().getConversionsTo(to).length; i += 3) {
            int conversion = getColorSpace().getConversionsTo(to)[i];
            int inputDim = getColorSpace().getConversionsTo(to)[i + 1];
            int outputDim = getColorSpace().getConversionsTo(to)[i + 2];

            Mat pointMatTo = new Mat();
            Mat pointMatFrom = new Mat(1, 1, CvType.CV_8UC(inputDim), output);
            Imgproc.cvtColor(pointMatFrom, pointMatTo, conversion, outputDim);
            output = new Scalar(pointMatTo.get(0, 0));
            pointMatTo.release();
            pointMatFrom.release();
        }
    } catch (Exception ignored) {
        throw new IllegalArgumentException("Cannot convert color to the desired color space.");
    }

    return output;
}

From source file:org.openpnp.machine.reference.ReferenceCamera.java

License:Open Source License

protected BufferedImage transformImage(BufferedImage image) {
    Mat mat = OpenCvUtils.toMat(image);

    mat = crop(mat);//  w  ww .j  a  v a2 s  . co m

    mat = calibrate(mat);

    mat = undistort(mat);

    // apply affine transformations
    mat = rotate(mat, rotation);

    mat = offset(mat, offsetX, offsetY);

    if (flipX || flipY) {
        int flipCode;
        if (flipX && flipY) {
            flipCode = -1;
        } else {
            flipCode = flipX ? 0 : 1;
        }
        Core.flip(mat, mat, flipCode);
    }

    image = OpenCvUtils.toBufferedImage(mat);
    mat.release();
    return image;
}

From source file:org.openpnp.machine.reference.ReferenceCamera.java

License:Open Source License

private Mat crop(Mat mat) {
    if (cropWidth != 0 || cropHeight != 0) {
        Rect roi = new Rect((int) ((mat.size().width / 2) - (cropWidth / 2)),
                (int) ((mat.size().height / 2) - (cropHeight / 2)), cropWidth, cropHeight);
        Mat tmp = new Mat(mat, roi);
        tmp.copyTo(mat);//from  w w  w. j a  v  a  2 s. c  om
        tmp.release();
    }
    return mat;
}

From source file:org.openpnp.machine.reference.ReferenceCamera.java

License:Open Source License

private Mat rotate(Mat mat, double rotation) {
    if (rotation == 0D) {
        return mat;
    }/* w w  w  .  ja va  2  s .  co  m*/

    // See:
    // http://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c
    Point center = new Point(mat.width() / 2D, mat.height() / 2D);
    Mat mapMatrix = Imgproc.getRotationMatrix2D(center, rotation, 1.0);

    // determine bounding rectangle
    Rect bbox = new RotatedRect(center, mat.size(), rotation).boundingRect();
    // adjust transformation matrix
    double[] cx = mapMatrix.get(0, 2);
    double[] cy = mapMatrix.get(1, 2);
    cx[0] += bbox.width / 2D - center.x;
    cy[0] += bbox.height / 2D - center.y;
    mapMatrix.put(0, 2, cx);
    mapMatrix.put(1, 2, cy);

    Mat dst = new Mat(bbox.width, bbox.height, mat.type());
    Imgproc.warpAffine(mat, dst, mapMatrix, bbox.size(), Imgproc.INTER_LINEAR);
    mat.release();

    mapMatrix.release();

    return dst;
}

From source file:org.openpnp.machine.reference.ReferenceCamera.java

License:Open Source License

private Mat offset(Mat mat, int offsetX, int offsetY) {
    if (offsetX == 0D && offsetY == 0D) {
        return mat;
    }/*www  .  ja va  2 s  .  co m*/

    Mat mapMatrix = new Mat(2, 3, CvType.CV_32F) {
        {
            put(0, 0, 1, 0, offsetX);
            put(1, 0, 0, 1, offsetY);
        }
    };

    Mat dst = mat.clone();
    Imgproc.warpAffine(mat, dst, mapMatrix, mat.size(), Imgproc.INTER_LINEAR);
    mat.release();

    mapMatrix.release();

    return dst;
}

From source file:org.openpnp.machine.reference.ReferenceCamera.java

License:Open Source License

private Mat undistort(Mat mat) {
    if (!calibration.isEnabled()) {
        return mat;
    }//from  ww  w  .jav  a 2s .c o m

    if (undistortionMap1 == null || undistortionMap2 == null) {
        undistortionMap1 = new Mat();
        undistortionMap2 = new Mat();
        Mat rectification = Mat.eye(3, 3, CvType.CV_32F);
        Imgproc.initUndistortRectifyMap(calibration.getCameraMatrixMat(),
                calibration.getDistortionCoefficientsMat(), rectification, calibration.getCameraMatrixMat(),
                mat.size(), CvType.CV_32FC1, undistortionMap1, undistortionMap2);
        rectification.release();
    }

    Mat dst = mat.clone();
    Imgproc.remap(mat, dst, undistortionMap1, undistortionMap2, Imgproc.INTER_LINEAR);
    mat.release();

    return dst;
}

From source file:org.openpnp.vision.FluentCv.java

License:Open Source License

private FluentCv store(Mat mat, String... tag) {
    this.mat = mat;
    if (tag != null && tag.length > 0) {
        // Clone so that future writes to the pipeline Mat
        // don't overwrite our stored one.
        mat = stored.get(tag[0]);/*from w  ww .ja  v a2 s  .c o m*/
        if (mat != null) {
            mat.release();
        }
        stored.put(tag[0], this.mat.clone());
    }
    return this;
}

From source file:qupath.opencv.classify.OpenCvClassifier.java

License:Open Source License

protected void createAndTrainClassifier() {

    // Create the required Mats
    int nMeasurements = measurements.size();

    Mat matTraining = new Mat(arrayTraining.length / nMeasurements, nMeasurements, CvType.CV_32FC1);
    matTraining.put(0, 0, arrayTraining);
    Mat matResponses = new Mat(arrayResponses.length, 1, CvType.CV_32SC1);
    matResponses.put(0, 0, arrayResponses);

    //      // Clear any existing classifier
    //      if (classifier != null)
    //         classifier.clear();

    logger.info("Training size: " + matTraining.size());
    logger.info("Responses size: " + matResponses.size());

    // Create & train the classifier
    try {//from  w  w  w.jav  a  2s . c  om
        classifier = createClassifier();
        classifier.train(matTraining, Ml.ROW_SAMPLE, matResponses);
    } catch (CvException e) {
        // For reasons I haven't yet discerned, sometimes OpenCV throws an exception with the following message:
        // OpenCV Error: Assertion failed ((int)_sleft.size() < n && (int)_sright.size() < n) in calcDir, file /tmp/opencv320150620-1681-1u5iwhh/opencv-3.0.0/modules/ml/src/tree.cpp, line 1190
        // With one sample fewer, it can often recover... so attempt that, rather than failing miserably...
        //         logger.error("Classifier training error", e);
        logger.info("Will attempt retraining classifier with one sample fewer...");
        matTraining = matTraining.rowRange(0, matTraining.rows() - 1);
        matResponses = matResponses.rowRange(0, matResponses.rows() - 1);
        classifier = createClassifier();
        classifier.train(matTraining, Ml.ROW_SAMPLE, matResponses);
    }

    matTraining.release();
    matResponses.release();

    logger.info("Classifier trained with " + arrayResponses.length + " samples");
}

From source file:qupath.opencv.classify.OpenCvClassifier.java

License:Open Source License

@Override
public int classifyPathObjects(Collection<PathObject> pathObjects) {

    int counter = 0;
    float[] array = new float[measurements.size()];
    Mat samples = new Mat(1, array.length, CvType.CV_32FC1);

    Mat results = new Mat();

    for (PathObject pathObject : pathObjects) {
        MeasurementList measurementList = pathObject.getMeasurementList();
        int idx = 0;
        for (String m : measurements) {
            double value = measurementList.getMeasurementValue(m);

            if (normScale != null && normOffset != null)
                value = (value + normOffset[idx]) * normScale[idx];

            array[idx] = (float) value;
            idx++;//from   w ww .j  a  v  a2 s . co m
        }

        samples.put(0, 0, array);

        try {
            setPredictedClass(classifier, pathClasses, samples, results, pathObject);
            //            float prediction = classifier.predict(samples);
            //            
            ////            float prediction2 = classifier.predict(samples, results, StatModel.RAW_OUTPUT);
            //            float prediction2 = classifier.predict(samples, results, StatModel.RAW_OUTPUT);
            //            
            //            pathObject.setPathClass(pathClasses.get((int)prediction), prediction2);
        } catch (Exception e) {
            pathObject.setPathClass(null);
            logger.trace("Error with samples: " + samples.dump());
            //               e.printStackTrace();
        }
        //         }
        counter++;
    }

    samples.release();
    results.release();

    return counter;
}

From source file:qupath.opencv.DetectCytokeratinCV.java

License:Open Source License

public static Area getArea(final Mat mat) {
    if (mat.empty())
        return null;

    // Identify all contours
    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(mat, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
    if (contours.isEmpty()) {
        hierarchy.release();
        return null;
    }/*from   w w w.  j  av a2  s .  c  o m*/

    Area area = new Area();
    updateArea(contours, hierarchy, area, 0, 0);

    hierarchy.release();

    return area;
}