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:io.github.jakejmattson.facialrecognition.ImageFrame.java

License:Open Source License

/**
 * Return the selected text color as an OpenCV Scalar.
 *
 * @return Scalar
 */
Scalar getTextColor() {
    return new Scalar(color.getBlue(), color.getGreen(), color.getRed());
}

From source file:it.baywaylabs.jumpersumo.FrameDisplayCV.java

License:Open Source License

/**
 * This method find a qr-code in the view cam and execute some control.
 *
 * @throws ChecksumException/*from   www . j  av a  2  s.  co m*/
 * @throws FormatException
 */
private void zxing() throws ChecksumException, FormatException {

    int[] intArray = new int[bitmapOriginal.getWidth() * bitmapOriginal.getHeight()];
    //copy pixel data from the Bitmap into the 'intArray' array
    bitmapOriginal.getPixels(intArray, 0, bitmapOriginal.getWidth(), 0, 0, bitmapOriginal.getWidth(),
            bitmapOriginal.getHeight());

    LuminanceSource source = new RGBLuminanceSource(bitmapOriginal.getWidth(), bitmapOriginal.getHeight(),
            intArray);

    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    Reader reader = new QRCodeMultiReader();

    String sResult = "";
    Double AREA_RIFERIMENTO = 11500.0;

    try {

        Result result = reader.decode(bitmap);
        sResult = result.getText();
        if (result.getBarcodeFormat().compareTo(BarcodeFormat.QR_CODE) == 0) {

            Log.d(TAG, "SI! E' Un QRCode");
            if ("jump".equalsIgnoreCase(sResult) && this.deviceController != null && this.flag_execute_qrcode) {
                deviceController.getFeatureJumpingSumo().sendAnimationsJump(
                        ARCOMMANDS_JUMPINGSUMO_ANIMATIONS_JUMP_TYPE_ENUM.ARCOMMANDS_JUMPINGSUMO_ANIMATIONS_JUMP_TYPE_HIGH);
            }
        }

        ResultPoint[] points = result.getResultPoints();
        Log.d(TAG, "PUNTI: " + points.toString());

        Point a = new Point(points[0].getX(), points[0].getY());
        Point b = new Point(points[2].getX(), points[2].getY());
        Rect rect = new Rect(a, b);

        Log.d(TAG, "Area del rettangolo: " + rect.area());
        if (rect.area() < AREA_RIFERIMENTO)
            Log.w(TAG, "Mi devo avvicinare!");
        else
            Log.w(TAG, "Mi devo allontanare!");

        Imgproc.rectangle(this.imgMAT, new Point(points[0].getX(), points[0].getY()),
                new Point(points[2].getX(), points[2].getY()), new Scalar(0, 255, 0), 3);
        Log.d(TAG, sResult);
        Point center = new Point(0, 0);

        Imgproc.circle(this.imgMAT, center, 10, new Scalar(0, 0, 255), 2);
    } catch (Resources.NotFoundException e) {
        Log.e(TAG, "Code Not Found");
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    }

}

From source file:it.baywaylabs.jumpersumo.MainActivity.java

License:Open Source License

public void zxing(Mat mRgba) throws ChecksumException, FormatException {

    Bitmap bMap = Bitmap.createBitmap(mRgba.width(), mRgba.height(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(mRgba, bMap);/*from w  w w .j  a  v a 2 s .  co  m*/
    int[] intArray = new int[bMap.getWidth() * bMap.getHeight()];
    //copy pixel data from the Bitmap into the 'intArray' array
    bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());

    LuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), bMap.getHeight(), intArray);

    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    Reader reader = new QRCodeMultiReader();

    String sResult = "";
    Double AREA_RIFERIMENTO = 11500.0;

    try {

        Result result = reader.decode(bitmap);
        sResult = result.getText();
        if (result.getBarcodeFormat().compareTo(BarcodeFormat.QR_CODE) == 0)
            Log.d(TAG, "SI! E' Un QRCode");
        ResultPoint[] points = result.getResultPoints();
        Log.d(TAG, "PUNTI: " + points.toString());
        //for (ResultPoint point : result.getResultPoints()) {
        Point a = new Point(points[0].getX(), points[0].getY());
        Point b = new Point(points[2].getX(), points[2].getY());
        Rect rect = new Rect(a, b);
        Log.d(TAG, "Area del rettangolo: " + rect.area());
        if (rect.area() < AREA_RIFERIMENTO)
            Log.w(TAG, "Mi devo avvicinare!");
        else
            Log.w(TAG, "Mi devo allontanare!");
        Imgproc.rectangle(this.mRgba, new Point(points[0].getX(), points[0].getY()),
                new Point(points[2].getX(), points[2].getY()), new Scalar(0, 255, 0), 3);
        Log.d(TAG, sResult);
        Point center = new Point(0, 0);

        Imgproc.circle(this.mRgba, center, 10, new Scalar(0, 0, 255), 2);
        //if (!"".equals(sResult))
        //Toast.makeText(MainActivity.this, "QRCode Scanned: " + sResult, Toast.LENGTH_LONG).show();
    } catch (Resources.NotFoundException e) {
        Log.e(TAG, "Code Not Found");
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    }

}

From source file:jarvis.module.colourtracking.ColourTrackingModule.java

@Override
public void run() {
    while (running) {
        // Get webcam image
        if (cap != null)
            cap.read(imageOriginal);//from   ww w . j a v a 2s  .  c o m
        // Convert from BGR to HSV
        Imgproc.cvtColor(imageOriginal, imageHSV, Imgproc.COLOR_RGB2HSV);
        // Threshold
        Core.inRange(imageHSV, new Scalar(lowH.getValue(), lowS.getValue(), lowV.getValue()),
                new Scalar(highH.getValue(), highS.getValue(), highV.getValue()), imageThresholded);
        // Remove small objects in the foreground 'morphological opening'
        Mat structure = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
        Imgproc.erode(imageThresholded, imageThresholded, structure);
        Imgproc.dilate(imageThresholded, imageThresholded, structure);
        // Remove holes in the foreground 'morphological closing'
        Imgproc.dilate(imageThresholded, imageThresholded, structure);
        Imgproc.erode(imageThresholded, imageThresholded, structure);

        // Get the spatial moment
        //            Moments moments = Imgproc.moments(imageThresholded);
        //            int area = (int)moments.get_m00();

        Imgproc.cvtColor(imageThresholded, imageThresholded, Imgproc.COLOR_GRAY2RGB);
        if (cap != null)
            frame.getContentPane().getGraphics().drawImage(mat2image.getImage(imageThresholded), 0, 50, null);
        if (cap != null)
            frame.repaint();
    }
}

From source file:javaapplication1.Ocv.java

/**
 * Find faces in an image./*from  w w w .  j av a  2 s.c om*/
 *
 * @param filter Path to the xml face finding filter to use
 * @param input Path to the input image file
 * @param output Path to the output image file
 */
public void findFaces(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(f.getAbsolutePath());
    */
    CascadeClassifier faceDetector = new CascadeClassifier(this.filter);
    System.out.println("This.filter " + this.filter);

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

    /*
    final Mat image = Highgui.imread(getClass().getResource(
        "./AverageMaleFace.jpg").getPath());
    */

    Mat image = Highgui.imread(this.input);
    System.out.println("This.input " + this.input);

    // run a face detector on the image
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);
    // inform about faces detected, and then outline each of them
    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
    // Draw rectangles on the image wherever we found faces
    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));
    }

    // save the image
    String filename = this.output;
    System.out.println(String.format("Writing %s", filename));
    Highgui.imwrite(filename, image);

}

From source file:javacv.JavaCV.java

/**
 * @param args the command line arguments
 *//* www  .j a  va  2 s.  co m*/
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/* w w  w  .  ja v a2 s  .  c o 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.MatrixBarcode.java

License:Open Source License

public List<CandidateResult> locateBarcode() throws IOException {

    calcGradientDirectionAndMagnitude();
    for (int tileSize = searchParams.tileSize; tileSize < rows && tileSize < cols; tileSize *= 4) {
        img_details.probabilities = calcProbabilityMatrix(tileSize); // find areas with low variance in gradient direction

        //    connectComponents();
        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        // findContours modifies source image so probabilities pass it a clone of img_details.probabilities
        // img_details.probabilities will be used again shortly to expand the barcode region
        Imgproc.findContours(img_details.probabilities.clone(), contours, hierarchy, Imgproc.RETR_LIST,
                Imgproc.CHAIN_APPROX_SIMPLE);

        double bounding_rect_area = 0;
        RotatedRect minRect;//www  .  j  a v a2  s .  c o m
        CandidateResult ROI;
        int area_multiplier = (searchParams.RECT_HEIGHT * searchParams.RECT_WIDTH)
                / (searchParams.PROB_MAT_TILE_SIZE * searchParams.PROB_MAT_TILE_SIZE);
        // pictures were downsampled during probability calc so we multiply it by the tile size to get area in the original picture

        for (int i = 0; i < contours.size(); i++) {
            double area = Imgproc.contourArea(contours.get(i));

            if (area * area_multiplier < searchParams.THRESHOLD_MIN_AREA) // ignore contour if it is of too small a region
                continue;

            minRect = Imgproc.minAreaRect(new MatOfPoint2f(contours.get(i).toArray()));
            bounding_rect_area = minRect.size.width * minRect.size.height;
            if (DEBUG_IMAGES) {
                System.out.println("Area is " + area * area_multiplier + " MIN_AREA is "
                        + searchParams.THRESHOLD_MIN_AREA);
                System.out.println("area ratio is " + ((area / bounding_rect_area)));
            }

            if ((area / bounding_rect_area) > searchParams.THRESHOLD_AREA_RATIO) // check if contour is of a rectangular object
            {
                CandidateMatrixBarcode cb = new CandidateMatrixBarcode(img_details, minRect, searchParams);
                if (DEBUG_IMAGES)
                    cb.debug_drawCandidateRegion(new Scalar(0, 255, 128), img_details.src_scaled);
                // get candidate regions to be a barcode

                // rotates candidate region to straighten it based on the angle of the enclosing RotatedRect                
                ROI = cb.NormalizeCandidateRegion(Barcode.USE_ROTATED_RECT_ANGLE);
                if (postProcessResizeBarcode)
                    ROI.ROI = scale_candidateBarcode(ROI.ROI);

                candidateBarcodes.add(ROI);

                if (DEBUG_IMAGES)
                    cb.debug_drawCandidateRegion(new Scalar(0, 0, 255), img_details.src_scaled);
            }
        }
    }
    return candidateBarcodes;
}

From source file:LetsStart.GUI.java

private void addNoise() {
    image = originalImage.clone();//  ww  w  . j  a  va 2  s. co m
    Mat grayRnd = new Mat(image.rows(), image.cols(), image.type());
    double noise = 128;
    grayRnd.setTo(new Scalar(noise / 2, noise / 2, noise / 2));
    Core.subtract(image, grayRnd, image);
    Core.randu(grayRnd, 0, noise);
    Core.add(image, grayRnd, image);
    processOperation();
    updateView();
}

From source file:logic.analyzer.PhotoAnalyzer.java

/**
 * See AnalyzeIF::analyze() for more details
 *//*from   www  .j a v a2 s  .  c  o  m*/
@Override
public void analyze() {
    //open port
    if (!this.imLoader.open())
        return;

    //localize ROI and extract FP

    //take frame
    container.origFrame = this.imLoader.loadImage();
    if (container.origFrame == null)
        return;

    //Preprocess frame
    container.grayFrame = Util.preprocessFrame(container.origFrame);

    //run INITIAL LOCALIZATION 

    if (!detectFaceFeatures())
        return;

    //rotate frame
    int rotRes = rotateFrameAndTrackTemplate(container.eyeBrowBaseDst, container.eyePairRect.width,
            container.eyeBrowBoundRectArr, container.eyeBrowTrackingTemplateArr,
            container.eyeBrowCentersPointsArr, new Scalar(0, 0, 255));

    if (rotRes != 1)
        return;

    Core.rectangle(container.origFrame, container.noseRect.tl(), container.noseRect.br(), new Scalar(0, 0, 255),
            2);
    Core.rectangle(container.origFrame, container.mouthRect.tl(), container.mouthRect.br(),
            new Scalar(0, 0, 255), 2);

    //detect mouth FPE and show results
    mouthFPE.detect(container);

    imShowOrig.showImage(container.mouthMat);
    imShowProc.showImage(container.origFrame);
}