Example usage for org.opencv.core Mat copyTo

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

Introduction

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

Prototype

public void copyTo(Mat m) 

Source Link

Usage

From source file:imageanalyzercv.ImageAnalyzerCV.java

/**
 * @param args the command line arguments
 *//*from w w w. j  av a  2s .  co  m*/
public static void main(String[] args) {
    System.out.println("path: " + System.getProperty("java.library.path"));
    System.loadLibrary("opencv_java300");

    Mat m = Highgui.imread("/Users/chintan/Downloads/software/image_analyis/mydata/SAM_0763.JPG");
    System.out.println("m = " + m.height());
    MatOfKeyPoint points = new MatOfKeyPoint();
    FeatureDetector.create(FeatureDetector.SURF).detect(m, points);

    Mat m2 = Highgui.imread("/Users/chintan/Downloads/software/image_analyis/mydata/SAM_0764.JPG");
    System.out.println("m = " + m2.height());
    MatOfKeyPoint points2 = new MatOfKeyPoint();
    FeatureDetector.create(FeatureDetector.SURF).detect(m2, points2);

    DescriptorExtractor SurfExtractor = DescriptorExtractor.create(DescriptorExtractor.BRISK);
    Mat imag1Desc = new Mat();
    SurfExtractor.compute(m, points, imag1Desc);

    Mat imag2Desc = new Mat();
    SurfExtractor.compute(m2, points2, imag2Desc);

    MatOfDMatch matches = new MatOfDMatch();

    Mat imgd = new Mat();
    imag1Desc.copyTo(imgd);
    System.out.println(imgd.size());
    DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING).match(imag2Desc, imag1Desc,
            (MatOfDMatch) matches);

    double min_distance = 1000.0;
    double max_distance = 0.0;
    DMatch[] matchArr = matches.toArray();
    for (int i = 0; i < matchArr.length; i++) {
        if (matchArr[i].distance > max_distance)
            max_distance = matchArr[i].distance;
        if (matchArr[i].distance < min_distance)
            min_distance = matchArr[i].distance;
    }

    ArrayList<DMatch> good_matches = new ArrayList<DMatch>();

    System.out.println("Min Distance: " + min_distance + "  Max distance: " + max_distance);
    double totalScore = 0.0;
    for (int j = 0; j < imag1Desc.rows() && j < matchArr.length; j++) {
        if ((matchArr[j].distance <= (11 * min_distance)) && (matchArr[j].distance >= min_distance * 1)) {
            good_matches.add(matchArr[j]);
            //System.out.println(matchArr[j]);
            totalScore = totalScore + matchArr[j].distance;

        }
        //good_matches.add(matchArr[j]);

    }
    System.out.println((1 - (totalScore / (good_matches.size() * ((max_distance + min_distance) / 2)))) * 100);
    // System.out.println(matches.toList().size());
    Mat out = new Mat();
    MatOfDMatch mats = new MatOfDMatch();
    mats.fromList(good_matches);
    Features2d.drawMatches(m2, points2, m, points, mats, out);
    Highgui.imwrite("/Users/chintan/Downloads/one2.jpg", out);
}

From source file:javaapplication1.Ocv.java

public void makeFacesGray(String filter, String input, String output) {
    // load the filter and create a classifier with it
    File f = new File(filter);
    final CascadeClassifier faceDetector = new CascadeClassifier(this.filter);

    // load the image and read it into a matrix
    File f2 = new File(input);
    final Mat image = Highgui.imread(this.input);

    // run a face detector on the image
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    // inform about faces detected
    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

    // make each face gray
    for (Rect rect : faceDetections.toArray()) {
        // get a shallow copy of the submatrix for the face
        Mat sub = image.submat(rect);
        // convert it to gray, then back to BGR
        Imgproc.cvtColor(sub, sub, Imgproc.COLOR_BGR2GRAY, 1);
        Imgproc.cvtColor(sub, sub, Imgproc.COLOR_GRAY2BGR, 3);
        // copy back to the original image
        sub.copyTo(image.submat(rect));
    }//from   www  . ja  v  a2s. c  om

    // save file
    Highgui.imwrite(this.output, image);
}

From source file:karthik.Barcode.CandidateMatrixBarcode.java

License:Open Source License

CandidateResult NormalizeCandidateRegion(double angle) {
    /* candidateRegion is the RotatedRect which contains a candidate region for the barcode
     // angle is the rotation angle or USE_ROTATED_RECT_ANGLE for this function to 
     // estimate rotation angle from the rect parameter
     // returns Mat containing cropped area(region of interest) with just the barcode 
     // The barcode region is from the *original* image, not the scaled image
     // the cropped area is also rotated as necessary to be horizontal or vertical rather than skewed        
     // Some parts of this function are from http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
     // and http://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c
     *///www .java  2  s.co m

    double rotation_angle;
    CandidateResult result = new CandidateResult();

    // scale candidate region back up to original size to return cropped part from *original* image 
    // need the 1.0 there to force floating-point arithmetic from int values
    double scale_factor = img_details.src_original.rows() / (1.0 * img_details.src_grayscale.rows());

    // expand the region found - this helps capture the entire code including the border zone
    candidateRegion.size.width += 2 * params.RECT_WIDTH;
    candidateRegion.size.height += 2 * params.RECT_HEIGHT;

    // calculate location of rectangle in original image and its corner points
    RotatedRect scaledRegion = new RotatedRect(candidateRegion.center, candidateRegion.size,
            candidateRegion.angle);
    scaledRegion.center.x = scaledRegion.center.x * scale_factor;
    scaledRegion.center.y = scaledRegion.center.y * scale_factor;
    scaledRegion.size.height *= scale_factor;
    scaledRegion.size.width *= scale_factor;

    scaledRegion.points(img_details.scaledCorners);
    // lets get the coordinates of the ROI in the original image and save it

    result.ROI_coords = Arrays.copyOf(img_details.scaledCorners, 4);

    // get the bounding rectangle of the ROI by sorting its corner points
    // we do it manually because RotatedRect can generate corner points outside the Mat area
    Arrays.sort(img_details.scaledCorners, CandidateBarcode.get_x_comparator());
    int leftCol = (int) img_details.scaledCorners[0].x;
    int rightCol = (int) img_details.scaledCorners[3].x;
    leftCol = (leftCol < 0) ? 0 : leftCol;
    rightCol = (rightCol > img_details.src_original.cols() - 1) ? img_details.src_original.cols() - 1
            : rightCol;

    Arrays.sort(img_details.scaledCorners, CandidateBarcode.get_y_comparator());
    int topRow = (int) img_details.scaledCorners[0].y;
    int bottomRow = (int) img_details.scaledCorners[3].y;
    topRow = (topRow < 0) ? 0 : topRow;
    bottomRow = (bottomRow > img_details.src_original.rows() - 1) ? img_details.src_original.rows() - 1
            : bottomRow;

    Mat ROI_region = img_details.src_original.submat(topRow, bottomRow, leftCol, rightCol);

    // create a container that is a square with side = diagonal of ROI.
    // this is large enough to accommodate the ROI region with rotation without cropping it

    int orig_rows = bottomRow - topRow;
    int orig_cols = rightCol - leftCol;
    int diagonal = (int) Math.sqrt(orig_rows * orig_rows + orig_cols * orig_cols);

    int newWidth = diagonal + 1;
    int newHeight = diagonal + 1;

    int offsetX = (newWidth - orig_cols) / 2;
    int offsetY = (newHeight - orig_rows) / 2;

    Mat enlarged_ROI_container = new Mat(newWidth, newHeight, img_details.src_original.type());
    enlarged_ROI_container.setTo(ZERO_SCALAR);

    // copy ROI to centre of container and rotate it
    ROI_region.copyTo(enlarged_ROI_container.rowRange(offsetY, offsetY + orig_rows).colRange(offsetX,
            offsetX + orig_cols));
    Point enlarged_ROI_container_centre = new Point(enlarged_ROI_container.rows() / 2.0,
            enlarged_ROI_container.cols() / 2.0);
    Mat rotated = Mat.zeros(enlarged_ROI_container.size(), enlarged_ROI_container.type());

    if (angle == Barcode.USE_ROTATED_RECT_ANGLE)
        rotation_angle = estimate_barcode_orientation();
    else
        rotation_angle = angle;

    // perform the affine transformation
    img_details.rotation_matrix = Imgproc.getRotationMatrix2D(enlarged_ROI_container_centre, rotation_angle,
            1.0);
    img_details.rotation_matrix.convertTo(img_details.rotation_matrix, CvType.CV_32F); // convert type so matrix multip. works properly

    img_details.newCornerCoord.setTo(ZERO_SCALAR);

    // convert scaledCorners to contain locations of corners in enlarged_ROI_container Mat
    img_details.scaledCorners[0] = new Point(offsetX, offsetY);
    img_details.scaledCorners[1] = new Point(offsetX, offsetY + orig_rows);
    img_details.scaledCorners[2] = new Point(offsetX + orig_cols, offsetY);
    img_details.scaledCorners[3] = new Point(offsetX + orig_cols, offsetY + orig_rows);
    // calculate the new location for each corner point of the rectangle ROI after rotation
    for (int r = 0; r < 4; r++) {
        img_details.coord.put(0, 0, img_details.scaledCorners[r].x);
        img_details.coord.put(1, 0, img_details.scaledCorners[r].y);
        Core.gemm(img_details.rotation_matrix, img_details.coord, 1, img_details.delta, 0,
                img_details.newCornerCoord);
        updatePoint(img_details.newCornerPoints.get(r), img_details.newCornerCoord.get(0, 0)[0],
                img_details.newCornerCoord.get(1, 0)[0]);
    }
    rotated.setTo(ZERO_SCALAR);
    Imgproc.warpAffine(enlarged_ROI_container, rotated, img_details.rotation_matrix,
            enlarged_ROI_container.size(), Imgproc.INTER_CUBIC);
    // sort rectangles points in order by first sorting all 4 points based on x
    // we then sort the first two based on y and then the next two based on y
    // this leaves the array in order top-left, bottom-left, top-right, bottom-right
    Collections.sort(img_details.newCornerPoints, CandidateBarcode.get_x_comparator());
    Collections.sort(img_details.newCornerPoints.subList(0, 2), CandidateBarcode.get_y_comparator());
    Collections.sort(img_details.newCornerPoints.subList(2, 4), CandidateBarcode.get_y_comparator());

    // calc height and width of rectangular region

    double height = length(img_details.newCornerPoints.get(1), img_details.newCornerPoints.get(0));
    double width = length(img_details.newCornerPoints.get(2), img_details.newCornerPoints.get(0));

    // create destination points for warpPerspective to map to
    updatePoint(img_details.transformedPoints.get(0), 0, 0);
    updatePoint(img_details.transformedPoints.get(1), 0, height);
    updatePoint(img_details.transformedPoints.get(2), width, 0);
    updatePoint(img_details.transformedPoints.get(3), width, height);

    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(
            Converters.vector_Point2f_to_Mat(img_details.newCornerPoints),
            Converters.vector_Point2f_to_Mat(img_details.transformedPoints));
    Mat perspectiveOut = Mat.zeros((int) height + 2, (int) width + 2, CvType.CV_32F);
    Imgproc.warpPerspective(rotated, perspectiveOut, perspectiveTransform, perspectiveOut.size(),
            Imgproc.INTER_CUBIC);

    result.ROI = perspectiveOut;
    return result;
}

From source file:logic.featurepointextractor.EyeBrowsFPE.java

/**
 * getSkeleton  obtain thin 1-pixel region from contour. 
 * @param src   input binary image//from   w ww .j  a  v a2  s  . c  o m
 * @return      binary image 
 */

private Mat getSkeleton(Mat src) {
    Mat skel = new Mat(src.rows(), src.cols(), CV_8UC1, new Scalar(0));
    Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(3, 3));
    Mat tmp = new Mat();
    Mat eroded = new Mat();
    boolean done = false;

    do {
        Imgproc.morphologyEx(src, eroded, Imgproc.MORPH_ERODE, element);
        Imgproc.morphologyEx(eroded, tmp, Imgproc.MORPH_DILATE, element);
        Core.subtract(src, tmp, tmp);
        Core.bitwise_or(skel, tmp, skel);
        eroded.copyTo(src);

        done = (Core.countNonZero(src) == 0);
    } while (!done);

    return skel;
}

From source file:net.bsrc.cbod.opencv.OpenCV.java

public static Mat copyImage(Mat org) {
    Mat copy = new Mat();
    org.copyTo(copy);
    return copy;
}

From source file:openbjk.Identificador.java

public Mat norm_0_255(Mat input) {

    Mat dst = null;/*from   ww w  . ja v  a 2s  .c  om*/
    switch (input.channels()) {
    case 1:
        Core.normalize(input, dst, 0, 255, 2, CvType.CV_8UC1);
        break;
    case 3:
        Core.normalize(input, dst, 0, 255, 2, CvType.CV_8UC3);
        break;
    default:
        input.copyTo(dst);
    }

    return dst;
}

From source file:opencltest.YetAnotherTestT.java

public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    Mat kernel = new Mat(3, 3, CV_8UC1);
    kernel.put(0, 0, new double[] { 0, 1, 0, 1, 1, 1, 0, 1, 0 });

    Mat source = Imgcodecs.imread("test.smaller.png");
    Mat blur = new Mat();
    Mat edges = new Mat();
    Mat dilated = new Mat();

    Imgproc.GaussianBlur(source, blur, new Size(13, 13), 0);
    Imgproc.Canny(blur, edges, 10, 30, 5, false);
    //        Imgproc.cvtColor(edges, edges, Imgproc.COLOR_RGB2GRAY);
    //        Imgproc.adaptiveThreshold(edges, edges, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 5, 2);
    //        Core.bitwise_not(edges, edges);
    //        Imgproc.dilate(edges, edges, kernel);
    //        Imgproc.dilate(edges, dilated, kernel);
    dilated = edges;//ww w .  j  av a  2 s.  c  o m
    //        Core.bitwise_not(edges, edges);

    Mat lines = new Mat();
    Imgproc.HoughLinesP(dilated, lines, 1, Math.PI / 180, 300, 10, 70);

    Mat empty = new Mat(source.height(), source.width(), source.type());
    //        paintLines(empty, lines);

    List<MatOfPoint> contours = new ArrayList<>();
    Mat hier = new Mat();
    Imgproc.findContours(edges, contours, hier, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    Mat foundSquare = new Mat(source.height(), source.width(), CvType.CV_8UC4);
    source.copyTo(foundSquare);

    List<Double> hor = new ArrayList<>();
    for (Iterator<MatOfPoint> iterator = contours.iterator(); iterator.hasNext();) {
        MatOfPoint next = iterator.next();
        Rect bounding = Imgproc.boundingRect(next);
        int tr = 20;
        if (diffLessThan(bounding.size().width - 40, tr) && diffLessThan(bounding.size().height - 40, tr)) {
            Imgproc.rectangle(empty, bounding.tl(), bounding.br(), randomColor(), 3);
            //                hor.add(bounding.x + 0.0);
            hor.add(bounding.x + bounding.width / 2.0 + 0.0);
            drawRect(bounding, foundSquare);
        }
    }

    Imgcodecs.imwrite("test_2.png", source);
    Imgcodecs.imwrite("test_3.png", dilated);
    Imgcodecs.imwrite("test_4.png", empty);
    Imgcodecs.imwrite("test_h.png", foundSquare);

    hor.sort(Double::compare);
    double low = hor.get(0);
    double hih = hor.get(hor.size() - 1);
    double n = hor.size();
    Function<Double, Double> K = (d) -> (Math.abs(d) <= 1) ? ((3.0 / 4.0) * (1 - (d * d))) : 0;//epanechnikov kernel
    List<Double> result = new ArrayList<>();
    double h = 10;
    for (int i = 0; i < source.width() + 1; i++)
        result.add(0.0);
    for (double d = low; d <= hih; d += 1) {
        double sum = 0;
        for (Double di : hor) {
            sum += K.apply((d - di) / h);
        }
        result.set((int) d, sum / (n * h));
        System.out.println(sum / (n * h));
    }
    normalize(result, 255);
    Mat test = new Mat(source.height(), source.width(), source.type());
    source.copyTo(test);
    draw(result, test);
    Imgcodecs.imwrite("test_uwot.png", test);
}

From source file:opencv.CaptchaDetection.java

/***
 * ?/*  w ww. ja v a  2s .c  o m*/
 * @param src
 * @return 
 */
private static String dect_number(List<Mat> src) {
    String answer = "";

    for (Mat numRoi : src) {
        Mat zoomNum = new Mat(numRoi.rows() * 2, numRoi.cols() * 2, CvType.CV_8UC1, new Scalar(0));
        numRoi.copyTo(
                zoomNum.submat(new Rect(numRoi.cols() / 2, numRoi.rows() / 2, numRoi.cols(), numRoi.rows())));

        double matchMin = Double.MAX_VALUE;
        int matchSample = 0;

        for (Map.Entry<Integer, List<Mat>> iter : sampleMat.entrySet()) {
            for (Mat sample : iter.getValue()) {
                int result_cols = zoomNum.cols() - sample.cols() + 1;
                int result_rows = zoomNum.rows() - sample.rows() + 1;

                Mat resultImg = new Mat(result_rows, result_cols, CvType.CV_32FC1);

                Imgproc.matchTemplate(zoomNum, sample, resultImg, Imgproc.TM_SQDIFF);

                Core.MinMaxLocResult mmr = Core.minMaxLoc(resultImg);

                if (matchMin > mmr.minVal) {
                    matchMin = mmr.minVal;
                    matchSample = iter.getKey();
                }
            }
        }
        answer += matchSample / 2;
        //out.println("NumRio\tmatch sample :  " + matchSample + "\tmatch value : " + matchMin);
    }

    //out.println("Answer is : " + answer);
    return answer;
}

From source file:opencvdemos.BallGame.java

License:Apache License

private Image grabFrame() {
    // Init everything
    Image imageToShow = null;//w w w.ja v a 2  s . c om
    Mat frame = new Mat();

    // Check if the capture is open
    if (this.capture.isOpened()) {
        try {
            // Read the current frame
            this.capture.read(frame);
            // Flip image for easy object manipulation
            Core.flip(frame, frame, 1);

            // If the frame is not empty, process it
            if (!frame.empty()) {
                // Init
                Mat blurredImage = new Mat();
                Mat hsvImage = new Mat();
                Mat mask = new Mat();
                Mat morphOutput = new Mat();

                // Remove some noise
                Imgproc.blur(frame, blurredImage, new Size(7, 7));

                // Convert the frame to HSV
                Imgproc.cvtColor(blurredImage, hsvImage, Imgproc.COLOR_BGR2HSV);

                // Get thresholding values from the UI
                // Remember: H ranges 0-180, S and V range 0-255
                Scalar minValues = new Scalar(this.hueStart.getValue(), this.saturationStart.getValue(),
                        this.valueStart.getValue());
                Scalar maxValues = new Scalar(this.hueStop.getValue(), this.saturationStop.getValue(),
                        this.valueStop.getValue());

                // Show the current selected HSV range
                String valuesToPrint = "Hue range: " + minValues.val[0] + "-" + maxValues.val[0]
                        + ". Sat. range: " + minValues.val[1] + "-" + maxValues.val[1] + ". Value range: "
                        + minValues.val[2] + "-" + maxValues.val[2];
                hsvCurrentValues.setText(valuesToPrint);

                // Threshold HSV image to select object
                Core.inRange(hsvImage, minValues, maxValues, mask);
                // Show the partial output
                maskImage.getGraphics().drawImage(this.mat2Image(mask), 0, 0, 205, 154, null);

                // Morphological operators
                // Dilate with large element, erode with small ones
                Mat dilateElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(24, 24));
                Mat erodeElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(12, 12));

                Imgproc.erode(mask, morphOutput, erodeElement);
                Imgproc.erode(mask, morphOutput, erodeElement);

                Imgproc.dilate(mask, morphOutput, dilateElement);
                Imgproc.dilate(mask, morphOutput, dilateElement);

                // Show the partial output
                morphImage.getGraphics().drawImage(this.mat2Image(morphOutput), 0, 0, 205, 154, null);

                // Find the object(s) contours and show them
                frame = this.findAndDrawObjects(morphOutput, frame);

                // Calculate centers and move ball
                Mat temp = new Mat();
                morphOutput.copyTo(temp);
                List<MatOfPoint> contours = new ArrayList<>();
                Imgproc.findContours(temp, contours, new Mat(), Imgproc.RETR_EXTERNAL,
                        Imgproc.CHAIN_APPROX_SIMPLE);
                for (int i = 0; i < contours.size(); i++) {
                    Rect objectBoundingRectangle = Imgproc.boundingRect(contours.get(i));
                    int x = objectBoundingRectangle.x + objectBoundingRectangle.width / 2;
                    int y = objectBoundingRectangle.y + objectBoundingRectangle.height / 2;

                    // Move ball
                    if (!ballChanged) {
                        if (b.x > objectBoundingRectangle.x
                                && b.x < objectBoundingRectangle.x + objectBoundingRectangle.width
                                && b.y > objectBoundingRectangle.y
                                && b.y < objectBoundingRectangle.y + objectBoundingRectangle.height) {
                            b.dx = -b.dx;
                            b.dy = -b.dy;
                            ballChanged = true;
                        }
                    }

                    // Show crosshair
                    Imgproc.circle(frame, new Point(x, y), 20, new Scalar(0, 255, 0), 2);
                    Imgproc.line(frame, new Point(x, y), new Point(x, y - 25), new Scalar(0, 255, 0), 2);
                    Imgproc.line(frame, new Point(x, y), new Point(x, y + 25), new Scalar(0, 255, 0), 2);
                    Imgproc.line(frame, new Point(x, y), new Point(x - 25, y), new Scalar(0, 255, 0), 2);
                    Imgproc.line(frame, new Point(x, y), new Point(x + 25, y), new Scalar(0, 255, 0), 2);
                    Imgproc.putText(frame, "Tracking object at (" + x + "," + y + ")", new Point(x, y), 1, 1,
                            new Scalar(255, 0, 0), 2);
                }
                ballChanged = false;

                // Move and draw the ball
                if (b.dx < 0)
                    b.dx = ballSpeed.getValue() * -1;
                else
                    b.dx = ballSpeed.getValue();
                if (b.dy < 0)
                    b.dy = ballSpeed.getValue() * -1;
                else
                    b.dy = ballSpeed.getValue();
                b.move();
                Imgproc.circle(frame, new Point(b.x, b.y), b.r, new Scalar(255, 0, 255), -1);

                // convert the Mat object (OpenCV) to Image (Java AWT)
                imageToShow = mat2Image(frame);
            }

        } catch (Exception e) {
            // log the error
            System.err.println("Exception during the frame elaboration: " + e);
        }
    }

    return imageToShow;
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.util.ResultUtil.java

License:Open Source License

@NonNull
public static Mat concatenate(@NonNull Mat m1, @NonNull Mat m2) {
    int width = Math.max(m1.cols(), m2.cols());
    int height = m1.rows() + m2.rows();

    Mat result = new Mat(height, width, CvType.CV_8UC3,
            new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE));

    // rect works with x, y, width, height
    Rect roi1 = new Rect(0, 0, m1.cols(), m1.rows());
    Mat roiMat1 = result.submat(roi1);//from  w ww. ja  va2 s. co m
    m1.copyTo(roiMat1);

    Rect roi2 = new Rect(0, m1.rows(), m2.cols(), m2.rows());
    Mat roiMat2 = result.submat(roi2);
    m2.copyTo(roiMat2);

    return result;
}