Example usage for org.opencv.core Scalar Scalar

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

Introduction

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

Prototype

public Scalar(double v0, double v1, double v2) 

Source Link

Usage

From source file:objectdetection.ObjectDetector.java

public void findObjects() {

    preProcessImg();/*from ww w  . j a  v  a2 s . c  om*/
    Imgproc.findContours(imgCanny, contours, imgCanny, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

    for (MatOfPoint mop : contours) {
        MatOfPoint2f m2p;
        m2p = new MatOfPoint2f(mop.toArray());
        Double peri = Imgproc.arcLength(m2p, true);
        Imgproc.approxPolyDP(m2p, m2p, 0.02 * peri, true);
        //Imgproc.drawContours(img, contours, -1, new Scalar(0, 0, 255), 2);

        float area = img.width() * img.height();
        Rect rect = Imgproc.boundingRect(mop);
        objList.add(rect);
        //if (rect.height * rect.width > area*5/100) {
        Imgproc.rectangle(img, rect.tl(), rect.br(), new Scalar(255, 0, 0));
        //}
    }
    Collections.sort(objList, new Comparator<Rect>() {
        @Override
        public int compare(Rect r1, Rect r2) {
            return (int) (r2.area() - r1.area());
        }

    });

    List<Rect> arr = objList;

    Rect bigRect = arr.get(0);
    Rect bigRect2 = arr.get(1);

    while (!equals(bigRect, bigRect2)) {
        bigRect2 = bigRect;
        for (int i = 1; i < arr.size(); ++i) {
            if (doOverlap(bigRect, arr.get(i))) {
                bigRect = union(bigRect, arr.get(i));
                arr.remove(i);
                break;
            }
        }

    }

    Imgproc.rectangle(img, bigRect.tl(), bigRect.br(), new Scalar(255, 255, 0));
    mainRect = bigRect;
}

From source file:openbjk.detectar.java

public void run(Canvas c, Mat image) throws IOException {
    System.out.println("Rodando DetectFace");

    CascadeClassifier faceDetector = new CascadeClassifier(
            "C:\\Users\\Gertrude\\Documents\\NetBeansProjects\\TCC-FacialRecognize\\src\\resources\\lbpcascade_frontalface.xml");
    //Mat image = Highgui.imread("C:/Users/Gertrude/Desktop/TCC/img/lena.png");

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

    System.out.printf("Detected %s faces", faceDetections.toArray().length);

    for (Rect rect : faceDetections.toArray()) {
        Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
                new Scalar(0, 255, 0));
    }/*from w  w  w.  ja  va2 s.com*/

    String filename = "C:/Users/DS-007/Pictures/faceDetection.png";

    System.out.println(String.format("Writing %s", filename));
    Highgui.imwrite(filename, image);

    int type = BufferedImage.TYPE_BYTE_GRAY;

    MatOfByte bytemat = new MatOfByte();
    Highgui.imencode(".png", image, bytemat);
    byte[] bytes = bytemat.toArray();
    InputStream in = new ByteArrayInputStream(bytes);

    BufferedImage render = ImageIO.read(in);
    // c.setSize(render.getWidth(), render.getHeight());     
    Graphics g = c.getGraphics();

    g.drawImage(render, 1, 1, c.getHeight(), c.getWidth(), Color.LIGHT_GRAY, c);

}

From source file:opencltest.YetAnotherTestT.java

private static void paintLines(Mat targetImg, Mat lines) {
    for (int x = 0; x < lines.rows(); x++) {
        double[] vec = lines.get(x, 0);
        double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3];
        Point start = new Point(x1, y1);
        Point end = new Point(x2, y2);
        Imgproc.line(targetImg, start, end, new Scalar(255, 0, 0), 1);
    }/*  ww  w .j  a  v a 2 s .com*/
}

From source file:opencltest.YetAnotherTestT.java

private static Scalar randomColor() {
    return new Scalar(Math.random() * 255, Math.random() * 255, Math.random() * 255);
}

From source file:opencltest.YetAnotherTestT.java

private static void draw(List<Double> result, Mat test) {
    for (int i = 1; i < result.size() - 1; i++) {
        if (result.get(i) > result.get(i + 1) && result.get(i) > result.get(i - 1)) {
            Imgproc.line(test, new Point(i, 0), new Point(i, test.height()),
                    //                        new Scalar(result.get(i), 0, 0), 1
                    new Scalar(0, 0, 255), 1);
        }//from w ww .j  a  va  2s . co m

        //            Imgproc.line(test,
        //                        new Point(i, 0), new Point(i, test.height()),
        //                        new Scalar(result.get(i), 0, 0), 1
        ////                        new Scalar(0,0,255),1
        //                );
    }
}

From source file:opencv.CamCapture.java

private void searchForMovement(Mat thresholdImage, Mat frame) {
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(thresholdImage, contours, hierarchy, Imgproc.RETR_EXTERNAL,
            Imgproc.CHAIN_APPROX_SIMPLE);

    Rect objectBoundingRectangle = new Rect(0, 0, 0, 0);
    for (int i = 0; i < contours.size(); i++) {
        objectBoundingRectangle = Imgproc.boundingRect(contours.get(i));
        if (objectBoundingRectangle.area() > 500)
            Imgproc.rectangle(frame, objectBoundingRectangle.tl(), objectBoundingRectangle.br(),
                    new Scalar(0, 255, 0));
    }//from www  .  j  a v a2s .  com
    ImageIcon i2 = new ImageIcon(Mat2bufferedImage(frame));
    jLabel5.setIcon(i2);

}

From source file:opencv.fark.FarkBulMainFrame.java

private void jTBWebCamOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTBWebCamOpenActionPerformed
    t = new Thread() {
        @Override//from w ww .j a  va 2 s .  c o m
        public void run() {
            MatToBufImg matToBufferedImageConverter = new MatToBufImg(); //Utility class to convert Mat to Java's BufferedImage

            videoCapture = new VideoCapture("D:\\colorTest.mp4");
            if (!videoCapture.isOpened()) {
                System.out.println("Kamera Ak Deil..!");
            } else
                System.out.println("Kamera Ald --> " + videoCapture.toString());

            web_cam = new Mat(480, 640, CvType.CV_8UC3);

            if (videoCapture.isOpened()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {

                }

                while (true) {
                    try {
                        videoCapture.read(web_cam);
                    } catch (Exception e) {
                        System.out.println("Web Cam Kapal !");
                    }

                    if (!web_cam.empty()) {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException ex) {

                        }
                        if (drag && reference_value == 0 && first_point != null && second_point != null) {
                            Core.rectangle(web_cam, first_point, second_point, new Scalar(0, 0, 255));
                        }
                        if (reference_value == 1) {
                            Core.rectangle(web_cam, staticFirstPoint, staticSecondPoint, new Scalar(255, 0, 0));
                        }

                        matToBufferedImageConverter.setMatrix(web_cam, ".jpg");
                        image = matToBufferedImageConverter.getBufferedImage();
                        g.drawImage(image, 0, 0, web_cam.cols(), web_cam.rows(), null);
                    } else {

                        System.out.println("Grnt yok!");
                        break;
                    }
                }
            }
        }
    };
    t.start();

}

From source file:opencv.fark.ResimSecMainFrame.java

private void jButtonKarsilastirV1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonKarsilastirV1ActionPerformed

    Mat resim1hsv = new Mat();
    Mat resim2hsv = new Mat();
    Imgproc.cvtColor(resim1, resim1hsv, Imgproc.COLOR_BGR2HSV);
    Imgproc.cvtColor(resim2, resim2hsv, Imgproc.COLOR_BGR2HSV);

    Mat image = resim1.clone();//  www  .ja  v  a 2s  . c  o  m

    double data2[] = new double[3];
    for (int i = 0; i < image.rows(); i++) {
        for (int j = 0; j < image.cols(); j++) {
            double[] data = resim1.get(i, j);
            double[] data1 = resim2.get(i, j);

            data2[0] = Math.abs(data[0] - data1[0]);
            data2[1] = Math.abs(data[1] - data1[1]);
            data2[2] = Math.abs(data[2] - data1[2]);
            image.put(i, j, data2);

        }

    }

    Core.inRange(image, new Scalar(1, 0, 0), new Scalar(255, 255, 255), image);
    //Imgproc.threshold(image, image, 0, 256, Imgproc.THRESH_BINARY);

    MatToBufImg buf = new MatToBufImg();
    buf.setMatrix(image, ".png");
    g.drawImage(buf.getBufferedImage(), 0, 0, null);

}

From source file:opencvdemos.BallGame.java

License:Apache License

private Mat findAndDrawObjects(Mat maskedImage, Mat frame) {
    // Init/*w  w  w  . j av  a  2  s.  c o m*/
    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();

    // Find contours
    Imgproc.findContours(maskedImage, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE);

    // If any contour exist...
    if (hierarchy.size().height > 0 && hierarchy.size().width > 0) {
        // for each contour, display it in blue
        for (int idx = 0; idx >= 0; idx = (int) hierarchy.get(0, idx)[0]) {
            Imgproc.drawContours(frame, contours, idx, new Scalar(250, 0, 0));
        }
    }

    return frame;
}

From source file:opencvdemos.BallGame.java

License:Apache License

private Image grabFrame() {
    // Init everything
    Image imageToShow = null;/* w  w w.j av a 2s. c o m*/
    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;
}