Example usage for org.opencv.imgproc Imgproc circle

List of usage examples for org.opencv.imgproc Imgproc circle

Introduction

In this page you can find the example usage for org.opencv.imgproc Imgproc circle.

Prototype

public static void circle(Mat img, Point center, int radius, Scalar color) 

Source Link

Usage

From source file:com.astrocytes.core.operationsengine.OperationsImpl.java

License:Open Source License

@Deprecated
private Mat drawAstrocyteCenters() {
    if (astrocytesCenters == null) {
        return sourceImage;
    }//  w  w w. ja  v  a2 s.  co  m

    Mat result = sourceImage.clone();
    Scalar color = new Scalar(108, 240, 3);

    for (Point center : astrocytesCenters) {
        Imgproc.circle(result, center, 3, color);
    }

    return result;
}

From source file:com.trandi.opentld.TLDView.java

License:Apache License

private static void drawPoints(Mat image, final Point[] points, final Size scale, final Scalar colour) {
    if (points != null) {
        for (Point point : points) {
            Imgproc.circle(image, scaleUp(point, scale), 2, colour);
        }/*from   w w w.j  a  v  a 2 s. co  m*/
    }
}

From source file:facerecognition.sample1.java

private static void draw_initial_points() {
    //        PrintWriter pw = null;
    //        try {
    faceDetectors = new CascadeClassifier[] { new CascadeClassifier("haarcascade_frontalface_alt_tree.xml"),
            new CascadeClassifier("haarcascade_frontalface_alt2.xml"),
            new CascadeClassifier("haarcascade_profileface.xml") };
    File[] image_files = get_images();
    int index = 0;
    int contador = 0;
    //            File resumen = new File(urlHelen + "\\summary.sum");
    //            pw = new PrintWriter(resumen);

    double[][] mask = leer_mask();

    for (File image_file : image_files) {
        System.out.println("Analizando imagen " + (++index) + " de " + image_files.length);
        //            BufferedImage img = convert_to_BufferedImage(image_file);
        //                File puntos_file = get_puntos_file(image_file);
        //                double[][] puntos = LWF.leerpuntos(puntos_file);

        Mat image = Imgcodecs.imread(image_file.getAbsolutePath());
        Mat img2 = image.clone();//from   w ww .ja v a 2s.c  o  m

        for (CascadeClassifier faceDetector : faceDetectors) {

            // Detect faces in the image.
            // MatOfRect is a special container class for Rect.
            MatOfRect faceDetections = new MatOfRect();
            faceDetector.detectMultiScale(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()) {
                Rect piv = rect.clone();
                //  falta expandir
                int h = piv.height, w = piv.width;
                piv.x -= w * percent / 2;
                piv.y -= h * percent / 2;
                piv.height *= (1 + percent);
                piv.width *= (1 + percent);

                //            Mat croped = new Mat(image, rect);
                //             Imgcodecs.imwrite("face"+(++i)+".png", croped);
                Imgproc.rectangle(img2, new Point(piv.x, piv.y),
                        new Point(piv.x + piv.width, piv.y + piv.height), new Scalar(0, 255, 0));

                for (double[] punto : mask) {
                    Imgproc.circle(img2, new Point(piv.x + piv.width * punto[0], piv.y + piv.height * punto[1]),
                            5, new Scalar(0, 255, 0));
                }
            }

        }
        //            pw.close();
        Imgcodecs.imwrite(urlHelen + "\\face" + (Math.random()) + ".png", img2);

    }

}

From source file:org.usfirst.frc.team2084.CMonster2016.vision.Target.java

License:Open Source License

/**
 * Draw information about the target on an image.
 * /*from  www .  j a  v a2s  .c om*/
 * @param image the image to draw on
 * @param text whether to include position outputs in the corners of the
 *        image
 * @param imageHeading the heading of the robot when the image was taken
 */
public void draw(Mat image, boolean text, double imageHeading) {
    Scalar drawColor = isValid() ? VALID_TARGET_COLOR : INVALID_TARGET_COLOR;
    if (text) {
        drawColor = TARGET_COLOR;
    }

    Imgproc.line(image, topLeft, topRight, drawColor, DRAW_THICKNESS);
    Imgproc.line(image, topRight, bottomRight, drawColor, DRAW_THICKNESS);
    Imgproc.line(image, bottomRight, bottomLeft, drawColor, DRAW_THICKNESS);
    Imgproc.line(image, bottomLeft, topLeft, drawColor, DRAW_THICKNESS);

    Imgproc.circle(image, center, 5, drawColor);

    if (isValid()) {
        Utils.drawText(image, "score: " + SCORE_FORMAT.format(score), center.x - 50, center.y + 20, 1,
                Color.RED);
    } else {
        Utils.drawText(image, "failed: " + failedValidator, center.x - 50, center.y + 20, 1, Color.RED);
    }

    if (text) {
        Utils.drawText(image, " rotation: " + NUMBER_FORMAT.format(Math.toDegrees(xGoalAngle)) + " deg", 0,
                IMAGE_SIZE.height - 85);
        Utils.drawText(image, "distance: " + NUMBER_FORMAT.format(distance) + " ft", 0, IMAGE_SIZE.height - 65);
        Utils.drawText(image, "        x: " + NUMBER_FORMAT.format(position.x) + " ft", 0,
                IMAGE_SIZE.height - 45);
        Utils.drawText(image, "        y: " + NUMBER_FORMAT.format(position.y) + " ft", 0,
                IMAGE_SIZE.height - 25);
        Utils.drawText(image, "        z: " + NUMBER_FORMAT.format(position.z) + " ft", 0,
                IMAGE_SIZE.height - 5);

        double textX = IMAGE_SIZE.width - 250;

        double angleX = Math.toDegrees(rotation.get(0, 0)[0]);
        double angleY = Math.toDegrees(rotation.get(1, 0)[0]);
        double angleZ = Math.toDegrees(rotation.get(2, 0)[0]);

        Utils.drawText(image, "heading: " + NUMBER_FORMAT.format(Math.toDegrees(imageHeading)) + " deg", textX,
                IMAGE_SIZE.height - 65);
        Utils.drawText(image, "x angle: " + NUMBER_FORMAT.format(angleX) + " deg", textX,
                IMAGE_SIZE.height - 45);
        Utils.drawText(image, "y angle: " + NUMBER_FORMAT.format(angleY) + " deg", textX,
                IMAGE_SIZE.height - 25);
        Utils.drawText(image, "z angle: " + NUMBER_FORMAT.format(angleZ) + " deg", textX,
                IMAGE_SIZE.height - 5);
    }

}

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();//  w  ww  . jav a2  s .com
    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:servershootingstar.BallDetector.java

public static String getAngleFromRobot(int input) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    System.out.println("before");
    int point;/*w  ww  . j  av a 2  s  . c om*/
    try {
        Mat frame = new Mat();
        System.out.println("AAAAAA");
        Mat originalFrame = new Mat();
        System.out.println("BBBBBB");
        VideoCapture videoCapture = new VideoCapture(0);
        System.out.println("CCCCCCCC");
        videoCapture.read(originalFrame);
        //                System.out.println("original" + originalFrame.dump());
        //                initSwing(originalFrame);
        int workaround = 20;
        while (workaround > 0) {
            System.out.println("workaround " + workaround);
            videoCapture.read(originalFrame);
            //                    System.out.println(originalFrame.dump() + originalFrame.dump().length());
            workaround--;
        }
        //                Imgcodecs.imwrite("C:\\Users\\Goran\\Desktop\\Goran.jpg", originalFrame);
        Mat cropped = originalFrame.submat(originalFrame.rows() / 4, originalFrame.rows() / 4 * 3, 0,
                originalFrame.cols());
        initSwing(cropped);
        Imgproc.cvtColor(cropped, frame, Imgproc.COLOR_BGR2HSV);

        // insert lower and upper bounds for colors
        Scalar greenLowerB = new Scalar(20, 55, 55);
        Scalar greenUpperB = new Scalar(40, 255, 255);

        Scalar redLowerB = new Scalar(160, 100, 35);
        Scalar red1LowerB = new Scalar(0, 100, 35);

        Scalar redUpperB = new Scalar(180, 255, 255);
        Scalar red1UpperB = new Scalar(20, 255, 255);

        Scalar blueLowerB = new Scalar(100, 100, 35);
        Scalar blueUpperB = new Scalar(120, 255, 155);

        Mat mask = new Mat();

        if (input == 1) {
            Mat otherMask = new Mat();
            Core.inRange(frame, redLowerB, redUpperB, mask);
            Core.inRange(frame, red1LowerB, red1UpperB, otherMask);
            Core.bitwise_or(mask, otherMask, mask);
        } else if (input == 2) {
            Core.inRange(frame, greenLowerB, greenUpperB, mask);
        } else {
            Core.inRange(frame, blueLowerB, blueUpperB, mask);
        }
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));

        int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, minY = Integer.MAX_VALUE,
                maxY = Integer.MIN_VALUE;
        for (int i = 0; i < mask.rows(); ++i) {
            for (int j = 0; j < mask.cols(); ++j) {
                double value = mask.get(i, j)[0];
                //System.out.println(value);
                if (value > 1) {
                    minX = Math.min(minX, i);
                    maxX = Math.max(maxX, i);
                    minY = Math.min(minY, j);
                    maxY = Math.max(maxY, j);
                }
            }
        }

        Imgproc.circle(mask, new Point((maxY + minY) / 2, (minX + maxX) / 2), 3, new Scalar(0, 0, 0));
        initSwing(mask);

        point = (minY + maxY) / 2;

        point = point - 320;

        cos = point / 320.0;
        System.out.println("OK");
    } catch (Exception ex) {
        point = (new Random()).nextInt(640);
        cos = -1;
        System.out.println("error imase, davam random brojka: " + point);
        ex.printStackTrace();

    }

    //            System.out.println();
    //            System.out.println("tockata u granica od [-320, 320]");
    //            System.out.println(point);
    //            System.out.println("cosinus vrednost");
    //            System.out.println(cos);
    //            System.out.println();
    System.out.println("cos = " + cos);
    if (cos == -1) {
        return "-1";
    }
    int res = (int) (2 * Math.toDegrees(Math.acos(cos)) / 3);
    System.out.println("Res: " + res);
    return String.valueOf(res);
}

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

License:Apache License

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    mRgba = inputFrame.rgba();//from   w ww. j a v  a  2  s .c o m
    mGray = inputFrame.gray();

    //        return mRgba;
    //        iThreshold = 10000;

    //Imgproc.blur(mRgba, mRgba, new Size(5,5));
    Imgproc.GaussianBlur(mRgba, mRgba, new org.opencv.core.Size(3, 3), 1, 1);
    //Imgproc.medianBlur(mRgba, mRgba, 3);

    if (!mIsColorSelected)
        return mRgba;

    List<MatOfPoint> contours = mDetector.getContours();
    mDetector.process(mRgba);

    Log.d(TAG, "Contours count: " + contours.size());

    if (contours.size() <= 0) {
        return mRgba;
    }

    RotatedRect rect = Imgproc.minAreaRect(new MatOfPoint2f(contours.get(0).toArray()));

    double boundWidth = rect.size.width;
    double boundHeight = rect.size.height;
    int boundPos = 0;

    for (int i = 1; i < contours.size(); i++) {
        rect = Imgproc.minAreaRect(new MatOfPoint2f(contours.get(i).toArray()));
        if (rect.size.width * rect.size.height > boundWidth * boundHeight) {
            boundWidth = rect.size.width;
            boundHeight = rect.size.height;
            boundPos = i;
        }
    }

    Rect boundRect = Imgproc.boundingRect(new MatOfPoint(contours.get(boundPos).toArray()));
    Imgproc.rectangle(mRgba, boundRect.tl(), boundRect.br(), CONTOUR_COLOR_WHITE, 2, 8, 0);

    Log.d(TAG, " Row start [" + (int) boundRect.tl().y + "] row end [" + (int) boundRect.br().y
            + "] Col start [" + (int) boundRect.tl().x + "] Col end [" + (int) boundRect.br().x + "]");

    int rectHeightThresh = 0;
    double a = boundRect.br().y - boundRect.tl().y;
    a = a * 0.7;
    a = boundRect.tl().y + a;

    Log.d(TAG, " A [" + a + "] br y - tl y = [" + (boundRect.br().y - boundRect.tl().y) + "]");

    //Core.rectangle( mRgba, boundRect.tl(), boundRect.br(), CONTOUR_COLOR, 2, 8, 0 );
    Imgproc.rectangle(mRgba, boundRect.tl(), new Point(boundRect.br().x, a), CONTOUR_COLOR, 2, 8, 0);

    MatOfPoint2f pointMat = new MatOfPoint2f();
    Imgproc.approxPolyDP(new MatOfPoint2f(contours.get(boundPos).toArray()), pointMat, 3, true);
    contours.set(boundPos, new MatOfPoint(pointMat.toArray()));

    MatOfInt hull = new MatOfInt();
    MatOfInt4 convexDefect = new MatOfInt4();
    Imgproc.convexHull(new MatOfPoint(contours.get(boundPos).toArray()), hull);

    if (hull.toArray().length < 3)
        return mRgba;

    Imgproc.convexityDefects(new MatOfPoint(contours.get(boundPos).toArray()), hull, convexDefect);

    List<MatOfPoint> hullPoints = new LinkedList<MatOfPoint>();
    List<Point> listPo = new LinkedList<Point>();
    for (int j = 0; j < hull.toList().size(); j++) {
        listPo.add(contours.get(boundPos).toList().get(hull.toList().get(j)));
    }

    MatOfPoint e = new MatOfPoint();
    e.fromList(listPo);
    hullPoints.add(e);

    List<MatOfPoint> defectPoints = new LinkedList<MatOfPoint>();
    List<Point> listPoDefect = new LinkedList<Point>();
    for (int j = 0; j < convexDefect.toList().size(); j = j + 4) {
        Point farPoint = contours.get(boundPos).toList().get(convexDefect.toList().get(j + 2));
        Integer depth = convexDefect.toList().get(j + 3);
        if (depth > iThreshold && farPoint.y < a) {
            listPoDefect.add(contours.get(boundPos).toList().get(convexDefect.toList().get(j + 2)));
        }
        Log.d(TAG, "defects [" + j + "] " + convexDefect.toList().get(j + 3));
    }

    MatOfPoint e2 = new MatOfPoint();
    e2.fromList(listPo);
    defectPoints.add(e2);

    Log.d(TAG, "hull: " + hull.toList());
    Log.d(TAG, "defects: " + convexDefect.toList());

    Imgproc.drawContours(mRgba, hullPoints, -1, CONTOUR_COLOR, 3);

    int defectsTotal = (int) convexDefect.total();
    Log.d(TAG, "Defect total " + defectsTotal);

    this.numberOfFingers = listPoDefect.size();
    if (this.numberOfFingers > 5)
        this.numberOfFingers = 5;

    mHandler.post(mUpdateFingerCountResults);

    for (Point p : listPoDefect) {
        Imgproc.circle(mRgba, p, 6, new Scalar(255, 0, 255));
    }

    return mRgba;
}

From source file:video.PictureView.java

public static BufferedImage setCross(BufferedImage img) {
    Mat imgMat;//from w  ww . j a va  2s.  com
    imgMat = bufferedImageToMat(img);
    Imgproc.circle(imgMat, new Point(imgMat.width() / 2, imgMat.height() / 2), 4,
            new Scalar(255, 49, 255, 255));
    img = mat2Img(imgMat);
    return img;
}