Example usage for org.opencv.core MatOfRect toArray

List of usage examples for org.opencv.core MatOfRect toArray

Introduction

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

Prototype

public Rect[] toArray() 

Source Link

Usage

From source file:Fiji_OpenCV.java

License:Creative Commons License

public void process(int[] pixels) {
    int channels = 3;
    byte[] buf = new byte[pixels.length * channels];
    for (int i = 0; i < pixels.length; i++) {
        buf[i * channels] = (byte) (0x000000ff & (pixels[i]));
        buf[i * channels + 1] = (byte) (0x000000ff & (pixels[i] >>> 8));
        buf[i * channels + 2] = (byte) (0x000000ff & (pixels[i] >>> 16));
    }//w w  w .j  av a  2  s  . c o  m

    Mat image = new Mat(width, height, CvType.CV_8UC3);
    image.put(0, 0, buf);

    // Create a face detector from the cascade file in the resources
    // directory.
    CascadeClassifier faceDetector = new CascadeClassifier(
            getClass().getResource("/opencv/data/haarcascades/haarcascade_frontalface_alt2.xml").getPath());

    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
                new Scalar(0, 255, 0));
    }

    image.get(0, 0, buf);
    for (int i = 0; i < pixels.length; i++) {
        pixels[i] = 0x80000000 + ((int) (buf[i * channels + 2]) << 16) + ((int) (buf[i * channels + 1]) << 8)
                + ((int) (buf[i * channels + 0]));
    }
    this.ip = new ColorProcessor(width, height, pixels);
}

From source file:M.java

/**
 * Resize the certain image to required size (WIDTH*HEIGHT).
 *
 * @param imgPath the path of the image.
 * @return the path of the resized image.
 * @throws Exception//from   w w  w .j a  va2  s .  c o  m
 */
public static String resize(String imgPath) throws Exception {
    System.out.println("\nRunning DetectFaceDemo");
    String xmlfilePath = FaceDetector.class.getResource("haarcascade_frontalface_alt.xml").getPath()
            .substring(1);
    System.out.println(xmlfilePath);//test
    CascadeClassifier faceDetector = new CascadeClassifier(xmlfilePath);
    //        String imgPath=FaceDetector.class.getResource("cam_img/test.jpg").getPath().substring(1);
    Mat image = Highgui.imread(imgPath);
    System.out.println(imgPath);
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);
    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
    int count = 1;
    String dir = "";
    for (Rect rect : faceDetections.toArray()) {
        ImageFilter cropFilter = new CropImageFilter(rect.x, rect.y, rect.width, rect.height);
        BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
        //            File file = new File("build\\classes\\cam_img\\test.jpg");
        File file = new File(imgPath);
        BufferedImage src = ImageIO.read(file);
        Image img = Toolkit.getDefaultToolkit()
                .createImage(new FilteredImageSource(src.getSource(), cropFilter));
        BufferedImage output = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = output.getGraphics();
        g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
        g.dispose();
        dir = "img_resized\\cut_image.jpg";
        //            String dir = "trainset\\57-tx\\57-"+(count++)+".jpg";
        File dest = new File(dir);
        ImageIO.write(output, "JPEG", dest);
    }
    return dir;
}

From source file:M.java

public static String resize(String imgPath, String andrewId, int trainImageCount) throws Exception {
    System.out.println("\nRunning DetectFaceDemo");
    String xmlfilePath = FaceDetector.class.getResource("haarcascade_frontalface_alt.xml").getPath()
            .substring(1);//  w w  w  .  j  a  v a  2 s.c om
    System.out.println(xmlfilePath);//test
    CascadeClassifier faceDetector = new CascadeClassifier(xmlfilePath);
    //        String imgPath=FaceDetector.class.getResource("cam_img/test.jpg").getPath().substring(1);
    Mat image = Highgui.imread(imgPath);
    System.out.println(imgPath);
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);
    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
    int count = 1;
    String dir = "";
    for (Rect rect : faceDetections.toArray()) {
        ImageFilter cropFilter = new CropImageFilter(rect.x, rect.y, rect.width, rect.height);
        BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
        //            File file = new File("build\\classes\\cam_img\\test.jpg");
        File file = new File(imgPath);
        BufferedImage src = ImageIO.read(file);
        Image img = Toolkit.getDefaultToolkit()
                .createImage(new FilteredImageSource(src.getSource(), cropFilter));
        BufferedImage output = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = output.getGraphics();
        g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
        g.dispose();
        int st_no = findLabel("photodb_resized\\", andrewId);
        dir = "photodb_resized\\" + st_no + "-" + andrewId + trainImageCount + ".jpg";
        //            String dir = "trainset\\57-tx\\57-"+(count++)+".jpg";
        File dest = new File(dir);
        ImageIO.write(output, "JPEG", dest);
    }
    return dir;
}

From source file:attendance_system_adder.cv.image.java

public Mat getFaceDetec(Mat image) {
    Mat face = null;//from  w w w. jav a2  s  . c  o m

    System.out.println("\nRunning DetectFaceDemo");

    CascadeClassifier faceDetector = new CascadeClassifier(".\\resource\\haarcascade_frontalface_default.xml");

    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    //    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
    //    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Imgproc.rectangle(image, new Point(rect.x, rect.y),
                new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(255, 0, 0));
        face = new Mat(image, rect);
    }
    //    // Save the visualized detection.
    //    String filename = "faceDetection.png";
    //    System.out.println(String.format("Writing %s", filename));
    //    imwrite(filename, image);
    //FaceRecognizer fr;//= new LBPHFaceRecognizer();
    return face;
}

From source file:attendance_system_adder.cv.image.java

public Mat FaceDetec(Mat image) {
    Mat face = null;/*from   ww  w  . j  a  v a2  s  .co  m*/

    System.out.println("\nRunning DetectFaceDemo");

    CascadeClassifier faceDetector = new CascadeClassifier(".\\resource\\haarcascade_frontalface_default.xml");

    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    //    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
    //    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Imgproc.rectangle(image, new Point(rect.x, rect.y),
                new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(255, 0, 0));

    }
    return image;
}

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();/*from  w  ww  . jav  a  2  s . com*/

    // 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:by.zuyeu.deyestracker.core.detection.detector.BaseDetector.java

protected Rect[] detectWithClassifier(final Mat inputframe, final CascadeClassifier classifier) {
    LOG.debug("detectWithClassifier - start;");

    final Mat mRgba = new Mat();
    final Mat mGrey = new Mat();
    final MatOfRect detectedObjects = new MatOfRect();
    inputframe.copyTo(mRgba);//w  ww  . jav  a2  s .  com
    inputframe.copyTo(mGrey);
    Imgproc.cvtColor(mRgba, mGrey, Imgproc.COLOR_BGR2GRAY);
    Imgproc.equalizeHist(mGrey, mGrey);
    classifier.detectMultiScale(mGrey, detectedObjects);

    LOG.debug("detectWithClassifier - end;");
    return detectedObjects.toArray();
}

From source file:car_counter.counting.opencv.OpencvCarCounter.java

License:Apache License

@Override
public Collection<DetectedVehicle> processVideo(Path video, DateTime startDateTime) {
    CascadeClassifier carDetector = new CascadeClassifier("/Users/luke/working/car-counter/data/cars3.xml");

    VideoCapture videoCapture = new VideoCapture();
    videoCapture.open("/Users/luke/working/car-counter/data/video1.m4v");

    int index = 0;

    while (true) {
        if (!videoCapture.read(image)) {
            break;
        }//from   w w  w  .j  a v  a 2s.  c  o m

        System.out.print(".");

        //processFrame();

        MatOfRect carDetections = new MatOfRect();
        carDetector.detectMultiScale(image, carDetections);

        System.out.println(String.format("Detected %s cars", carDetections.toArray().length));

        // Draw a bounding box around each hit
        for (Rect rect : carDetections.toArray()) {
            Core.rectangle(image, new Point(rect.x, rect.y),
                    new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
        }

        String file = String.format("/Users/luke/working/car-counter/data/out/out-%03d.jpg", index++);
        org.opencv.highgui.Highgui.imwrite(file, image);
    }

    return null;
}

From source file:ch.zhaw.facerecognitionlibrary.Helpers.FaceDetection.java

License:Open Source License

public Eyes getEyes(Mat img) {
    double halfWidth = img.cols() / 2;
    double height = img.rows();
    double[] values = new double[4];
    values[0] = 0;//from ww w. j a  v a2 s .co  m
    values[1] = 0;
    values[2] = halfWidth;
    values[3] = height;
    Rect rightHalf = new Rect(values);
    values[0] = halfWidth;
    Rect leftHalf = new Rect(values);
    MatOfRect rightEyes = new MatOfRect();
    MatOfRect leftEyes = new MatOfRect();

    Mat rightHalfImg = img.submat(rightHalf);
    rightEyeDetector.detectMultiScale(rightHalfImg, rightEyes);
    Mat leftHalfImg = img.submat(leftHalf);
    leftEyeDetector.detectMultiScale(leftHalfImg, leftEyes);

    if (rightEyes.empty() || leftEyes.empty() || rightEyes.toArray().length > 1
            || leftEyes.toArray().length > 1) {
        return null;
    }

    Rect rightEye = rightEyes.toArray()[0];
    Rect leftEye = leftEyes.toArray()[0];

    MatOfFloat rightPoint = new MatOfFloat(rightEye.x + rightEye.width / 2, rightEye.y + rightEye.height / 2);
    MatOfFloat leftPoint = new MatOfFloat(img.cols() / 2 + leftEye.x + leftEye.width / 2,
            leftEye.y + leftEye.height / 2);

    MatOfFloat diff = new MatOfFloat();
    Core.subtract(leftPoint, rightPoint, diff);
    double angle = Core.fastAtan2(diff.toArray()[1], diff.toArray()[0]);
    double dist = Core.norm(leftPoint, rightPoint, Core.NORM_L2);
    Eyes eyes = new Eyes(dist, rightPoint, leftPoint, angle);
    return eyes;
}

From source file:classes.FaceDetector.java

public static String detectFace(String filePath) {

    //        String dirName = "C:/Users/ggm/Documents/NetBeansProjects/MyWebApplication";
    String dirName = "C:/Users/Gonzalo/Documents/NetBeansProjects/MyWebApplication";
    //        String dirName = "/Users/ggmendez/Development/MyWebApplication";

    System.out.println(dirName);/*from w  w  w . ja v  a2s . co m*/

    String frontalfaceFile = dirName + "/data/lbpcascades/lbpcascade_frontalface.xml";

    System.out.println(frontalfaceFile);

    CascadeClassifier faceDetector = new CascadeClassifier(frontalfaceFile);

    Mat image = Highgui.imread(filePath);

    System.out.println(image);

    // Detect faces in the image 
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
                new Scalar(0, 255, 0));
    }

    // Save the visualized detection.            
    Date date = new Date();
    Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
    String filename = dirName + "/imgs/out_" + formatter.format(date) + ".png";

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

    Gson gson = new Gson();
    String jsonResponse = gson.toJson(faceDetections.toArray());
    jsonResponse = jsonResponse.replaceAll("x", "left").replaceAll("y", "top");

    return jsonResponse;

}