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(int x, int y, int width, int height) 

Source Link

Usage

From source file:PlateSegment.java

public void findPossibleCharacters() {
    // Is is assumed that the plate has been normalized?
    // If it is then we can skip this...SEGMENTATION_THRESHOLD

    // --- Threshold the plate :)
    Image image = this.getLicensePlate();
    int width = image.getImageWidth(), height = image.getImageHeight();
    Mat threshold = image.generateThresholdImage(image.equalizeHistogram(), image.SEGMENTATION_THRESHOLD);

    // --- Normalize the plate
    // step 1) adjust the plate... (streching) 

    // step 2) readjust the plate such that the external dirt is cleaned... 
    //         of course, we crop it :)

    int newWidth = (int) (width * 0.85), newHeight = (int) (height * 0.60); //By 90%;
    int newX = Math.round((width - newWidth) / 2);
    int newY = (int) (height * 0.13); //Math.round((height-newHeight)/2);
    Rect roi = new Rect(newX, newY, newWidth, newHeight);
    Mat newImage = new Mat(threshold, roi);
    /*   //from  w ww .jav  a  2  s . c o m
    //Generate threshold values for canny :)
    //Histogram h = new Histogram(image); int mean = h.getHistogramMean();
            
    //int low = 100;
    //Mat canny = image.generateCannyEdgeImage(newImage, low, low*3);
    //Imgproc.dilate(canny, canny, new Mat(), new Point(-1, -1), 1);
    */
    //List<MatOfPoint> list = image.getContourMap(newImage);
    //List<Rect> rectangles = contourToBoundingBoxes(list);

    Mat orig = image.getImage();
    Mat testImage = new Mat(orig, roi);
    //Imgproc.drawContours(testImage, list, -1, image.COLOR_RED);

    int i = 1;
    /*
    String platePatha = "/media/902A1D4D2A1D31A8/thesis/images/test/local/carrots/";
    for(Rect rectangle:rectangles){
       //Point pt1 = new Point(rectangle.x, rectangle.y),
       //     pt2 = new Point(rectangle.x+rectangle.width, rectangle.y+rectangle.height);
       //Core.rectangle(testImage, pt1, pt2, image.COLOR_GREEN, 1);
               
       String name = platePatha+"rectangle"+i+".JPG";
       Mat subimage = new Mat(testImage, rectangle);
       image.writeImageToFile(name, subimage);
               
       i++;
    }
    */
    String platePath = "/media/902A1D4D2A1D31A8/thesis/images/test/local/carrots/croppped.JPG";
    image.writeImageToFile(platePath, newImage);

}

From source file:OctoEye.java

License:Open Source License

private boolean detectSymbol(int[] shape, int ystart) {
    // create a 12x12 pixel buffer for the area of a star or ring shape
    byte buff[] = new byte[12 * 12];

    // fetch the area of a star or ring shape from the image and write it to the buffer
    Mat m = src.submat(new Rect(WIDTH - 30, ystart, 12, 12));
    m.get(0, 0, buff);/*from  w w  w. ja v  a  2s .c  om*/

    int shapePixel = -64;
    int correctPixels = 0;
    int totalPixels = 0;
    for (int i = 0; i < 12 * 12; i++) {
        correctPixels += buff[i] == shapePixel && shape[i] == 1 ? 1 : 0;
        totalPixels += shape[i];
    }
    return correctPixels == totalPixels && correctPixels > 0;
}

From source file:OCV_GrabCut.java

License:Open Source License

@Override
public int setup(String arg, ImagePlus imp) {
    if (!OCV__LoadLibrary.isLoad()) {
        IJ.error("Library is not loaded.");
        return DONE;
    }//  w  w w  . j  av a  2 s  .  com

    if (imp == null) {
        IJ.noImage();
        return DONE;
    } else {
        // get the windows
        lst_wnd = WindowManager.getIDList();

        if (lst_wnd == null || lst_wnd.length < 2) {
            IJ.error("At least more than 2 images are needed.");
            return DONE;
        }

        titles_wnd = new String[lst_wnd.length];

        for (int i = 0; i < lst_wnd.length; i++) {
            ImagePlus imp2 = WindowManager.getImage(lst_wnd[i]);
            titles_wnd[i] = imp2 != null ? imp2.getTitle() : "";
        }

        // get the ROI
        Rectangle rect_java;

        if (imp.getRoi() != null) {
            rect_java = imp.getRoi().getBounds();
        } else {
            rect_java = new Rectangle(1, 1, imp.getWidth() - 2, imp.getHeight() - 2);
        }

        rect = new Rect(rect_java.x, rect_java.y, rect_java.width, rect_java.height);

        return FLAGS;
    }
}

From source file:LicenseDetection.java

public void run() {

    // ------------------ set up tesseract for later use ------------------
    ITesseract tessInstance = new Tesseract();
    tessInstance.setDatapath("/Users/BradWilliams/Downloads/Tess4J");
    tessInstance.setLanguage("eng");

    // ------------------  Save image first ------------------
    Mat img;//  w w  w  . j a  v  a  2s . co  m
    img = Imgcodecs.imread(getClass().getResource("/resources/car_2_shopped2.jpg").getPath());
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/True_Image.png", img);

    // ------------------ Convert to grayscale ------------------
    Mat imgGray = new Mat();
    Imgproc.cvtColor(img, imgGray, Imgproc.COLOR_BGR2GRAY);
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/Gray.png", imgGray);

    // ------------------ Blur so edge detection wont pick up noise ------------------
    Mat imgGaussianBlur = new Mat();
    Imgproc.GaussianBlur(imgGray, imgGaussianBlur, new Size(3, 3), 0);
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/gaussian_blur.png", imgGaussianBlur);

    // ****************** Create image that will be cropped at end of program before OCR ***************************

    // ------------------ Binary theshold for OCR (used later)------------------
    Mat imgThresholdOCR = new Mat();
    Imgproc.adaptiveThreshold(imgGaussianBlur, imgThresholdOCR, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C,
            Imgproc.THRESH_BINARY, 7, 10);
    //Imgproc.threshold(imgSobel,imgThreshold,120,255,Imgproc.THRESH_TOZERO);
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgThresholdOCR.png", imgThresholdOCR);

    // ------------------ Erosion operation------------------
    Mat kern = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_CROSS, new Size(3, 3));
    Mat imgErodeOCR = new Mat();
    Imgproc.morphologyEx(imgThresholdOCR, imgErodeOCR, Imgproc.MORPH_DILATE, kern); //Imgproc.MORPH_DILATE is performing erosion, wtf?
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgErodeOCR.png", imgErodeOCR);

    //------------------ Dilation operation  ------------------
    Mat kernall = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(3, 3));
    Mat imgDilateOCR = new Mat();
    Imgproc.morphologyEx(imgErodeOCR, imgDilateOCR, Imgproc.MORPH_ERODE, kernall);
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgDilateOCR.png", imgDilateOCR);

    // *************************************************************************************************************

    //        // ------------------ Close operation (dilation followed by erosion) to reduce noise ------------------
    //        Mat k = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(3, 3));
    //        Mat imgCloseOCR = new Mat();
    //        Imgproc.morphologyEx(imgThresholdOCR,imgCloseOCR,1,k);
    //        Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgCloseOCR.png", imgCloseOCR);

    // ------------------ Sobel vertical edge detection ------------------
    Mat imgSobel = new Mat();
    Imgproc.Sobel(imgGaussianBlur, imgSobel, -1, 1, 0);
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgSobel.png", imgSobel);

    // ------------------ Binary theshold ------------------
    Mat imgThreshold = new Mat();
    Imgproc.adaptiveThreshold(imgSobel, imgThreshold, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C,
            Imgproc.THRESH_BINARY, 99, -60);
    //Imgproc.threshold(imgSobel,imgThreshold,120,255,Imgproc.THRESH_TOZERO);
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgThreshold.png", imgThreshold);

    //        // ------------------ Open operation (erosion followed by dilation) ------------------
    //        Mat ker = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_CROSS, new Size(3, 2));
    //        Mat imgOpen = new Mat();
    //        Imgproc.morphologyEx(imgThreshold,imgOpen,0,ker);
    //        Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgOpen.png", imgOpen);

    // ------------------ Close operation (dilation followed by erosion) to reduce noise ------------------
    Mat kernel = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(22, 8));
    Mat imgClose = new Mat();
    Imgproc.morphologyEx(imgThreshold, imgClose, 1, kernel);
    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgClose.png", imgClose);

    // ------------------ Find contours ------------------
    List<MatOfPoint> contours = new ArrayList<>();

    Imgproc.findContours(imgClose, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

    // **************************** DEBUG CODE **************************

    Mat contourImg = new Mat(imgClose.size(), imgClose.type());
    for (int i = 0; i < contours.size(); i++) {
        Imgproc.drawContours(contourImg, contours, i, new Scalar(255, 255, 255), -1);
    }

    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/contours.png", contourImg);

    // ******************************************************************

    // --------------  Convert contours --------------------

    //Convert to MatOfPoint2f so that minAreaRect can be called
    List<MatOfPoint2f> newContours = new ArrayList<>();

    for (MatOfPoint mat : contours) {

        MatOfPoint2f newPoint = new MatOfPoint2f(mat.toArray());
        newContours.add(newPoint);

    }

    //Get minAreaRects
    List<RotatedRect> minAreaRects = new ArrayList<>();

    for (MatOfPoint2f mat : newContours) {

        RotatedRect rect = Imgproc.minAreaRect(mat);

        /*
         --------------- BUG WORK AROUND ------------
                
        Possible bug:
        When converting from MatOfPoint2f to RotatectRect the width height were reversed and the
        angle was -90 degrees from what it would be if the width and height were correct.
                
        When painting rectangle in image, the correct boxes were produced, but performing calculations on rect.angle
        rect.width, or rect.height yielded unwanted results.
                
        The following work around is buggy but works for my purpose
         */

        if (rect.size.width < rect.size.height) {
            double temp;

            temp = rect.size.width;
            rect.size.width = rect.size.height;
            rect.size.height = temp;
            rect.angle = rect.angle + 90;

        }

        //check aspect ratio and area and angle
        if (rect.size.width / rect.size.height > 1 && rect.size.width / rect.size.height < 5
                && rect.size.width * rect.size.height > 10000 && rect.size.width * rect.size.height < 50000
                && Math.abs(rect.angle) < 20) {
            minAreaRects.add(rect);
        }

        //minAreaRects.add(rect);
    }

    // **************************** DEBUG CODE **************************
    /*
    The following code is used to draw the rectangles on top of the original image for debugging purposes
     */
    //Draw Rotated Rects
    Point[] vertices = new Point[4];

    Mat imageWithBoxes = img;

    // Draw color rectangles on top of binary contours
    //        Mat imageWithBoxes = new Mat();
    //        Mat temp = imgDilateOCR;
    //        Imgproc.cvtColor(temp, imageWithBoxes, Imgproc.COLOR_GRAY2RGB);

    for (RotatedRect rect : minAreaRects) {

        rect.points(vertices);

        for (int i = 0; i < 4; i++) {
            Imgproc.line(imageWithBoxes, vertices[i], vertices[(i + 1) % 4], new Scalar(0, 0, 255), 2);
        }

    }

    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgWithBoxes.png", imageWithBoxes);

    // ******************************************************************

    // **************************** DEBUG CODE **************************
    //        for(RotatedRect rect : minAreaRects) {
    //            System.out.println(rect.toString());
    //        }
    // ******************************************************************

    /*
    In order to rotate image without cropping it:
            
    1. Create new square image with dimension = diagonal of initial image.
    2. Draw initial image into the center of new image.
     Insert initial image at ROI (Region of Interest) in new image
    3. Rotate new image
     */

    //Find diagonal/hypotenuse
    int hypotenuse = (int) Math.sqrt((img.rows() * img.rows()) + (img.cols() * img.cols()));

    //New Mat with hypotenuse as height and width
    Mat rotateSpace = new Mat(hypotenuse, hypotenuse, 0);

    int ROI_x = (rotateSpace.width() - imgClose.width()) / 2; //x start of ROI
    int ROI_y = (rotateSpace.height() - imgClose.height()) / 2; //x start of ROI

    //designate region of interest
    Rect r = new Rect(ROI_x, ROI_y, imgClose.width(), imgClose.height());

    //Insert image into region of interest
    imgDilateOCR.copyTo(rotateSpace.submat(r));

    Mat rotatedTemp = new Mat(); //Mat to hold temporarily rotated mat
    Mat rectMat = new Mat();//Mat to hold rect contents (needed for looping through pixels)
    Point[] rectVertices = new Point[4];//Used to build rect to make ROI
    Rect rec = new Rect();

    List<RotatedRect> edgeDensityRects = new ArrayList<>(); //populate new arraylist with rects that satisfy edge density

    int count = 0;

    //Loop through Rotated Rects and find edge density
    for (RotatedRect rect : minAreaRects) {

        count++;

        rect.center = new Point((float) ROI_x + rect.center.x, (float) ROI_y + rect.center.y);

        //rotate image to math orientation of rotated rect
        rotate(rotateSpace, rotatedTemp, rect.center, rect.angle);

        //remove rect rotation
        rect.angle = 0;

        //get vertices from rotatedRect
        rect.points(rectVertices);

        // **************************** DEBUG CODE **************************
        //
        //            for (int k = 0; k < 4; k++) {
        //                System.out.println(rectVertices[k]);
        //                Imgproc.line(rotatedTemp, rectVertices[k], rectVertices[(k + 1) % 4], new Scalar(0, 0, 255), 2);
        //            }
        //
        //            Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rotated" + count + ".png", rotatedTemp);

        // *****************************************************************

        //build rect to use as ROI
        rec = new Rect(rectVertices[1], rectVertices[3]);

        rectMat = rotatedTemp.submat(rec);

        Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/extracted" + count + ".png", rectMat);

        //find edge density

        //            // ------------------------ edge density check NOT IMPLEMENTED --------------------
        //            /*
        //            Checking for edge density was not necessary for this image so it was not implemented due to lack of time
        //             */
        //            for(int i = 0; i < rectMat.rows(); ++i){
        //                for(int j = 0; j < rectMat.cols(); ++j){
        //
        //                  //add up white pixels
        //                }
        //            }
        //
        //            //check number of white pixels against total pixels
        //            //only add rects to new arraylist that satisfy threshold

        edgeDensityRects.add(rect);
    }

    // **************************** DEBUG CODE **************************

    Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rotatedSpace.png", rotateSpace);
    //Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rotatedSpaceROTATED.png", rotatedTemp);

    //System.out.println(imgGray.type());

    // *****************************************************************

    // if there is only one rectangle left, its the license plate
    if (edgeDensityRects.size() == 1) {

        String result = ""; //Hold result from OCR
        BufferedImage bimg;
        Mat cropped;

        cropped = rectMat.submat(new Rect(20, 50, rectMat.width() - 40, rectMat.height() - 70));

        Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rectMatCropped.png", cropped);

        bimg = matToBufferedImage(cropped);

        BufferedImage image = bimg;

        try {
            result = tessInstance.doOCR(image);
        } catch (TesseractException e) {
            System.err.println(e.getMessage());
        }

        for (int i = 0; i < 10; ++i) {

        }

        result = result.replace("\n", "");

        System.out.println(result);

        CarProfDBImpl db = new CarProfDBImpl();

        db.connect("localhost:3306/computer_vision", "root", "*******");

        CarProf c = db.getCarProf(result);

        System.out.print(c.toString());

        db.close();

    }

}

From source file:abc.RomanCharacterPicture.java

public int evaluatePicture() {
    try {/*  w ww. jav a 2 s. co  m*/
        ITesseract instance = new Tesseract();

        MatToBufImg webcamImageBuff = new MatToBufImg();

        webcamImageBuff.setMatrix(webcam_image, ".jpg");
        double heightRatio = (double) webcamImageBuff.getBufferedImage().getHeight()
                / (double) webcam_image.height();
        double widthRatio = (double) webcamImageBuff.getBufferedImage().getWidth()
                / (double) webcam_image.width();
        int x1 = this.leftRectangle.getxPos();
        int y1 = this.leftRectangle.getyPos();
        int x2 = this.rightRectangle.getxPos();
        int y2 = this.rightRectangle.getyPos();
        Rect rect = new Rect(leftRectangle.getxPos(), leftRectangle.getyPos(),
                (rightRectangle.getxPos() - leftRectangle.getxPos()),
                (rightRectangle.getyPos() - leftRectangle.getyPos()));
        //Rect rect = new Rect(new Point(leftRectangle.getxPos(), leftRectangle.getyPos()), new Point(leftRectangle.getxPos(), rightRectangle.getyPos()), , (rightRectangle.getxPos()-leftRectangle.getxPos()));
        Mat subImageMat = webcam_image.submat(rect);

        BufferedImage romanCharacter = webcamImageBuff.getBufferedImage().getSubimage((int) (x1 * widthRatio),
                (int) (y1 * heightRatio), (int) (widthRatio * (x2 - x1)), (int) (heightRatio * (y2 - y1)));

        //int[] pixels = ((DataBufferInt) romanCharacter.getRaster().getDataBuffer()).getData();
        //Mat subImageMat = new Mat(romanCharacter.getHeight(), romanCharacter.getWidth(), CvType.CV_8UC3);
        //subImageMat.put(0, 0, pixels);

        Mat hsv_image = new Mat();
        Imgproc.cvtColor(subImageMat, hsv_image, Imgproc.COLOR_BGR2HSV);

        Mat lower_black_hue_range = new Mat();
        Mat upper_black_hue_range = new Mat();

        Core.inRange(hsv_image, new Scalar(0, 0, 0), new Scalar(180, 255, 30), lower_black_hue_range);
        Core.inRange(hsv_image, new Scalar(0, 0, 20), new Scalar(180, 255, 40), upper_black_hue_range);

        Mat black_hue_image = new Mat();
        Core.addWeighted(lower_black_hue_range, 1.0, upper_black_hue_range, 1.0, 0.0, black_hue_image);

        Imgproc.GaussianBlur(black_hue_image, black_hue_image, new Size(9, 9), 2, 2);

        MatToBufImg blackImageBuff = new MatToBufImg();

        blackImageBuff.setMatrix(black_hue_image, ".jpg");
        BufferedImage test = blackImageBuff.getBufferedImage();

        //ImageIO.write(test, "PNG", new FileOutputStream((Math.round(Math.random()*1000))+"dst.png"));
        String result = instance.doOCR(test);
        int counterI = 0;
        for (int i = 0; i < result.length(); i++) {
            if (result.charAt(i) == 'I' || result.charAt(i) == 'l' || result.charAt(i) == '1'
                    || result.charAt(i) == 'i' || result.charAt(i) == 'L' || result.charAt(i) == 'j'
                    || result.charAt(i) == 'J') {
                counterI++;
            }
        }

        int counterV = 0;
        for (int i = 0; i < result.length(); i++) {
            if (result.charAt(i) == 'V' || result.charAt(i) == 'v' || result.charAt(i) == 'W'
                    || result.charAt(i) == 'w' || result.contains("\\//")) {
                counterV++;
            }
        }
        //System.out.println("Result: "+result+ " calc:" + (counterI + (counterV * 5)));
        return (counterI + (counterV * 5));
    } catch (Exception ex) {
        //System.out.println(ex.getMessage());
        ex.printStackTrace();
        return 0;
    }

}

From source file:bikecalibration.fxml.controller.MainWindowController.java

private boolean createAndDrawNode(MouseEvent event) {
    try {/*from   w w w  . j  a  v a  2s . co  m*/
        // create the node
        Mat original_mat = OpenCvUtils.getImageFromVideo(currentVideoFrameNumberProperty.get(), cap);
        double original_width = original_mat.cols();
        double resized_width = imageViewCanvas.getWidth();

        double[] orig_coords = Utils.calculateOriginalCoordinates(original_width, resized_width,
                new double[] { event.getX(), event.getY() });
        double[] orig_width = Utils.calculateOriginalCoordinates(original_width, resized_width,
                new double[] { NODE_WIDTH });
        Rect roi = new Rect((int) orig_coords[0], (int) orig_coords[1], (int) orig_width[0],
                (int) orig_width[0]);
        Mat roi_mat = original_mat.submat(roi);
        Node n = new Node((int) orig_coords[0], (int) orig_coords[1], cpickerNode.getValue().toString(),
                currentVideoFrameNumberProperty.getName(), null);
        n.setRoi(roi_mat);
        n.setId(nodeData.size());
        nodeData.add(n);

        // add the node to the nodes array
        Node[] currentFrameNodes = nodes[currentVideoFrameNumberProperty.get()];
        if (currentFrameNodes == null) {
            currentFrameNodes = new Node[1];
            currentFrameNodes[0] = n;
            nodes[currentVideoFrameNumberProperty.get()] = currentFrameNodes;
        } else {
            Node[] tmp = new Node[currentFrameNodes.length + 1];
            int i = 0;
            for (Node currentFrameNode : currentFrameNodes) {
                tmp[i] = currentFrameNode;
                ++i;
            }
            tmp[i] = n;
            nodes[currentVideoFrameNumberProperty.get()] = tmp;
        }
        // start editing current image
        drawImage(Utils.matToImage(original_mat));
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:by.zuyeu.deyestracker.core.detection.model.DetectFaceSample.java

public DetectFaceSample(final boolean fillWithZero) {
    face = new Rect(0, 0, 0, 0);
    leftEye = new Rect(0, 0, 0, 0);
    rightEye = new Rect(0, 0, 0, 0);
    leftPupil = new Point(0, 0);
    rightPupil = new Point(0, 0);
}

From source file:cmib_4_4.Countour.java

public static void main(String args[]) {

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    Mat image = Highgui.imread("input1.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE);
    Mat image1 = Highgui.imread("input1.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE);
    Mat image4 = Highgui.imread("input1.jpg");
    Imgproc.threshold(image1, image1, 0, 255, THRESH_OTSU);
    Imgproc.Canny(image1, image1, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU,
            Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);
    Mat image2 = Mat.zeros(image.rows() + 2, image.cols() + 2, CV_8U);
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Imgproc.findContours(image1, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

    for (int i = 0; i < contours.size(); i++) {

        if (Imgproc.contourArea(contours.get(i)) > 100) {

            Rect rect = Imgproc.boundingRect(contours.get(i));
            Imgproc.floodFill(image1, image2, new Point(150, 150), new Scalar(255));
            Rect rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
            Mat image_roi_rgb = new Mat(image4, rectCrop);
            Highgui.imwrite("crop2.jpg", image_roi_rgb);
            if (rect.height > 28) {

                Core.rectangle(image, new Point(rect.x, rect.y),
                        new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 0, 255));
            }// w ww.  j ava  2s  . com
        }
    }
    Highgui.imwrite("falciparum2.jpg", image);

}

From source file:cn.xiongyihui.webcam.setup.java

License:Open Source License

@Override
public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        try {/*  w  w w .  j a  v  a2 s  .c o m*/
            final ImageView imageView = (ImageView) findViewById(R.id.imageView);

            int X = (int) event.getX();
            int Y = (int) event.getY();

            int[] coordinates = new int[2];//{0,0};
            imageView.getLocationOnScreen(coordinates);
            int viewTop = coordinates[1];
            int viewBottom = coordinates[1] + imageView.getHeight();
            try {
                int viewLeft = coordinates[2];
                int viewRight = coordinates[2] + imageView.getWidth();
            } catch (Exception e) {
                Log.e(TAG, "getLocationOnScreen:Error!");
            }

            imageViewHeight = (double) viewBottom - viewTop;
            imageViewWidth = aspectRatio * imageViewHeight;

            int imageViewWidthINT = (int) imageViewWidth;
            int imageViewHeightINT = (int) imageViewHeight;

            Display display = getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int widthScreen = (int) size.x;
            int heightScreen = (int) size.y;

            int Yoffset = heightScreen - viewBottom;
            int Xoffset = widthScreen - imageView.getWidth();

            int virtualOriginX = (int) ((widthScreen - imageViewWidthINT + Xoffset) / 2);
            int virtualOriginY = (int) (heightScreen - imageViewHeightINT - Yoffset / 2);

            x0 = X - virtualOriginX;
            y0 = Y - virtualOriginY;

            double openCVratio = (double) bitmapHeight / imageViewHeight;

            x0final = (int) ((double) x0 * openCVratio);
            y0final = (int) ((double) y0 * openCVratio);
        } catch (Exception e) {
            Log.e(TAG, "Touch events are not working!");
        }
    }

    if (event.getAction() == MotionEvent.ACTION_UP) {
        try {
            final ImageView imageView = (ImageView) findViewById(R.id.imageView);

            int X = (int) event.getX();
            int Y = (int) event.getY();

            int[] coordinates = new int[2];//{0,0};
            imageView.getLocationOnScreen(coordinates);
            int viewTop = coordinates[1];
            int viewBottom = coordinates[1] + imageView.getHeight();
            try {
                int viewLeft = coordinates[2];
                int viewRight = coordinates[2] + imageView.getWidth();
            } catch (Exception e) {
                Log.e(TAG, "getLocationOnScreen:Error!");
            }

            imageViewHeight = (double) viewBottom - viewTop;
            imageViewWidth = aspectRatio * imageViewHeight;

            int imageViewWidthINT = (int) imageViewWidth;
            int imageViewHeightINT = (int) imageViewHeight;

            Display display = getWindowManager().getDefaultDisplay();
            android.graphics.Point size = new android.graphics.Point();
            display.getSize(size);
            int widthScreen = (int) size.x;
            int heightScreen = (int) size.y;

            int Yoffset = heightScreen - viewBottom;
            int Xoffset = widthScreen - imageView.getWidth();

            int virtualOriginX = (int) ((widthScreen - imageViewWidthINT + Xoffset) / 2);
            int virtualOriginY = (int) (heightScreen - imageViewHeightINT - Yoffset / 2);

            x1 = X - virtualOriginX;
            y1 = Y - virtualOriginY;

            double openCVratio = (double) bitmapHeight / imageViewHeight;

            x1final = (int) ((double) x1 * openCVratio);
            y1final = (int) ((double) y1 * openCVratio);

            bitmap = BitmapFactory.decodeFile(filePath);
            bitmap = Bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, true);
            Mat frame = new Mat(bitmap.getHeight(), bitmap.getHeight(), CvType.CV_8UC3);
            Utils.bitmapToMat(bitmap, frame);
            rect = new Rect(x0final, y0final, x1final - x0final, y1final - y0final);
            Core.rectangle(frame, rect.tl(), rect.br(), color, 3);
            Utils.matToBitmap(frame, bitmap);
            imageView.setImageBitmap(bitmap);
        } catch (Exception e) {
            Log.e(TAG, "Touch events are not working!");
        }
    }

    return true;
}

From source file:cn.xiongyihui.webcam.setup.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setup);

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    final Button cameraButton = (Button) findViewById(R.id.cameraButton);
    final Button selectButton = (Button) findViewById(R.id.selectButton);
    final Button templateButton = (Button) findViewById(R.id.templateButton);
    final Button instructionButton = (Button) findViewById(R.id.instructionButton);
    final ImageView imageView = (ImageView) findViewById(R.id.imageView);

    try {/*from w  w  w  . j a  v  a2 s.c o m*/
        int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();

        Toast.makeText(this, NUMBER_OF_CORES, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Log.e(TAG, "Processor-cores are not getting detected!");
    }

    try {
        final Toast toast = Toast.makeText(this,
                "Please capture image; \n" + "select image; \n"
                        + "Drag-and-drop, swipe on the desired region and confirm template!",
                Toast.LENGTH_LONG);
        final TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
        instructionButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (v != null)
                    v.setGravity(Gravity.CENTER);
                toast.show();
            }
        });
    } catch (Exception e) {
        Log.e(TAG, "Instructions are not getting displayed!");
    }

    try {
        cameraButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, requestCode);
            }
        });
    } catch (Exception e) {
        Log.e(TAG, "Camera is not working!");
    }

    try {
        selectButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, requestCode);

                bitmap = BitmapFactory.decodeFile(filePath);
                imageView.setImageBitmap(bitmap);
            }
        });
    } catch (Exception e) {
        Log.e(TAG, "Selection is not working!");
    }

    try {
        templateButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (imageView.getDrawable() == null) {
                    Log.e(TAG, "Null ImageView!");
                }
                Log.e(TAG, "Button is working.");
                try {
                    bitmap = BitmapFactory.decodeFile(filePath);
                    bitmap = Bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, true);
                    Mat frame = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC4);
                    Utils.bitmapToMat(bitmap, frame);

                    GlobalClass globalVariable = (GlobalClass) getApplicationContext();
                    globalVariable.setTemplateCapturedBitmapHeight(bitmapHeight);
                    globalVariable.setTemplateCapturedBitmapWidth(bitmapWidth);
                    Log.e(TAG, "Bitmap has been set successfully; Template is being generated!");

                    rect = new Rect(x0final, y0final, x1final - x0final, y1final - y0final);
                    Utils.matToBitmap(frame, bitmap);

                    if (x0final < x1final) {
                        x0display = x0final;
                        x1display = x1final;
                    }
                    if (x0final > x1final) {
                        x1display = x0final;
                        x0display = x1final;
                    }
                    if (y0final < y1final) {
                        y0display = y0final;
                        y1display = y1final;
                    }
                    if (y0final > y1final) {
                        y1display = y0final;
                        y0display = y1final;
                    }

                    long timeBegin = (int) System.currentTimeMillis();

                    bitmap = Bitmap.createBitmap(bitmap, x0display, y0display, x1display - x0display,
                            y1display - y0display);

                    /*String path = Environment.getExternalStorageDirectory().toString();
                            
                    Log.e(TAG, "File is about to be written!");
                            
                    //File file = new File(path, "TraQuad");
                    //bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOutputStream);
                            
                    //Log.e(TAG, "Stored image successfully!");
                    //fOutputStream.flush();
                    //fOutputStream.close();
                            
                    //MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());*/

                    /*Prominent colors code; This is not working in Android; OpenCV assertion error
                    Log.e(TAG, "Retrieved image successfully!");
                            
                    Imgproc.medianBlur(frame, frame, 3);
                    Log.e(TAG, "Filtered image successfully!");
                            
                    try {
                    Mat mask = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1);
                    MatOfFloat range = new MatOfFloat(0f, 255f);
                    Mat hist = new Mat();
                    MatOfInt mHistSize = new MatOfInt(256);
                    List<Mat> lHsv = new ArrayList<Mat>(3);
                    Mat hsv = new Mat();
                    Imgproc.cvtColor(frame, hsv, Imgproc.COLOR_RGB2HSV);
                    Core.split(frame, lHsv);
                    Mat mH = lHsv.get(0);
                    Mat mS = lHsv.get(1);
                    Mat mV = lHsv.get(2);
                    ArrayList<Mat> ListMat = new ArrayList<Mat>();
                    ListMat.add(mH);
                    Log.e(TAG, String.valueOf(ListMat));
                    MatOfInt channels = new MatOfInt(0, 1);
                    Imgproc.calcHist(Arrays.asList(mH), channels, mask, hist, mHistSize, range);
                    ListMat.clear();
                    }catch (Exception e){
                    Log.e(TAG, "Prominent colors are not getting detected!");
                    }*/

                    Mat colorFrame = frame;
                    colorFrame = frame.clone();

                    Utils.bitmapToMat(bitmap, frame);
                    Imgproc.cvtColor(frame, frame, Imgproc.COLOR_RGB2GRAY);

                    Log.e(TAG, "Converted color successfully!");

                    int detectorType = FeatureDetector.ORB;
                    //int detectorType = FeatureDetector.SIFT; //SIFT and SURF are not working!
                    //int detectorType = FeatureDetector.SURF;
                    FeatureDetector featureDetector = FeatureDetector.create(detectorType);

                    Log.e(TAG, "Feature detection has begun!");

                    MatOfKeyPoint keypoints = new MatOfKeyPoint();

                    featureDetector.detect(frame, keypoints);

                    Log.e(TAG, "Feature detection has ended successfully!");

                    /*if (!featureDetector.empty()) {
                    //Draw the detected keypoints
                    int flagDraw = Features2d.NOT_DRAW_SINGLE_POINTS;
                    Features2d.drawKeypoints(frame, keypoints, frame, color, flagDraw);
                    Utils.matToBitmap(frame, bitmap);
                    }*/

                    imageView.setImageBitmap(bitmap);

                    Log.e(TAG, "Final bitmap has been loaded!");

                    KeyPoint[] referenceKeypoints = keypoints.toArray();

                    Log.e(TAG, "Number of keypoints detected is " + String.valueOf(referenceKeypoints.length));

                    int iterationMax = referenceKeypoints.length;
                    int iterate = 0;
                    double xFeaturePoint, yFeaturePoint;
                    double xSum = 0, ySum = 0;
                    double totalResponse = 0;
                    double keyPointResponse = 0;
                    double xTemplateCentroid = 0, yTemplateCentroid = 0;

                    DescriptorExtractor descriptorExtractor = DescriptorExtractor
                            .create(DescriptorExtractor.ORB);

                    Mat templateDescriptor = new Mat();

                    descriptorExtractor.compute(frame, keypoints, templateDescriptor);

                    for (iterate = 0; iterate < iterationMax; iterate++) {
                        xFeaturePoint = referenceKeypoints[iterate].pt.x;
                        yFeaturePoint = referenceKeypoints[iterate].pt.y;
                        keyPointResponse = referenceKeypoints[iterate].response;

                        if (keyPointResponse > 0) {
                            xSum = xSum + keyPointResponse * xFeaturePoint;
                            ySum = ySum + keyPointResponse * yFeaturePoint;
                            totalResponse = totalResponse + keyPointResponse;

                            //Log.e(TAG, "Feature " + String.valueOf(iterate) + ":" + String.valueOf(referenceKeypoints[iterate]));
                        }
                    }

                    xTemplateCentroid = xSum / totalResponse;
                    yTemplateCentroid = ySum / totalResponse;
                    Log.e(TAG, "Finished conversion of features to points!");
                    Log.e(TAG, "Centroid location is: (" + xTemplateCentroid + "," + yTemplateCentroid + ")");

                    double xSquareDistance = 0, ySquareDistance = 0;
                    double distanceTemplateFeatures = 0;
                    int numberOfPositiveResponses = 0;

                    double[] colorValue;
                    double rSum = 0, gSum = 0, bSum = 0;
                    double rCentral, gCentral, bCentral;

                    for (iterate = 0; iterate < iterationMax; iterate++) {
                        xFeaturePoint = referenceKeypoints[iterate].pt.x;
                        yFeaturePoint = referenceKeypoints[iterate].pt.y;
                        keyPointResponse = referenceKeypoints[iterate].response;

                        colorValue = colorFrame.get((int) yFeaturePoint, (int) xFeaturePoint);
                        rSum = rSum + colorValue[0];
                        gSum = gSum + colorValue[1];
                        bSum = bSum + colorValue[2];

                        if (keyPointResponse > 0) {
                            xSquareDistance = xSquareDistance
                                    + (xFeaturePoint - xTemplateCentroid) * (xFeaturePoint - xTemplateCentroid);
                            ySquareDistance = ySquareDistance
                                    + (yFeaturePoint - yTemplateCentroid) * (yFeaturePoint - yTemplateCentroid);
                            numberOfPositiveResponses++;
                        }
                    }

                    rCentral = rSum / iterationMax;
                    gCentral = gSum / iterationMax;
                    bCentral = bSum / iterationMax;

                    double deltaColor = 21;

                    double rLow = rCentral - deltaColor;
                    double rHigh = rCentral + deltaColor;
                    double gLow = rCentral - deltaColor;
                    double gHigh = rCentral + deltaColor;
                    double bLow = rCentral - deltaColor;
                    double bHigh = rCentral + deltaColor;

                    Log.e(TAG, "Prominent color (R,G,B): (" + rCentral + "," + gCentral + "," + bCentral + ")");

                    distanceTemplateFeatures = Math
                            .sqrt((xSquareDistance + ySquareDistance) / numberOfPositiveResponses);

                    KeyPoint[] offsetCompensatedKeyPoints = keypoints.toArray();

                    double xMaxNormalisation, yMaxNormalisation;

                    xMaxNormalisation = x1display - x0display;
                    yMaxNormalisation = y1display - y0display;

                    for (iterate = 0; iterate < iterationMax; iterate++) {
                        offsetCompensatedKeyPoints[iterate].pt.x = offsetCompensatedKeyPoints[iterate].pt.x
                                / xMaxNormalisation;
                        offsetCompensatedKeyPoints[iterate].pt.y = offsetCompensatedKeyPoints[iterate].pt.y
                                / yMaxNormalisation;

                        //Log.e(TAG, "Compensated: (" + String.valueOf(offsetCompensatedKeyPoints[iterate].pt.x) + "," + String.valueOf(offsetCompensatedKeyPoints[iterate].pt.y) + ")");
                    }

                    double xCentroidNormalised, yCentroidNormalised;

                    xCentroidNormalised = (xTemplateCentroid - x0display) / xMaxNormalisation;
                    yCentroidNormalised = (yTemplateCentroid - y0display) / yMaxNormalisation;

                    Log.e(TAG, "Normalised Centroid: (" + String.valueOf(xCentroidNormalised) + ","
                            + String.valueOf(yCentroidNormalised));

                    long timeEnd = (int) System.currentTimeMillis();
                    Log.e(TAG, "Time consumed is " + String.valueOf(timeEnd - timeBegin) + " milli-seconds!");

                    Log.e(TAG, "RMS distance is: " + distanceTemplateFeatures);

                    globalVariable.setDistanceTemplateFeatures(distanceTemplateFeatures);
                    globalVariable.setX0display(x0display);
                    globalVariable.setY0display(y0display);
                    globalVariable.setX1display(x1display);
                    globalVariable.setY1display(y1display);
                    globalVariable.setKeypoints(keypoints);
                    globalVariable.setXtemplateCentroid(xTemplateCentroid);
                    globalVariable.setYtemplateCentroid(yTemplateCentroid);
                    globalVariable.setTemplateDescriptor(templateDescriptor);
                    globalVariable.setNumberOfTemplateFeatures(iterationMax);
                    globalVariable.setNumberOfPositiveTemplateFeatures(numberOfPositiveResponses);
                    globalVariable.setRhigh(rHigh);
                    globalVariable.setRlow(rLow);
                    globalVariable.setGhigh(gHigh);
                    globalVariable.setGlow(gLow);
                    globalVariable.setBhigh(bHigh);
                    globalVariable.setBlow(bLow);
                    globalVariable.setXnormalisedCentroid(xCentroidNormalised);
                    globalVariable.setYnormalisedCentroid(yCentroidNormalised);
                    globalVariable.setNormalisedTemplateKeyPoints(offsetCompensatedKeyPoints);

                    Log.e(TAG, "Finished setting the global variables!");

                } catch (Exception e) {
                    Log.e(TAG, "Please follow instructions!");
                }
            }
        });
    } catch (Exception e) {
        Log.e(TAG, "Template is not working!");
    }

}