Example usage for org.opencv.core Rect Rect

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

Introduction

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

Prototype

public Rect(Point p, Size s) 

Source Link

Usage

From source file:OctoEye.java

License:Open Source License

private void detectPupil() {
    // min and max pupil radius
    int r_min = 2;
    int r_max = 45;

    // min and max pupil diameter
    int d_min = 2 * r_min;
    int d_max = 2 * r_max;

    // min and max pupil area
    double area;/*from w w  w .j a v a2s.co m*/
    double a_min = Math.PI * r_min * r_min;
    double a_max = Math.PI * r_max * r_max;

    // histogram stuff
    List<Mat> images;
    MatOfInt channels;
    Mat mask;
    Mat hist;
    MatOfInt mHistSize;
    MatOfFloat mRanges;

    // contour and circle stuff
    Rect rect = null;
    Rect rectMin;
    Rect rectMax;
    List<MatOfPoint> contours;
    MatOfPoint3 circles;

    // pupil center
    Point p;

    // ellipse test points
    Point v;
    Point r;
    Point s;

    // rect points
    Point tl;
    Point br;

    // pupil edge detection
    Vector<Point> pointsTest;
    Vector<Point> pointsEllipse;
    Vector<Point> pointsRemoved;

    // temporary variables
    double distance;
    double rad;
    double length;
    int x;
    int y;
    int tmp;
    byte buff[];

    // -------------------------------------------------------------------------------------------------------------
    // step 1
    // blur the image to reduce noise

    Imgproc.medianBlur(src, tmp1, 25);

    // -------------------------------------------------------------------------------------------------------------
    // step 2
    // locate the pupil with feature detection and compute a histogram for each,
    // the best feature will be used as rough pupil location (rectMin)

    int score = 0;
    int winner = 0;

    // feature detection
    MatOfKeyPoint matOfKeyPoints = new MatOfKeyPoint();
    FeatureDetector blobDetector = FeatureDetector.create(FeatureDetector.MSER); // Maximal Stable Extremal Regions
    blobDetector.detect(tmp1, matOfKeyPoints);
    List<KeyPoint> keyPoints = matOfKeyPoints.toList();

    // histogram calculation
    for (int i = 0; i < keyPoints.size(); i++) {
        x = (int) keyPoints.get(i).pt.x;
        y = (int) keyPoints.get(i).pt.y;
        tl = new Point(x - 5 >= 0 ? x - 5 : 0, y - 5 >= 0 ? y - 5 : 0);
        br = new Point(x + 5 < WIDTH ? x + 5 : WIDTH - 1, y + 5 < HEIGHT ? y + 5 : HEIGHT - 1);

        images = new ArrayList<Mat>();
        images.add(tmp1.submat(new Rect(tl, br)));
        channels = new MatOfInt(0);
        mask = new Mat();
        hist = new Mat();
        mHistSize = new MatOfInt(256);
        mRanges = new MatOfFloat(0f, 256f);
        Imgproc.calcHist(images, channels, mask, hist, mHistSize, mRanges);

        tmp = 0;
        for (int j = 0; j < 256 / 3; j++) {
            tmp += (256 / 3 - j) * (int) hist.get(j, 0)[0];
        }
        if (tmp >= score) {
            score = tmp;
            winner = i;
            rect = new Rect(tl, br);
        }

        if (debug) {
            // show features (orange)
            Core.circle(dbg, new Point(x, y), 3, ORANGE);
        }
    }
    if (rect == null) {
        return;
    }
    rectMin = rect.clone();

    if (debug) {
        // show rectMin (red)
        Core.rectangle(dbg, rectMin.tl(), rect.br(), RED, 1);
    }

    // -------------------------------------------------------------------------------------------------------------
    // step 3
    // compute a rectMax (blue) which is larger than the pupil

    int margin = 32;

    rect.x = rect.x - margin;
    rect.y = rect.y - margin;
    rect.width = rect.width + 2 * margin;
    rect.height = rect.height + 2 * margin;

    rectMax = rect.clone();

    if (debug) {
        // show features (orange)
        Core.rectangle(dbg, rectMax.tl(), rectMax.br(), BLUE);
    }

    // -------------------------------------------------------------------------------------------------------------
    // step 4
    // blur the image again

    Imgproc.medianBlur(src, tmp1, 7);
    Imgproc.medianBlur(tmp1, tmp1, 3);
    Imgproc.medianBlur(tmp1, tmp1, 3);
    Imgproc.medianBlur(tmp1, tmp1, 3);

    // -------------------------------------------------------------------------------------------------------------
    // step 5
    // detect edges

    Imgproc.Canny(tmp1, tmp2, 40, 50);

    // -------------------------------------------------------------------------------------------------------------
    // step 6
    // from pupil center to maxRect borders, find all edge points, compute a first ellipse

    p = new Point(rectMin.x + rectMin.width / 2, rectMin.y + rectMin.height / 2);
    pointsTest = new Vector<Point>();
    pointsEllipse = new Vector<Point>();
    pointsRemoved = new Vector<Point>();
    buff = new byte[tmp2.rows() * tmp2.cols()];
    tmp2.get(0, 0, buff);

    length = Math.min(p.x - rectMax.x - 3, p.y - rectMax.y - 3);
    length = Math.sqrt(2 * Math.pow(length, 2));
    Point z = new Point(p.x, p.y - length);
    for (int i = 0; i < 360; i += 15) {
        rad = Math.toRadians(i);
        x = (int) (p.x + Math.cos(rad) * (z.x - p.x) - Math.sin(rad) * (z.y - p.y));
        y = (int) (p.y + Math.sin(rad) * (z.x - p.x) - Math.cos(rad) * (z.y - p.y));
        pointsTest.add(new Point(x, y));
    }

    if (debug) {
        for (int i = 0; i < pointsTest.size(); i++) {
            Core.line(dbg, p, pointsTest.get(i), GRAY, 1);
            Core.rectangle(dbg, rectMin.tl(), rectMin.br(), GREEN, 1);
            Core.rectangle(dbg, rectMax.tl(), rectMax.br(), BLUE, 1);
        }
        Core.rectangle(dbg, rectMin.tl(), rectMin.br(), BLACK, -1);
        Core.rectangle(dbg, rectMin.tl(), rectMin.br(), RED, 1);
        Core.rectangle(dbg, rectMax.tl(), rectMax.br(), BLUE);
    }

    // p: Ursprung ("Mittelpunkt" der Ellipse)
    // v: Zielpunkt (Testpunkt)
    // r: Richtungsvektor PV
    for (int i = 0; i < pointsTest.size(); i++) {
        v = new Point(pointsTest.get(i).x, pointsTest.get(i).y);
        r = new Point(v.x - p.x, v.y - p.y);
        length = Math.sqrt(Math.pow(p.x - v.x, 2) + Math.pow(p.y - v.y, 2));
        boolean found = false;
        for (int j = 0; j < Math.round(length); j++) {
            s = new Point(Math.rint(p.x + (double) j / length * r.x),
                    Math.rint(p.y + (double) j / length * r.y));
            s.x = Math.max(1, Math.min(s.x, WIDTH - 2));
            s.y = Math.max(1, Math.min(s.y, HEIGHT - 2));
            tl = new Point(s.x - 1, s.y - 1);
            br = new Point(s.x + 1, s.y + 1);
            buff = new byte[3 * 3];
            rect = new Rect(tl, br);
            try {
                (tmp2.submat(rect)).get(0, 0, buff);
                for (int k = 0; k < 3 * 3; k++) {
                    if (Math.abs(buff[k]) == 1) {
                        pointsEllipse.add(s);
                        found = true;
                        break;
                    }
                }
            } catch (Exception e) {
                break;
            }
            if (found) {
                break;
            }
        }
    }

    double e_min = Double.POSITIVE_INFINITY;
    double e_max = 0;
    double e_med = 0;
    for (int i = 0; i < pointsEllipse.size(); i++) {
        v = pointsEllipse.get(i);
        length = Math.sqrt(Math.pow(p.x - v.x, 2) + Math.pow(p.y - v.y, 2));
        e_min = (length < e_min) ? length : e_min;
        e_max = (length > e_max) ? length : e_max;
        e_med = e_med + length;
    }
    e_med = e_med / pointsEllipse.size();
    if (pointsEllipse.size() >= 5) {
        Point[] points1 = new Point[pointsEllipse.size()];
        for (int i = 0; i < pointsEllipse.size(); i++) {
            points1[i] = pointsEllipse.get(i);
        }
        MatOfPoint2f points2 = new MatOfPoint2f();
        points2.fromArray(points1);
        pupil = Imgproc.fitEllipse(points2);
    }
    if (pupil.center.x == 0 && pupil.center.y == 0) {
        // something went wrong, return null
        reset();
        return;
    }

    if (debug) {
        Core.ellipse(dbg, pupil, PURPLE, 2);
    }

    // -------------------------------------------------------------------------------------------------------------
    // step 7
    // remove some outlier points and compute the ellipse again

    try {
        for (int i = 1; i <= 4; i++) {
            distance = 0;
            int remove = 0;
            for (int j = pointsEllipse.size() - 1; j >= 0; j--) {
                v = pointsEllipse.get(j);
                length = Math.sqrt(Math.pow(v.x - pupil.center.x, 2) + Math.pow(v.y - pupil.center.y, 2));
                if (length > distance) {
                    distance = length;
                    remove = j;
                }
            }
            v = pointsEllipse.get(remove);
            pointsEllipse.removeElementAt(remove);
            pointsRemoved.add(v);
        }
    } catch (Exception e) {
        // something went wrong, return null
        reset();
        return;
    }
    if (pointsEllipse.size() >= 5) {
        Point[] points1 = new Point[pointsEllipse.size()];
        for (int i = 0; i < pointsEllipse.size(); i++) {
            points1[i] = pointsEllipse.get(i);
        }
        MatOfPoint2f points2 = new MatOfPoint2f();
        points2.fromArray(points1);
        pupil = Imgproc.fitEllipse(points2);

        Point[] vertices = new Point[4];
        pupil.points(vertices);
        double d1 = Math
                .sqrt(Math.pow(vertices[1].x - vertices[0].x, 2) + Math.pow(vertices[1].y - vertices[0].y, 2));
        double d2 = Math
                .sqrt(Math.pow(vertices[2].x - vertices[1].x, 2) + Math.pow(vertices[2].y - vertices[1].y, 2));

        if (d1 >= d2) {
            pupilMajorAxis = (int) (d1 / 2);
            pupilMinorAxis = (int) (d2 / 2);
            axisA = new Point(vertices[1].x + (vertices[2].x - vertices[1].x) / 2,
                    vertices[1].y + (vertices[2].y - vertices[1].y) / 2);
            axisB = new Point(vertices[0].x + (vertices[1].x - vertices[0].x) / 2,
                    vertices[0].y + (vertices[1].y - vertices[0].y) / 2);
        } else {
            pupilMajorAxis = (int) (d2 / 2);
            pupilMinorAxis = (int) (d1 / 2);
            axisB = new Point(vertices[1].x + (vertices[2].x - vertices[1].x) / 2,
                    vertices[1].y + (vertices[2].y - vertices[1].y) / 2);
            axisA = new Point(vertices[0].x + (vertices[1].x - vertices[0].x) / 2,
                    vertices[0].y + (vertices[1].y - vertices[0].y) / 2);
        }
    }

    double ratio = (double) pupilMinorAxis / (double) pupilMajorAxis;
    if (ratio < 0.75 || 2 * pupilMinorAxis <= d_min || 2 * pupilMajorAxis >= d_max) {
        // something went wrong, return null
        reset();
        return;
    }

    // pupil found
    if (debug) {
        Core.ellipse(dbg, pupil, GREEN, 2);
        Core.line(dbg, pupil.center, axisA, RED, 2);
        Core.line(dbg, pupil.center, axisB, BLUE, 2);
        Core.circle(dbg, pupil.center, 1, GREEN, 0);

        x = 5;
        y = 5;
        Core.rectangle(dbg, new Point(x, y), new Point(x + 80 + 4, y + 10), BLACK, -1);
        Core.rectangle(dbg, new Point(x + 2, y + 2), new Point(x + 2 + pupilMajorAxis, y + 4), RED, -1);
        Core.rectangle(dbg, new Point(x + 2, y + 6), new Point(x + 2 + pupilMinorAxis, y + 8), BLUE, -1);

        for (int i = pointsEllipse.size() - 1; i >= 0; i--) {
            Core.circle(dbg, pointsEllipse.get(i), 2, ORANGE, -1);
        }
        for (int i = pointsRemoved.size() - 1; i >= 0; i--) {
            Core.circle(dbg, pointsRemoved.get(i), 2, PURPLE, -1);
        }
    }
    Core.ellipse(dst, pupil, GREEN, 2);
    Core.circle(dst, pupil.center, 1, GREEN, 0);
}

From source file:br.com.prj.TelaPrincipal.java

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

    // remove todos os labels do componente
    jPanel1.removeAll();//  ww  w .  j  a v a  2s.  co  m

    // reposicionao o primeiro label
    boundX = 12;
    boundY = 22;

    CascadeClassifier faceDetector = new CascadeClassifier(URL_LIB_FACE);

    imagemCarregada = Imgcodecs.imread(selectedFile.getAbsolutePath(), Imgcodecs.CV_LOAD_IMAGE_COLOR);
    // imagem com retangulo dos rostos encontrados
    imagemDest = new Mat(imagemCarregada.rows(), imagemCarregada.cols(), imagemCarregada.type());
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(imagemCarregada, faceDetections);

    // tentar verificar se o rect encontrado possui olhos
    Rect[] faceEncontrada = new Rect[faceDetections.toArray().length];
    int i = 0;
    for (Rect rect : faceDetections.toArray()) {

        faceEncontrada[i] = new Rect(new Point(rect.x - PAD_LATERAL + 5, rect.y - PAD_SUPERIOR + 5),
                new Point(rect.x + rect.width + PAD_LATERAL, (rect.y + rect.height + PAD_SUPERIOR) - 5));

        adicionarLabel(convertMatToImage(new Mat(imagemCarregada, faceEncontrada[i])), faceEncontrada[i]);

        //            ADICIONA RETANGULO DO ROSTO NA IMAGEM  
        //            Imgproc.rectangle(imagemDest,
        //                    new Point(rect.x - PAD_LATERAL, rect.y - PAD_SUPERIOR),
        //                    new Point(rect.x + rect.width + PAD_LATERAL, (rect.y + rect.height + PAD_SUPERIOR) - 5),
        //                    new Scalar(0, 255, 0));
        i++;
    }

    if (faceDetections.toArray().length == 0) {
        totalRostos.setText("No foi possvel identificar nenhum rosto na imagem selecionada.");
    } else {
        totalRostos
                .setText("Identificamos " + faceDetections.toArray().length + " rosto(s) na imagem carregada.");
    }

}

From source file:classes.TextExtractor.java

public void extractText(Rect roi, double roiAngle) throws Exception {

    Point roiTopLeft = roi.tl();//ww w. jav a2 s  .c  om

    double radians = Math.toRadians(roiAngle);
    double sin = Math.abs(Math.sin(radians));
    double cos = Math.abs(Math.cos(radians));

    int newWidth = (int) (image.width() * cos + image.height() * sin);
    int newHeight = (int) (image.width() * sin + image.height() * cos);

    int[] newWidthHeight = { newWidth, newHeight };

    int pivotX = newWidthHeight[0] / 2;
    int pivotY = newWidthHeight[1] / 2;

    Point center = new Point(pivotX, pivotY);

    Size targetSize = new Size(newWidthHeight[0], newWidthHeight[1]);

    Mat intermediateImage = new Mat(targetSize, image.type());

    int offsetX = (newWidthHeight[0] - image.width()) / 2;
    int offsetY = (newWidthHeight[1] - image.height()) / 2;

    Point paddedTopLeft = new Point(roiTopLeft.x + offsetX, roiTopLeft.y + offsetY);

    Mat containerImage = intermediateImage.submat(offsetY, offsetY + image.height(), offsetX,
            offsetX + image.width());
    image.copyTo(containerImage);

    Mat rotationMatrix = Imgproc.getRotationMatrix2D(center, roiAngle, 1.0);

    Point transformedTopLeft = transformPoint(paddedTopLeft, rotationMatrix);

    Mat rotatedImage = new Mat();
    Imgproc.warpAffine(intermediateImage, rotatedImage, rotationMatrix, targetSize, Imgproc.INTER_LINEAR,
            Imgproc.BORDER_CONSTANT, new Scalar(0));

    ImageUtils.saveImage(rotatedImage, imageID + "_rotatedImage.png", request);

    double adjustedWidth = roi.size().width;
    double adjustedHeight = roi.size().height;

    if (transformedTopLeft.x + adjustedWidth > rotatedImage.width()) {
        adjustedWidth = rotatedImage.width() - transformedTopLeft.x;
    }

    if (transformedTopLeft.y + adjustedHeight > rotatedImage.height()) {
        adjustedHeight = rotatedImage.height() - transformedTopLeft.y;
    }

    Rect newROI = new Rect(transformedTopLeft, new Size(adjustedWidth, adjustedHeight));

    Mat extractedROI = new Mat(rotatedImage, newROI);

    String fileName = ImageUtils.saveImage(extractedROI, imageID + "_ROI.png", request);

    extractText(fileName);
}

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

License:Apache License

public TLDView(Context context, AttributeSet attrs) {
    super(context, attrs);
    _holder = getHolder();//w  ww .jav  a 2  s  .  c om

    // Init the PROPERTIES
    InputStream propsIS = null;
    try {
        propsIS = context.getResources().openRawResource(R.raw.parameters);
        _tldProperties = new Properties();
        _tldProperties.load(propsIS);
    } catch (IOException e) {
        Log.e(Util.TAG, "Can't load properties", e);
    } finally {
        if (propsIS != null) {
            try {
                propsIS.close();
            } catch (IOException e) {
                Log.e(Util.TAG, "Can't close props", e);
            }
        }
    }

    // listens to its own events
    setCvCameraViewListener(this);

    // DEBUG
    //_trackedBox = new BoundingBox(165,93,51,54, 0, 0);

    // LISTEN for touches of the screen, to define the BOX to be tracked
    final AtomicReference<Point> trackedBox1stCorner = new AtomicReference<Point>();
    final Paint rectPaint = new Paint();
    rectPaint.setColor(Color.rgb(0, 255, 0));
    rectPaint.setStrokeWidth(5);
    rectPaint.setStyle(Style.STROKE);

    setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // re-init
            _errMessage = null;
            _tld = null;

            final Point corner = new Point(event.getX() - _canvasImgXOffset, event.getY() - _canvasImgYOffset);
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                trackedBox1stCorner.set(corner);
                Log.i(Util.TAG, "1st corner: " + corner);
                break;
            case MotionEvent.ACTION_UP:
                _trackedBox = new Rect(trackedBox1stCorner.get(), corner);
                Log.i(Util.TAG, "Tracked box DEFINED: " + _trackedBox);
                break;
            case MotionEvent.ACTION_MOVE:
                final android.graphics.Rect rect = new android.graphics.Rect(
                        (int) trackedBox1stCorner.get().x + _canvasImgXOffset,
                        (int) trackedBox1stCorner.get().y + _canvasImgYOffset,
                        (int) corner.x + _canvasImgXOffset, (int) corner.y + _canvasImgYOffset);
                final Canvas canvas = _holder.lockCanvas(rect);
                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); // remove old rectangle
                canvas.drawRect(rect, rectPaint);
                _holder.unlockCanvasAndPost(canvas);
                break;
            }

            return true;
        }
    });
}

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

License:Apache License

private static Rect scaleUp(Rect rect, Size scale) {
    if (rect == null || scale == null)
        return null;
    return new Rect(scaleUp(rect.tl(), scale), scaleUp(rect.br(), scale));
}

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

License:Apache License

private static Rect scaleDown(Rect rect, Size scale) {
    if (rect == null || scale == null)
        return null;
    return new Rect(scaleDown(rect.tl(), scale), scaleDown(rect.br(), scale));
}

From source file:cx.uni.jk.mms.iaip.tools.SimpleBrushTool.java

License:Open Source License

@Override
public Rect apply(Mat mat, BrushModel brush, int x, int y, boolean inverseEffect) {

    Rect changedArea = null;//from   w  w w.  j a  v  a  2 s .  c o m

    try {
        this.logger.finer(String.format("apply mode=\"%s\" inverse=%s, size=%d, strength=%d", brush.getMode(),
                inverseEffect, brush.getSize(), brush.getValue()));

        this.logger.finest("mat    = " + mat.toString());

        /** where is brush going to work? this may reach outside the mat! */
        int brushColStart = x - (brush.getSize() - 1) / 2;
        int brushColEnd = x + brush.getSize() / 2;
        int brushRowStart = y - (brush.getSize() - 1) / 2;
        int brushRowEnd = y + brush.getSize() / 2;

        if (brushColEnd >= 0 && brushColStart < mat.cols() && brushRowEnd >= 0 && brushRowStart < mat.rows()) {

            /** calculate bounds for roiMat to fit into original mat */
            int subColStart = Math.max(0, brushColStart);
            int subColEnd = Math.min(brushColEnd, mat.cols() - 1);
            int subRowStart = Math.max(0, brushRowStart);
            int subRowEnd = Math.min(brushRowEnd, mat.rows() - 1);

            /**
             * the caller may want to know. Rect constructor interprets the
             * second point being outside of the Rect! a one pixel rectangle
             * Rect(Point(a,b), Point(a+1,b+1)) has height and width 1. see
             * 
             * @link{http://docs.opencv.org/java/org/opencv/core/Rect.html
             */
            changedArea = new Rect(new Point(subColStart, subRowStart),
                    new Point(subColEnd + 1, subRowEnd + 1));

            /**
             * get the part of original mat which going to be affected by
             * change
             */
            Mat roiMat = mat.submat(subRowStart, subRowEnd + 1, subColStart, subColEnd + 1);
            this.logger.finest("matRoi = " + roiMat.toString());

            /** does the brush fit into the roiMat we shall work on ? */
            boolean brushFits = brushColStart == subColStart && brushColEnd == subColEnd
                    && brushRowStart == subRowStart && brushRowEnd == subRowEnd;

            this.logger.finest("brush fits = " + brushFits);

            /**
             * make sure to have a working mat which matches the full brush
             * size
             */
            Mat workMat, workRoi = null;
            if (brushFits) {
                /** just work in the original mat area defined by roi */
                workMat = roiMat;
            } else {
                /** create a new mat as big as the brush */
                workMat = Mat.zeros(brush.getSize(), brush.getSize(), MatModel.MAT_TYPE);
                this.logger.finest("workMat= " + workMat.toString());
                /**
                 * create an ROI in the workMat as big as the subMat,
                 * correct offset for brushing in the middle
                 */
                int roiColStart = subColStart - brushColStart;
                int roiColEnd = roiColStart + roiMat.cols();
                int roiRowStart = subRowStart - brushRowStart;
                int roiRowEend = roiRowStart + roiMat.rows();

                workRoi = workMat.submat(roiRowStart, roiRowEend, roiColStart, roiColEnd);
                this.logger.finest("workRoi= " + workRoi.toString());
                roiMat.copyTo(workRoi);
                this.logger.finest("workRoi= " + workRoi.toString());

                // workRoi.put(0, 0, 1333.0d);
                this.logger.finest("roiMat  dump1 " + roiMat.dump());
                this.logger.finest("workRoi dump1 " + workRoi.dump());
                this.logger.finest("workMat dump1 " + workMat.dump());
            }

            /** the real action */
            this.applyToWorkMat(brush, inverseEffect, workMat);

            this.logger.finest("workMat dump2 " + workMat.dump());
            this.logger.finest("matRoi  dump2 " + roiMat.dump());

            if (brushFits) {
                /**
                 * nothing to do, we have been working directly in original
                 * mat
                 */
            } else {
                /** copy workMat back into original mat */
                this.logger.finest("workRoi dump2 " + workRoi.dump());
                // workRoi.put(0, 0, 1338);
                this.logger.finest("workRoi dump3 " + workRoi.dump());
                /**
                 * copy roi of changed workmat back into roi of original mat
                 */
                this.logger.finest("matRoi = " + roiMat.toString());
                workRoi.copyTo(roiMat);
                this.logger.finest("matRoi = " + roiMat.toString());
            }
            this.logger.finest("matRoi  dump3 " + roiMat.dump());
        }

    } catch (CvException e) {
        /** nevermind if the user does not notice */
        this.logger.fine(e.getStackTrace().toString());
    }

    /** let the caller know caller which area has potentially been changed */
    return changedArea;
}

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/* www .  j av  a  2  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);//w w w.  j  av  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:logic.helpclass.Util.java

/**
 * Track template within the image/*from   ww w  . j  a  v a2 s .  c o m*/
 * @param grayFrame
 * @param rect
 * @param temp
 * @return 
 */
static public Rect trackTemplate(Mat grayFrame, Rect rect, Mat temp) {
    Rect searchRect = new Rect(new Point(rect.x - rect.width / 2, rect.y - rect.height / 2),
            new Point(rect.x + rect.width * 3 / 2, rect.y + rect.height * 3 / 2));

    Mat dst = new Mat(searchRect.width - temp.width() + 1, searchRect.height - temp.height() + 1, CV_32FC1);

    if ((searchRect.x < 0 || searchRect.y < 0) || (searchRect.x + searchRect.width > grayFrame.cols()
            || searchRect.y + searchRect.height > grayFrame.rows()))
        return null;

    Imgproc.matchTemplate(grayFrame.submat(searchRect), temp, dst, Imgproc.TM_SQDIFF_NORMED);

    Core.MinMaxLocResult result = Core.minMaxLoc(dst);

    //check new location: if coordinates change so variously, remain previous location
    if (true) {
        rect.x = (int) (searchRect.x + result.minLoc.x);
        rect.y = (int) (searchRect.y + result.minLoc.y);
        return rect;
    } else {
        return null;
    }
}