Example usage for org.opencv.core Rect area

List of usage examples for org.opencv.core Rect area

Introduction

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

Prototype

public double area() 

Source Link

Usage

From source file:by.zuyeu.deyestracker.core.detection.processor.BiggerFaceProcessor.java

@Override
public Rect process(Rect[] input) {
    if (input == null || input.length == 0) {
        return null;
    }//from  w w w  .j  av  a2  s .c  o m
    // default if length = 0
    int mainFaceIndex = 0;
    double maxArea = 0;
    for (int i = 0; (i < input.length) && (input.length > 1); i++) {
        final Rect rect = input[i];
        final double area = rect.area();
        if (area > maxArea) {
            maxArea = area;
            mainFaceIndex = i;
        }
    }
    return input[mainFaceIndex];
}

From source file:com.mitzuli.core.ocr.OcrPreprocessor.java

License:Open Source License

/**
 * Binarizes and cleans the input image for OCR, saving debugging images in the given directory.
 *
 * @param input the input image, which is recycled by this method, so the caller should make a defensive copy of it if necessary.
 * @param debugDir the directory to write the debugging images to, or null to disable debugging.
 * @return the preprocessed image./*from   w w  w.j a  v  a  2s  .  com*/
 */
static Image preprocess(final Image input, final File debugDir) {
    // TODO Temporary workaround to allow to manually enable debugging (the global final variable should be used)
    boolean DEBUG = debugDir != null;

    // Initialization
    final Mat mat = input.toGrayscaleMat();
    final Mat debugMat = DEBUG ? input.toRgbMat() : null;
    input.recycle();
    final Mat aux = new Mat(mat.size(), CvType.CV_8UC1);
    final Mat binary = new Mat(mat.size(), CvType.CV_8UC1);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "1_input.jpg"));

    // Binarize the input image in mat through adaptive Gaussian thresholding
    Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 51,
            13);
    // Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 31, 7);

    // Edge detection
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_3X3); // Open
    Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_3X3); // Close
    Core.addWeighted(mat, 0.5, aux, 0.5, 0, mat); // Average
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_GRADIENT, KERNEL_3X3); // Gradient
    Imgproc.threshold(mat, mat, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); // Edge map
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "2_edges.jpg"));

    // Extract word level connected-components from the dilated edge map
    Imgproc.dilate(mat, mat, KERNEL_3X3);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "3_dilated_edges.jpg"));
    final List<MatOfPoint> wordCCs = new ArrayList<MatOfPoint>();
    Imgproc.findContours(mat, wordCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Filter word level connected-components individually and calculate their average attributes
    final List<MatOfPoint> individuallyFilteredWordCCs = new ArrayList<MatOfPoint>();
    final List<MatOfPoint> removedWordCCs = new ArrayList<MatOfPoint>();
    double avgWidth = 0, avgHeight = 0, avgArea = 0;
    for (MatOfPoint cc : wordCCs) {
        final Rect boundingBox = Imgproc.boundingRect(cc);
        if (boundingBox.height >= 6 // bounding box height >= 6
                && boundingBox.area() >= 50 // bounding box area >= 50
                && (double) boundingBox.width / (double) boundingBox.height >= 0.25 // bounding box aspect ratio >= 1:4
                && boundingBox.width <= 0.75 * mat.width() // bounding box width <= 0.75 image width
                && boundingBox.height <= 0.75 * mat.height()) // bounding box height <= 0.75 image height
        {
            individuallyFilteredWordCCs.add(cc);
            avgWidth += boundingBox.width;
            avgHeight += boundingBox.height;
            avgArea += boundingBox.area();
        } else {
            if (DEBUG)
                removedWordCCs.add(cc);
        }
    }
    wordCCs.clear();
    avgWidth /= individuallyFilteredWordCCs.size();
    avgHeight /= individuallyFilteredWordCCs.size();
    avgArea /= individuallyFilteredWordCCs.size();
    if (DEBUG) {
        Imgproc.drawContours(debugMat, removedWordCCs, -1, BLUE, -1);
        removedWordCCs.clear();
    }

    // Filter word level connected-components in relation to their average attributes
    final List<MatOfPoint> filteredWordCCs = new ArrayList<MatOfPoint>();
    for (MatOfPoint cc : individuallyFilteredWordCCs) {
        final Rect boundingBox = Imgproc.boundingRect(cc);
        if (boundingBox.width >= 0.125 * avgWidth // bounding box width >= 0.125 average width
                && boundingBox.width <= 8 * avgWidth // bounding box width <= 8 average width
                && boundingBox.height >= 0.25 * avgHeight // bounding box height >= 0.25 average height
                && boundingBox.height <= 4 * avgHeight) // bounding box height <= 4 average height
        {
            filteredWordCCs.add(cc);
        } else {
            if (DEBUG)
                removedWordCCs.add(cc);
        }
    }
    individuallyFilteredWordCCs.clear();
    if (DEBUG) {
        Imgproc.drawContours(debugMat, filteredWordCCs, -1, GREEN, -1);
        Imgproc.drawContours(debugMat, removedWordCCs, -1, PURPLE, -1);
        removedWordCCs.clear();
    }

    // Extract paragraph level connected-components
    mat.setTo(BLACK);
    Imgproc.drawContours(mat, filteredWordCCs, -1, WHITE, -1);
    final List<MatOfPoint> paragraphCCs = new ArrayList<MatOfPoint>();
    Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_30X30);
    Imgproc.findContours(aux, paragraphCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Filter paragraph level connected-components according to the word level connected-components inside
    final List<MatOfPoint> textCCs = new ArrayList<MatOfPoint>();
    for (MatOfPoint paragraphCC : paragraphCCs) {
        final List<MatOfPoint> wordCCsInParagraphCC = new ArrayList<MatOfPoint>();
        aux.setTo(BLACK);
        Imgproc.drawContours(aux, Collections.singletonList(paragraphCC), -1, WHITE, -1);
        Core.bitwise_and(mat, aux, aux);
        Imgproc.findContours(aux, wordCCsInParagraphCC, new Mat(), Imgproc.RETR_EXTERNAL,
                Imgproc.CHAIN_APPROX_SIMPLE);
        final Rect boundingBox = Imgproc.boundingRect(paragraphCC);
        final double center = mat.size().width / 2;
        final double distToCenter = center > boundingBox.x + boundingBox.width
                ? center - boundingBox.x - boundingBox.width
                : center < boundingBox.x ? boundingBox.x - center : 0.0;
        if (DEBUG) {
            System.err.println("****************************************");
            System.err.println("\tArea:                " + boundingBox.area());
            System.err.println("\tDistance to center:  " + distToCenter);
            System.err.println("\tCCs inside:          " + wordCCsInParagraphCC.size());
        }
        if ((wordCCsInParagraphCC.size() >= 10 || wordCCsInParagraphCC.size() >= 0.3 * filteredWordCCs.size())
                && mat.size().width / distToCenter >= 4) {
            textCCs.addAll(wordCCsInParagraphCC);
            if (DEBUG) {
                System.err.println("\tText:                YES");
                Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_GREEN, 5);
            }
        } else {
            if (DEBUG) {
                System.err.println("\tText:                NO");
                Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_RED, 5);
            }
        }
    }
    filteredWordCCs.clear();
    paragraphCCs.clear();
    mat.setTo(WHITE);
    Imgproc.drawContours(mat, textCCs, -1, BLACK, -1);
    textCCs.clear();
    if (DEBUG)
        Image.fromMat(debugMat).write(new File(debugDir, "4_filtering.jpg"));

    // Obtain the final text mask from the filtered connected-components
    Imgproc.erode(mat, mat, KERNEL_15X15);
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_30X30);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "5_text_mask.jpg"));

    // Apply the text mask to the binarized image
    if (DEBUG)
        Image.fromMat(binary).write(new File(debugDir, "6_binary.jpg"));
    binary.setTo(WHITE, mat);
    if (DEBUG)
        Image.fromMat(binary).write(new File(debugDir, "7_binary_text.jpg"));

    // Dewarp the text using Leptonica
    Pix pixs = Image.fromMat(binary).toGrayscalePix();
    Pix pixsDewarp = Dewarp.dewarp(pixs, 0, Dewarp.DEFAULT_SAMPLING, 5, true);
    final Image result = Image.fromGrayscalePix(pixsDewarp);
    if (DEBUG)
        result.write(new File(debugDir, "8_dewarp.jpg"));

    // Clean up
    pixs.recycle();
    mat.release();
    aux.release();
    binary.release();
    if (debugMat != null)
        debugMat.release();

    return result;
}

From source file:com.mycompany.analyzer.RegionSizeAnalyzer.java

private double calcAreaRatio(Rect rect) {
    double imgArea = frameWidth * frameHeight;
    return (rect.area() / imgArea);
}

From source file:com.mycompany.analyzer.RuleOfThirdsAnalyzer.java

public double calcSumOfMass() {
    double imgArea = frameWidth * frameHeight;
    double weight = imgArea * 3 / 100;
    double sumOfMass = 0;
    for (Rect rect : objectList) {
        sumOfMass += rect.area();
    }/*www  .j a v  a2 s.  c  o m*/
    for (Rect rect : faceList) {
        sumOfMass += rect.area() + weight;
    }
    return sumOfMass;
}

From source file:com.mycompany.analyzer.RuleOfThirdsAnalyzer.java

private double calcEPoint() {
    double imgArea = frameWidth * frameHeight;
    double weight = imgArea * 3 / 100;
    if (objectList.size() + faceList.size() > 0) {
        double ePoint = calcSumOfMass();
        double sum = 0;
        for (Rect rect : objectList) {
            sum = sum + (rect.area() * Math.exp((-1 * Math.pow(minDistToPowerPoints(rect), 2)) / (2 * 0.17)));
        }/*from  w w w .j av a  2 s.co m*/
        for (Rect rect : faceList) {
            sum = sum + ((rect.area() + weight)
                    * Math.exp((-1 * Math.pow(minDistToPowerPoints(rect), 2)) / (2 * 0.17)));
        }
        return (1 / ePoint * sum);
    } else {
        return 0;
    }
}

From source file:com.mycompany.analyzer.VisualBalanceAnalyzer.java

public Point getAllRegionsCenter() {
    int x = 0;//w  ww.  j  ava 2 s .c  o m
    int y = 0;
    int sumX = 0;
    int sumY = 0;
    double imgArea = frameWidth * frameHeight;
    double weight = imgArea * 3 / 100;
    Point actualCenter;
    if (objectList.size() + faceList.size() > 0) {
        for (Rect rect : objectList) {
            actualCenter = getRectCenter(rect);
            x = (int) actualCenter.x;
            y = (int) actualCenter.y;
            sumX += (x * rect.area());
            sumY += (y * rect.area());
        }
        for (Rect rect : faceList) {
            actualCenter = getRectCenter(rect);
            x = (int) actualCenter.x;
            y = (int) actualCenter.y;
            sumX += (x * (rect.area() + weight));
            sumY += (y * (rect.area() + weight));
        }
        sumX = (int) (sumX / calcSumOfMass());
        sumY = (int) (sumY / calcSumOfMass());
    }
    return new Point(sumX, sumY);
}

From source file:com.mycompany.objectdetection.ObjectDetector.java

public void findObjects() {

    //        Imgproc.cvtColor(img, imgGrayscale, Imgproc.COLOR_RGBA2GRAY, 1); 
    //        Core.convertScaleAbs(img, imgGrayscale);
    //        Core.normalize(imgGrayscale, imgMeanShifted, 0.0, 1.0, NORM_MINMAX);
    preProcessImg();//from ww  w.j a  v  a  2 s. c  o  m

    toGrayScale(imgMeanShifted);
    detectEdges(imgGrayscale);
    Imgproc.findContours(imgCanny, contours, imgCanny, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
    objList = new ArrayList();

    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(imgOut, contours, -1, new Scalar(0, 0, 255), 2);

        float area = img.width() * img.height();
        Rect rect = Imgproc.boundingRect(mop);
        objList.add(rect);
        Imgproc.rectangle(imgOut, 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;

    while (arr.size() > 0) {
        //System.out.println("---->" + arr);
        Rect bigRect = arr.get(0);
        arr.remove(0);
        Rect bigRect2 = new Rect();

        while (!equals(bigRect, bigRect2)) {
            bigRect2 = bigRect;
            for (int i = 0; i < arr.size(); ++i) {
                // System.out.println("elotte"+arr.get(i));
                if (doOverlap(bigRect, arr.get(i))) {
                    //System.out.println("utana"+arr.get(i));
                    bigRect = union(bigRect, arr.get(i));
                    arr.remove(i);
                    break;
                }
            }

        }

        mainRect = bigRect;

        if (objList.size() > 5 && mainRect.area() >= img.width() * img.height() * 3 / 100) {
            Imgproc.rectangle(imgOut, bigRect.tl(), bigRect.br(), new Scalar(255, 255, 0));
            mainObjects.add(mainRect);
        } else if (objList.size() <= 5) {
            mainObjects.add(mainRect);
        }
    }

}

From source file:Comun.Imagen.java

public String dividirImagen(String nombreCarpeta) {
    StringBuilder SB = new StringBuilder();

    //Crea la carpeta donde alojar las imagenes
    this.nombreCarpeta = nombreCarpeta;
    File carpeta = new File(nombreCarpeta);
    if (carpeta.mkdir()) {
        Mat imgAux = new Mat();
        //Convertir la imagen en escala de grises a binario
        threshold(imagen, imgAux, 128, 255, THRESH_BINARY | THRESH_OTSU);

        //Dibuja los bordes
        double umbral = 100;
        Canny(imgAux, imgAux, umbral, umbral * 2);

        //Lista que guarda los puntos de los contornos
        LinkedList<MatOfPoint> contornos = new LinkedList<>();
        Mat jerarquia = new Mat();

        //Detecto los contornos
        findContours(imgAux, contornos, jerarquia, RETR_TREE, CHAIN_APPROX_SIMPLE);

        Rect contorno;

        if (!contornos.isEmpty()) {
            SB.append("Se han encontrado ").append(contornos.size()).append(" contornos -");

            double areaProm = 0;
            for (int i = 0; i < contornos.size(); i++) {
                contorno = boundingRect(contornos.get(i));
                areaProm += contorno.area();
            }//from   w w  w  . jav  a  2 s .c  o m

            //Asigna que para ser un contorno valido debe ser mayor al 10% del segundo mayor
            areaProm = (areaProm / contornos.size()) * 0.25;
            ArrayList<Rect> contornosFiltrados = new ArrayList<>();

            //Guarda las letras detectadas
            for (int i = 0; i < contornos.size(); i++) {

                contorno = boundingRect(contornos.get(i));
                //Verifica que supere el limite
                if (contorno.area() > areaProm) {
                    contornosFiltrados.add(contorno);
                }
            }
            //Ordeno los contornos de mayor a menor
            Mergesort merge = new Mergesort(contornosFiltrados);
            merge.ordenar();
            contornosFiltrados = merge.getV();

            //Filtro solo los contornos que no se superponen con otro
            ArrayList<Rect> contornosFinal = new ArrayList<>();
            boolean bandera = false;
            for (Rect recta : contornosFiltrados) {
                for (Rect c : contornosFinal) {
                    if (c.contains(recta.tl()) || c.contains(recta.br())) {
                        bandera = true;
                        break;
                    }
                }
                if (!bandera) {
                    //Agrego el contorno a la lista final de contornos
                    contornosFinal.add(recta);
                    //Guardo la imagen en la carpeta
                    this.guardarImagen(new Mat(imagen, recta), contornosFinal.size());

                    //La marca en la imagen principal
                    rectangle(imagen, new Point(recta.x, recta.y),
                            new Point(recta.x + recta.width, recta.y + recta.height), new Scalar(0, 255, 0));
                }
                bandera = false;
            }

            SB.append("Contornos Validos: ").append(contornosFinal.size());

        } else {
            SB.append("No se ha encontrado ningun contorno");
        }
    } else {
        SB.append("No se pudo crear la carpeta");
    }
    this.guardarImagen(imagen, 0);
    return SB.toString();
}

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/*  w w w  .j a v a2 s  .c  o 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 www  .j  a v a 2  s  . c  om*/
    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();
    }

}