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:qupath.opencv.TissueSegmentationCommand.java

License:Open Source License

@Override
public void hierarchyChanged(PathObjectHierarchyEvent event) {
    if (img == null || isChanging || event.isChanging())
        return;//from   w  ww  .  j  a  v a  2s  . c  om

    List<PathObject> annotations = hierarchy.getObjects(null, PathAnnotationObject.class);
    if (annotation != null)
        annotations.remove(annotation);
    List<PathObject> background = new ArrayList<>();
    List<PathObject> foreground = new ArrayList<>();
    PathClass whitespaceClass = PathClassFactory.getDefaultPathClass(PathClasses.WHITESPACE);
    for (PathObject a : annotations) {
        if (a == annotation)
            continue;
        if (a.getPathClass() == whitespaceClass)
            background.add(a);
        else
            foreground.add(a);
    }

    if (background.isEmpty() || foreground.isEmpty())
        return;

    // Create labels
    Graphics2D g2d = imgMask.createGraphics();
    g2d.setColor(Color.BLACK);
    g2d.fillRect(0, 0, img.getWidth(), img.getHeight());
    g2d.scale((double) img.getWidth() / imageData.getServer().getWidth(),
            (double) img.getHeight() / imageData.getServer().getHeight());
    g2d.setColor(Color.GRAY);
    for (PathObject a : background) {
        g2d.draw(PathROIToolsAwt.getShape(a.getROI()));
    }
    g2d.setColor(Color.WHITE);
    for (PathObject a : foreground) {
        g2d.draw(PathROIToolsAwt.getShape(a.getROI()));
    }
    g2d.dispose();

    // Get the data to classify
    RTrees trees = RTrees.create();

    byte[] bytes = ((DataBufferByte) imgMask.getRaster().getDataBuffer()).getData();
    int n = 0;
    for (int i = 0; i < bytes.length; i++) {
        byte b = bytes[i];
        if (b == (byte) 0)
            continue;
        if (b == (byte) 255) {
            trainingResponses[n] = 2;
        } else {
            trainingResponses[n] = 1;
        }
        for (int k = 0; k < featureStride; k++)
            training[n * featureStride + k] = features[i * featureStride + k];
        n++;
    }

    Mat matTraining = new Mat(n, featureStride, CvType.CV_32FC1);
    matTraining.put(0, 0, Arrays.copyOf(training, n * featureStride));
    Mat matResponses = new Mat(n, 1, CvType.CV_32SC1);
    matResponses.put(0, 0, Arrays.copyOf(trainingResponses, n));

    trees.train(matTraining, Ml.ROW_SAMPLE, matResponses);

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

    Mat samples = new Mat(buf.length, featureStride, CvType.CV_32FC1);
    samples.put(0, 0, features);
    Mat results = new Mat(buf.length, 1, CvType.CV_32SC1);
    trees.predict(samples, results, RTrees.PREDICT_AUTO);
    BufferedImage imgOutput = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
    float[] resultsArray = new float[buf.length];
    results.get(0, 0, resultsArray);

    for (int i = 0; i < resultsArray.length; i++) {
        if (resultsArray[i] == 1f)
            imgOutput.setRGB(i % img.getWidth(), i / img.getWidth(), ColorTools.makeRGB(255, 0, 0));
        else if (resultsArray[i] == 2f)
            imgOutput.setRGB(i % img.getWidth(), i / img.getWidth(), ColorTools.makeRGB(255, 255, 255));
    }

    isChanging = true;
    hierarchy.fireHierarchyChangedEvent(this);
    isChanging = false;
}

From source file:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

@Override
public byte extractFeatures(Mat image, String outputFile) {
    int rows = image.rows();
    int cols = image.cols();
    int blockHeigth = rows / numberBlocksHeigth;
    int blockWidth = cols / numberBlocksWidth;
    int sizeOfBlocks = blockHeigth * blockWidth;
    rows = numberBlocksHeigth * blockHeigth;
    cols = numberBlocksWidth * blockWidth;
    Imgproc.resize(image, image, new Size(cols, rows));

    double[] vectors = new double[numberBlocksWidth * numberBlocksHeigth * 6]; // 3 channels, average and variance for each
    int counter = 0;

    for (int i = 0; i < rows; i += blockHeigth)
        for (int j = 0; j < cols; j += blockWidth) {
            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    double pixel[] = image.get(ii, jj);
                    vectors[counter] += pixel[0]; // H mean
                    vectors[counter + 1] += pixel[1]; // S mean
                    vectors[counter + 2] += pixel[2]; // V mean
                }//from   w w  w . ja  va2 s. co  m
            vectors[counter] /= sizeOfBlocks; // H mean
            vectors[counter + 1] /= sizeOfBlocks; // S mean
            vectors[counter + 2] /= sizeOfBlocks; // V mean

            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    double pixel[] = image.get(ii, jj);
                    vectors[counter + 3] += Math.pow(pixel[0] - vectors[counter], 2); // H variation
                    vectors[counter + 4] += Math.pow(pixel[1] - vectors[counter + 1], 2); // S variation
                    vectors[counter + 5] += Math.pow(pixel[2] - vectors[counter + 2], 2); // V variation
                }
            vectors[counter + 3] = Math.sqrt(vectors[counter + 3] / sizeOfBlocks); // H variation
            vectors[counter + 4] = Math.sqrt(vectors[counter + 4] / sizeOfBlocks); // S variation
            vectors[counter + 5] = Math.sqrt(vectors[counter + 5] / sizeOfBlocks); // V variation

            counter += 6;
        }

    writeVectorToFile(vectors, outputFile);
    image.release();
    return 1;
}

From source file:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

public byte extractFeaturesHUE(Mat image, String outputFile) {
    int rows = image.rows();
    int cols = image.cols();
    int blockHeigth = rows / numberBlocksHeigth;
    int blockWidth = cols / numberBlocksWidth;
    int sizeOfBlocks = blockHeigth * blockWidth;
    rows = numberBlocksHeigth * blockHeigth;
    cols = numberBlocksWidth * blockWidth;
    Imgproc.resize(image, image, new Size(cols, rows));
    Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2HSV);

    double[] vectors = new double[numberBlocksWidth * numberBlocksHeigth * 6]; // 3 channels, average and variance for each
    int counter = 0;

    double Hmean = 0;
    double Smean = 0;
    double Vmean = 0;

    for (int i = 0; i < rows; i += blockHeigth)
        for (int j = 0; j < cols; j += blockWidth) {
            double pixel[] = image.get(i, j);
            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    if (vectors[counter] < pixel[0])
                        vectors[counter] = pixel[0]; // H max
                    if (vectors[counter + 1] < pixel[1])
                        vectors[counter + 1] = pixel[1]; // H max
                    if (vectors[counter + 2] < pixel[2])
                        vectors[counter + 2] = pixel[1]; // H max

                    Hmean += pixel[0]; // H mean
                    Smean += pixel[1]; // S mean
                    Vmean += pixel[2]; // V mean
                }/*from  ww  w.  j  a  v a 2  s .  c o  m*/
            vectors[counter] *= 2; // OpenCV scales H to H/2 to fit uchar;

            Hmean = Hmean * 2 / sizeOfBlocks; // H mean
            Smean /= sizeOfBlocks; // S mean
            Vmean /= sizeOfBlocks; // V mean

            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    vectors[counter + 3] += Math.pow(pixel[0] * 2 - Hmean, 2); // H variation
                    vectors[counter + 4] += Math.pow(pixel[1] - Smean, 2); // S variation
                    vectors[counter + 5] += Math.pow(pixel[2] - Vmean, 2); // V variation
                }
            vectors[counter + 3] = Math.sqrt(vectors[counter + 3] / sizeOfBlocks); // H variation
            vectors[counter + 4] = Math.sqrt(vectors[counter + 4] / sizeOfBlocks); // S variation
            vectors[counter + 5] = Math.sqrt(vectors[counter + 5] / sizeOfBlocks); // V variation

            counter += 6;
        }

    writeVectorToFile(vectors, outputFile);
    image.release();
    return 1;
}

From source file:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

public double[] extractFeaturesHUE(Mat image) {
    int rows = image.rows();
    int cols = image.cols();
    int blockHeigth = rows / numberBlocksHeigth;
    int blockWidth = cols / numberBlocksWidth;
    int sizeOfBlocks = blockHeigth * blockWidth;
    rows = numberBlocksHeigth * blockHeigth;
    cols = numberBlocksWidth * blockWidth;
    Imgproc.resize(image, image, new Size(cols, rows));
    Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2HSV);

    double[] vectors = new double[numberBlocksWidth * numberBlocksHeigth * 6]; // 3 channels, average and variance for each
    int counter = 0;

    double Hmean = 0;
    double Smean = 0;
    double Vmean = 0;

    for (int i = 0; i < rows; i += blockHeigth)
        for (int j = 0; j < cols; j += blockWidth) {
            double pixel[] = image.get(i, j);
            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    if (vectors[counter] < pixel[0])
                        vectors[counter] = pixel[0]; // H max
                    if (vectors[counter + 1] < pixel[1])
                        vectors[counter + 1] = pixel[1]; // H max
                    if (vectors[counter + 2] < pixel[2])
                        vectors[counter + 2] = pixel[1]; // H max

                    Hmean += pixel[0]; // H mean
                    Smean += pixel[1]; // S mean
                    Vmean += pixel[2]; // V mean
                }//from   w  ww  . ja va 2  s  . c om
            vectors[counter] *= 2; // OpenCV scales H to H/2 to fit uchar;

            Hmean = Hmean * 2 / sizeOfBlocks; // H mean
            Smean /= sizeOfBlocks; // S mean
            Vmean /= sizeOfBlocks; // V mean

            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    vectors[counter + 3] += Math.pow(pixel[0] * 2 - Hmean, 2); // H variation
                    vectors[counter + 4] += Math.pow(pixel[1] - Smean, 2); // S variation
                    vectors[counter + 5] += Math.pow(pixel[2] - Vmean, 2); // V variation
                }
            vectors[counter + 3] = Math.sqrt(vectors[counter + 3] / sizeOfBlocks); // H variation
            vectors[counter + 4] = Math.sqrt(vectors[counter + 4] / sizeOfBlocks); // S variation
            vectors[counter + 5] = Math.sqrt(vectors[counter + 5] / sizeOfBlocks); // V variation

            counter += 6;
        }

    image.release();
    return vectors;
}

From source file:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

public double[] extractFeatures(Mat image) {
    //       Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2HSV);
    int rows = image.rows();
    int cols = image.cols();
    int blockHeigth = rows / numberBlocksHeigth;
    int blockWidth = cols / numberBlocksWidth;
    int sizeOfBlocks = blockHeigth * blockWidth;
    System.out.println(sizeOfBlocks);
    rows = numberBlocksHeigth * blockHeigth;
    cols = numberBlocksWidth * blockWidth;
    Imgproc.resize(image, image, new Size(cols, rows));

    double[] vectors = new double[numberBlocksWidth * numberBlocksHeigth * 6]; // 3 channels, average and variance for each
    int counter = 0;

    for (int i = 0; i < rows; i += blockHeigth)
        for (int j = 0; j < cols; j += blockWidth) {
            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    double pixel[] = image.get(ii, jj);
                    vectors[counter] += pixel[0]; // H mean
                    vectors[counter + 1] += pixel[1]; // S mean
                    vectors[counter + 2] += pixel[2]; // V mean
                }// w  w  w.  j a v  a  2  s.co  m
            vectors[counter] /= sizeOfBlocks; // H mean
            vectors[counter + 1] /= sizeOfBlocks; // S mean
            vectors[counter + 2] /= sizeOfBlocks; // V mean

            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    double pixel[] = image.get(ii, jj);
                    vectors[counter + 3] += Math.pow(pixel[0] - vectors[counter], 2); // H variation
                    vectors[counter + 4] += Math.pow(pixel[1] - vectors[counter + 1], 2); // S variation
                    vectors[counter + 5] += Math.pow(pixel[2] - vectors[counter + 2], 2); // V varation
                }
            vectors[counter + 3] = Math.sqrt(vectors[counter + 3] / sizeOfBlocks); // H variation
            vectors[counter + 4] = Math.sqrt(vectors[counter + 4] / sizeOfBlocks); // S variation
            vectors[counter + 5] = Math.sqrt(vectors[counter + 5] / sizeOfBlocks); // V varation

            counter += 6;
        }
    image.release();
    return vectors;
}

From source file:tv.danmaku.ijk.media.example.activities.VideoActivity.java

License:Apache License

public boolean onTouch(View v, MotionEvent event) {
    int cols = mRgba.cols();
    int rows = mRgba.rows();

    int xOffset = (mOpenCvCameraView.getWidth() - cols) / 2;
    int yOffset = (mOpenCvCameraView.getHeight() - rows) / 2;

    int x = (int) event.getX() - xOffset;
    int y = (int) event.getY() - yOffset;

    Log.i(TAG, "Touch image coordinates: (" + x + ", " + y + ")");

    if ((x < 0) || (y < 0) || (x > cols) || (y > rows))
        return false;

    Rect touchedRect = new Rect();

    touchedRect.x = (x > 5) ? x - 5 : 0;
    touchedRect.y = (y > 5) ? y - 5 : 0;

    touchedRect.width = (x + 5 < cols) ? x + 5 - touchedRect.x : cols - touchedRect.x;
    touchedRect.height = (y + 5 < rows) ? y + 5 - touchedRect.y : rows - touchedRect.y;

    Mat touchedRegionRgba = mRgba.submat(touchedRect);

    Mat touchedRegionHsv = new Mat();
    Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);

    // Calculate average color of touched region
    mBlobColorHsv = Core.sumElems(touchedRegionHsv);
    int pointCount = touchedRect.width * touchedRect.height;
    for (int i = 0; i < mBlobColorHsv.val.length; i++)
        mBlobColorHsv.val[i] /= pointCount;

    mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);

    Log.i(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] + ", "
            + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");

    mDetector.setHsvColor(mBlobColorHsv);

    Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);

    mIsColorSelected = true;//  w w  w.j a v  a  2  s .  c o  m

    touchedRegionRgba.release();
    touchedRegionHsv.release();

    return false; // don't need subsequent touch events
}

From source file:uk.ac.horizon.artcodes.detect.marker.MarkerDetector.java

License:Open Source License

@Override
public void process(ImageBuffers buffers) {
    final ArrayList<MatOfPoint> contours = new ArrayList<>();
    final Mat hierarchy = new Mat();
    // Make sure the image is rotated before the contours are generated, if necessary
    //if (Feature.get(this.context, R.bool.feature_combined_markers).isEnabled() || outlineDisplay != OutlineDisplay.none || codeDisplay == CodeDisplay.visible)
    //{/*from  w  ww .j a v a 2 s .  c  o m*/
    // if statement commented out as there was a bug where the overlay was not getting cleared
    // after cycling through the threshold views.
    buffers.getOverlay();
    //}
    try {
        final List<Marker> foundMarkers = new ArrayList<>();
        Imgproc.findContours(buffers.getImageInGrey(), contours, hierarchy, Imgproc.RETR_TREE,
                Imgproc.CHAIN_APPROX_NONE);
        for (int i = 0; i < contours.size(); i++) {
            final Marker marker = createMarkerForNode(i, contours, hierarchy);
            if (marker != null) {
                final String markerCode = getCodeKey(marker);
                if (validCodes.isEmpty() || validCodes.contains(markerCode)) {
                    // If this marker has a minimum size set and is smaller: continue in loop.
                    Action action = experience.getActionForCode(markerCode);
                    if (action != null && action.getMinimumSize() != null) {
                        double minimumSize = action.getMinimumSize();
                        Rect boundingRect = Imgproc.boundingRect(contours.get(i));
                        if (!(boundingRect.width / (float) buffers.getImageInAnyFormat().cols() > minimumSize
                                || boundingRect.height
                                        / (float) buffers.getImageInAnyFormat().rows() > minimumSize)) {
                            continue;
                        }
                    }

                    foundMarkers.add(marker);

                    if (outlineDisplay != OutlineDisplay.none) {
                        Mat overlay = buffers.getOverlay();
                        if (outlineDisplay == OutlineDisplay.regions) {
                            double[] nodes = hierarchy.get(0, i);
                            int currentRegionIndex = (int) nodes[FIRST_NODE];

                            while (currentRegionIndex >= 0) {
                                Imgproc.drawContours(overlay, contours, currentRegionIndex, outlineColour, 4);
                                Imgproc.drawContours(overlay, contours, currentRegionIndex, regionColour, 2);

                                nodes = hierarchy.get(0, currentRegionIndex);
                                currentRegionIndex = (int) nodes[NEXT_NODE];
                            }
                        }

                        Imgproc.drawContours(overlay, contours, i, outlineColour, 7);
                        Imgproc.drawContours(overlay, contours, i, detectedColour, 5);
                    }

                    if (codeDisplay == CodeDisplay.visible) {
                        Mat overlay = buffers.getOverlay();
                        Rect bounds = Imgproc.boundingRect(contours.get(i));
                        Imgproc.putText(overlay, markerCode, bounds.tl(), Core.FONT_HERSHEY_SIMPLEX, 1,
                                outlineColour, 5);
                        Imgproc.putText(overlay, markerCode, bounds.tl(), Core.FONT_HERSHEY_SIMPLEX, 1,
                                detectedColour, 3);
                    }
                }
            }
        }

        buffers.setDetected(!foundMarkers.isEmpty());
        handler.onMarkersDetected(foundMarkers, contours, hierarchy, buffers.getImageInGrey().size());
    } finally {
        contours.clear();
        hierarchy.release();
    }
}

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

License:Open Source License

@Override
public void process(ImageBuffers buffers) {
    Mat image = buffers.getImageInGrey();
    Imgproc.GaussianBlur(image, image, new Size(5, 5), 0);

    if (display == Display.greyscale) {
        Imgproc.cvtColor(image, buffers.getOverlay(false), Imgproc.COLOR_GRAY2BGRA);
    }//ww w.ja  v  a  2  s .  com

    tiles = 1;
    final int tileHeight = (int) image.size().height / tiles;
    final int tileWidth = (int) image.size().width / tiles;

    // Split image into tiles and apply process on each image tile separately.
    for (int tileRow = 0; tileRow < tiles; tileRow++) {
        final int startRow = tileRow * tileHeight;
        int endRow;
        if (tileRow < tiles - 1) {
            endRow = (tileRow + 1) * tileHeight;
        } else {
            endRow = (int) image.size().height;
        }

        for (int tileCol = 0; tileCol < tiles; tileCol++) {
            final int startCol = tileCol * tileWidth;
            int endCol;
            if (tileCol < tiles - 1) {
                endCol = (tileCol + 1) * tileWidth;
            } else {
                endCol = (int) image.size().width;
            }

            final Mat tileMat = image.submat(startRow, endRow, startCol, endCol);
            Imgproc.threshold(tileMat, tileMat, 127, 255, Imgproc.THRESH_OTSU);
            tileMat.release();
        }
    }

    if (display == Display.threshold) {
        Imgproc.cvtColor(image, buffers.getOverlay(false), Imgproc.COLOR_GRAY2BGRA);
    }

    buffers.setImage(image);
}

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

License:Open Source License

@Override
public void process(ImageBuffers buffers) {
    Mat image = buffers.getImageInGrey();
    Imgproc.GaussianBlur(image, image, new Size(5, 5), 0);

    if (display == Display.greyscale) {
        Imgproc.cvtColor(image, buffers.getOverlay(false), Imgproc.COLOR_GRAY2BGRA);
    }//w ww . jav  a  2  s.c o  m

    if (!buffers.hasDetected()) {
        tiles = (tiles % 9) + 1;
    }
    final int tileHeight = (int) image.size().height / tiles;
    final int tileWidth = (int) image.size().width / tiles;

    // Split image into tiles and apply process on each image tile separately.
    for (int tileRow = 0; tileRow < tiles; tileRow++) {
        final int startRow = tileRow * tileHeight;
        int endRow;
        if (tileRow < tiles - 1) {
            endRow = (tileRow + 1) * tileHeight;
        } else {
            endRow = (int) image.size().height;
        }

        for (int tileCol = 0; tileCol < tiles; tileCol++) {
            final int startCol = tileCol * tileWidth;
            int endCol;
            if (tileCol < tiles - 1) {
                endCol = (tileCol + 1) * tileWidth;
            } else {
                endCol = (int) image.size().width;
            }

            final Mat tileMat = image.submat(startRow, endRow, startCol, endCol);
            Imgproc.threshold(tileMat, tileMat, 127, 255, Imgproc.THRESH_OTSU);
            tileMat.release();
        }
    }

    if (display == Display.threshold) {
        Imgproc.cvtColor(image, buffers.getOverlay(false), Imgproc.COLOR_GRAY2BGRA);
    }

    buffers.setImage(image);
}

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

License:Open Source License

public void release() {
    lut.release();/*from ww  w .java  2 s .c  o  m*/
    for (Mat channel : channels) {
        channel.release();
    }
    emptyMatMask.release();
    for (Mat histogram : histograms) {
        histogram.release();
    }
    size.release();
    range.release();
}