Example usage for org.opencv.core Point Point

List of usage examples for org.opencv.core Point Point

Introduction

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

Prototype

public Point(double x, double y) 

Source Link

Usage

From source file:javacv.JavaCV.java

/**
 * @param args the command line arguments
 *//*w  w w .  j a  v  a2 s .  c  om*/
public static void main(String[] args) {
    // TODO code application logic here

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
    System.out.println("mat = " + mat.dump());

    CascadeClassifier faceDetector = new CascadeClassifier("./data/lbpcascade_frontalface.xml");
    //CascadeClassifier faceDetector = new CascadeClassifier();

    JFrame frame = new JFrame("BasicPanel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    JavaCV panel = new JavaCV();
    frame.setContentPane(panel);
    frame.setVisible(true);
    Mat webcam_image = new Mat();
    BufferedImage temp;
    VideoCapture capture;
    capture = new VideoCapture(0);

    if (capture.isOpened()) {
        while (true) {
            capture.read(webcam_image);
            if (!webcam_image.empty()) {
                frame.setSize(webcam_image.width() + 40, webcam_image.height() + 60);

                MatOfRect faceDetections = new MatOfRect();
                faceDetector.detectMultiScale(webcam_image, faceDetections);

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

                // Draw a bounding box around each face.
                for (Rect rect : faceDetections.toArray()) {
                    Core.rectangle(webcam_image, new Point(rect.x, rect.y),
                            new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
                }

                temp = matToBufferedImage(webcam_image);
                panel.setimage(temp);
                panel.repaint();
            } else {
                System.out.println(" --(!) No captured frame -- Break!");
                break;
            }
        }
    }
    return;

}

From source file:javafx1.JavaFX1.java

private Mat doBackgroundRemoval(Mat frame) {
        // init//from   w  w w.  ja v  a 2 s .  co m
        Mat hsvImg = new Mat();
        List<Mat> hsvPlanes = new ArrayList<>();
        Mat thresholdImg = new Mat();

        int thresh_type = Imgproc.THRESH_BINARY_INV;
        //inverse
        thresh_type = Imgproc.THRESH_BINARY;

        // threshold the image with the average hue value
        hsvImg.create(frame.size(), CvType.CV_8U);
        Imgproc.cvtColor(frame, hsvImg, Imgproc.COLOR_BGR2HSV);
        Core.split(hsvImg, hsvPlanes);

        // get the average hue value of the image
        double threshValue = this.getHistAverage(hsvImg, hsvPlanes.get(0));

        Imgproc.threshold(hsvPlanes.get(0), thresholdImg, threshValue, 179.0, thresh_type);

        Imgproc.blur(thresholdImg, thresholdImg, new Size(5, 5));

        // dilate to fill gaps, erode to smooth edges
        Imgproc.dilate(thresholdImg, thresholdImg, new Mat(), new Point(-1, -1), 1);
        Imgproc.erode(thresholdImg, thresholdImg, new Mat(), new Point(-1, -1), 3);

        Imgproc.threshold(thresholdImg, thresholdImg, threshValue, 179.0, Imgproc.THRESH_BINARY);

        // create the new image
        Mat foreground = new Mat(frame.size(), CvType.CV_8UC3, new Scalar(255, 255, 255));
        frame.copyTo(foreground, thresholdImg);

        return foreground;
    }

From source file:karthik.Barcode.CandidateMatrixBarcode.java

License:Open Source License

CandidateMatrixBarcode(ImageInfo img_details, RotatedRect minRect, SearchParameters params) {
    super(img_details, minRect, params);

    int adj_factor = params.RECT_HEIGHT / params.PROB_MAT_TILE_SIZE;

    Point candidateCentre = new Point(minRect.center.x * adj_factor, minRect.center.y * adj_factor);
    Size candidateSize = new Size(minRect.size.width * adj_factor, minRect.size.height * adj_factor);
    RotatedRect candidateRect = new RotatedRect(candidateCentre, candidateSize, minRect.angle);
    this.candidateRegion = candidateRect;

}

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
     *//*from  w w w .  j av a  2 s. com*/

    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:karthiknr.TextID.ProcessAsyncActivity.java

License:Apache License

public Mat findWarpedMat(Mat imgSource) {

    //convert the image to black and white does (8 bit)
    Imgproc.Canny(imgSource, imgSource, 50, 50);

    //apply gaussian blur to smoothen lines of dots
    Imgproc.GaussianBlur(imgSource, imgSource, new org.opencv.core.Size(5, 5), 5);

    //find the contours
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Imgproc.findContours(imgSource, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

    double maxArea = -1;
    int maxAreaIdx = -1;
    Log.d("size", Integer.toString(contours.size()));
    MatOfPoint temp_contour = contours.get(0); //the largest is at the index 0 for starting point
    MatOfPoint2f approxCurve = new MatOfPoint2f();
    MatOfPoint largest_contour = contours.get(0);
    //largest_contour.ge
    List<MatOfPoint> largest_contours = new ArrayList<MatOfPoint>();
    //Imgproc.drawContours(imgSource,contours, -1, new Scalar(0, 255, 0), 1);

    for (int idx = 0; idx < contours.size(); idx++) {
        temp_contour = contours.get(idx);
        double contourarea = Imgproc.contourArea(temp_contour);
        //compare this contour to the previous largest contour found
        if (contourarea > maxArea) {
            //check if this contour is a square
            MatOfPoint2f new_mat = new MatOfPoint2f(temp_contour.toArray());
            int contourSize = (int) temp_contour.total();
            MatOfPoint2f approxCurve_temp = new MatOfPoint2f();
            Imgproc.approxPolyDP(new_mat, approxCurve_temp, contourSize * 0.05, true);
            if (approxCurve_temp.total() == 4) {
                maxArea = contourarea;/*  ww  w  .j av  a 2 s .c om*/
                maxAreaIdx = idx;
                approxCurve = approxCurve_temp;
                largest_contour = temp_contour;
            }
        }
    }

    Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BayerBG2RGB);
    //Mat sourceImage =Imgcodecs.imread(Environment.getExternalStorageDirectory().getAbsolutePath()+"/TextID/"+"/oocr.png");
    double[] temp_double;
    temp_double = approxCurve.get(0, 0);
    Point p1 = new Point(temp_double[0], temp_double[1]);
    //Core.circle(imgSource,p1,55,new Scalar(0,0,255));
    //Imgproc.warpAffine(sourceImage, dummy, rotImage,sourceImage.size());
    temp_double = approxCurve.get(1, 0);
    Point p2 = new Point(temp_double[0], temp_double[1]);
    // Core.circle(imgSource,p2,150,new Scalar(255,255,255));
    temp_double = approxCurve.get(2, 0);
    Point p3 = new Point(temp_double[0], temp_double[1]);
    //Core.circle(imgSource,p3,200,new Scalar(255,0,0));
    temp_double = approxCurve.get(3, 0);
    Point p4 = new Point(temp_double[0], temp_double[1]);
    // Core.circle(imgSource,p4,100,new Scalar(0,0,255));
    List<Point> source = new ArrayList<Point>();
    source.add(p1);
    source.add(p2);
    source.add(p3);
    source.add(p4);
    Mat startM = Converters.vector_Point2f_to_Mat(source);
    return startM;
}

From source file:karthiknr.TextID.ProcessAsyncActivity.java

License:Apache License

public Mat warpImage(Mat inputMat, Mat startM) {
    int resultWidth = 1000;
    int resultHeight = 1000;

    Mat outputMat = new Mat(resultWidth, resultHeight, CvType.CV_8UC4);

    Point ocvPOut1 = new Point(0, 0);
    Point ocvPOut2 = new Point(0, resultHeight);
    Point ocvPOut3 = new Point(resultWidth, resultHeight);
    Point ocvPOut4 = new Point(resultWidth, 0);
    List<Point> dest = new ArrayList<Point>();
    dest.add(ocvPOut1);//from ww w .jav  a2  s .co  m
    dest.add(ocvPOut2);
    dest.add(ocvPOut3);
    dest.add(ocvPOut4);
    Mat endM = Converters.vector_Point2f_to_Mat(dest);

    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(startM, endM);

    Imgproc.warpPerspective(inputMat, outputMat, perspectiveTransform, new Size(resultWidth, resultHeight),
            Imgproc.INTER_CUBIC);

    return outputMat;
}

From source file:logic.analyzer.AnalyzerIF.java

/**
 * Virtual/*from ww  w.j  a  v  a2 s.co m*/
 * Rotates frame according to detected eye irises: compares y-coordinates and computes
 * angles between eye centers, calculates rotation matrix and rotates target image.
 * @return -1 if detected irises are not appropriate or computed eye centers angle is wrong, 
 * 0 if rotation matrix is not detected, 1 if success
 */
public int rotateFrameAndTrackTemplate(double in_baseDist, int in_boundRect, Rect[] in_out_trackRectArr,
        Mat[] out_trackTemplateMatArr, Point[] in_pointLocationArr, Scalar in_color) {
    //check if tracked objects lost location
    double tmp = in_baseDist / (double) in_boundRect;

    if (tmp < Parameters.eyeRectAndBaseDiffMinThresh || tmp > Parameters.eyeRectAndBaseDiffMaxThresh) {

        LOG.warn("baseDst: condition FAIL");

        return -1;
    }

    if (!trackRectArr(container.grayFrame, container.origFrame, in_out_trackRectArr, out_trackTemplateMatArr,
            in_pointLocationArr, in_color))
        return -1;

    //save new centers to feature in container
    container.features.eyeBrowCenterPointArr = in_pointLocationArr;

    if (in_pointLocationArr.length == 2) {
        Drawer.drawRectanglePair(container.origFrame, in_out_trackRectArr[0], in_out_trackRectArr[1], in_color);
        Drawer.drawTrackedEyeCenters(container.origFrame, in_pointLocationArr[0], in_pointLocationArr[1]);
    }

    //rotate images: color for watching, gray for further processing 
    //(eye templates rotate by themselves)
    container.rotationMat = getRotationMat(container.origFrame, container.faceRect, in_pointLocationArr[0],
            in_pointLocationArr[1], prevAlpha);

    if (prevAlpha != null && prevAlpha.x < 0) {
        LOG.warn("PrevAlpha: RESET");
        prevAlpha = new Point(0.0, 0.0);
        return -1;
    }

    if (container.rotationMat == null) {
        LOG.warn("Rotation angle is out of +/- " + Parameters.maxIrisAngle);
        return 0;
    }

    //save rot angle to features in container
    container.features.faceRotAngle = prevAlpha.y;

    Imgproc.warpAffine(container.origFrame, container.origFrame, container.rotationMat,
            container.origFrame.size(), Imgproc.INTER_LINEAR, Imgproc.BORDER_CONSTANT, new Scalar(0));

    Imgproc.warpAffine(container.grayFrame, container.grayFrame, container.rotationMat,
            container.grayFrame.size(), Imgproc.INTER_LINEAR, Imgproc.BORDER_CONSTANT, new Scalar(0));

    //recompute eyebrow interrocular distance
    container.eyeBrowBaseDst = Math
            .abs(container.eyeBrowBoundRectArr[0].x + container.eyeBrowBoundRectArr[0].width / 2
                    - (container.eyeBrowBoundRectArr[1].x + container.eyeBrowBoundRectArr[1].width / 2));

    LOG.info("eyeBrowBaseDst = " + container.eyeBrowBaseDst);

    return 1;
}

From source file:logic.analyzer.AnalyzerIF.java

/**
* Obtain rotation matrix for further image rotation
* Angle controlling algorithm: compute angle between eyes
*                              check angle range: if it is bigger
*                                  or smaller than threshold, we return null
*                                  and freeze frame
*                              check anle changing speed: compute first 
*                                  deriviation on time. In other words, we
*                                  compute differences betwee angle that was 
*                                  computed before and now. If angle value
*                                  changes faster than threshold, we reset
*                                  angle and compute all face features from
*                                  the begininig. Otherwise, compute rotation
*                                  matrix.
* @param frame//from   ww  w. j  a v  a  2 s . c o  m
* @param faceRect
* @param prevalpha angle, computed previously. If it is null, do not compute,
* because we are dealing with a static image
* @param p1
* @param p2
* @return rotation matrix
*/
public Mat getRotationMat(Mat frame, Rect faceRect, Point p1, Point p2, Point prevAlpha) {
    //compute angle
    double deltaX = p1.x - p2.x;
    double deltaY = p1.y - p2.y;
    double alpha = Math.tan(deltaY / deltaX) * 180. / Math.PI * (-1);

    double absAlpha = Math.abs(alpha);

    if (absAlpha > Parameters.maxIrisAngle)
        return null;

    if (prevAlpha != null) {
        double alphaDiff = Math.abs(absAlpha - prevAlpha.x);

        LOG.info("AlphaDif = " + alphaDiff);

        if (alphaDiff > Parameters.maxPrevAngDiff) {
            prevAlpha.x = -1;
            return null;
        }
        prevAlpha.x = absAlpha;
    }

    //save roteted angle
    prevAlpha.y = alpha;

    Point centerPoint = new Point(faceRect.x + faceRect.width / 2, faceRect.y + faceRect.height / 2);

    return Imgproc.getRotationMatrix2D(centerPoint, -alpha, 1);
}

From source file:logic.analyzer.AnalyzerIF.java

/**
 * Tracks rectangle patterns on image.//www  . j  ava  2 s .c  om
 * Algorithm:   check computed distance between patterns for thresh
 *                  if not excceeds: 
 *                      for each rectangle
 *                          track template, find new Rect location
 *                              if not null 
 *                                  save point coordinates
 *                              end if
 *                      end for
 *                      draw rectangle pair and centers
 *                  end if
 * @param in_srcMat
 * @param in_baseDist
 * @param in_boundRect
 * @param in_out_trackRectArr
 * @param out_trackTemplateMatArr
 * @param in_pointLocationArr
 * @param in_color
 * @return false if error, true otherwise
 */
protected boolean trackRectArr(Mat in_srcGrayMat, Mat in_srcColorMat, Rect[] in_out_trackRectArr,
        Mat[] out_trackTemplateMatArr, Point[] in_pointLocationArr, Scalar in_color) {

    //save prev location for further shifting computation

    //find new rect location
    for (int i = 0; i < 2; i++) {
        in_out_trackRectArr[i] = Util.trackTemplate(in_srcGrayMat, in_out_trackRectArr[i],
                out_trackTemplateMatArr[i]);

        //check if eyes lost image
        if (in_out_trackRectArr[i] == null) {

            LOG.warn("Tracking pattern is out of image scope");

            return false;
        }

        //new center
        in_pointLocationArr[i] = new Point(in_out_trackRectArr[i].x + in_out_trackRectArr[i].width / 2,
                in_out_trackRectArr[i].y + in_out_trackRectArr[i].height / 2);

        LOG.info("New centers: " + in_pointLocationArr[i].x + " " + in_pointLocationArr[i].y);
    }
    return true;
}

From source file:logic.analyzer.VideoAnalyzer.java

public VideoAnalyzer(logic.helpclass.Parameters.CAMERA_TYPE camType, boolean isByKey, int nPort) {
    prevAlpha = new Point(0.0, 0.0);

    switch (camType) {
    case USB_MONO: {
        imLoader = new USBCamera(nPort, isByKey);
        this.isByKey = isByKey;
        break;/* ww w.  j av  a2s .c o m*/
    }
    case USB_STEREO: {
        break;
    }
    case KINECT: {
        break;
    }
    }
}