Home | History | Annotate | Download | only in java
      1 import org.opencv.core.Core;
      2 import org.opencv.core.Mat;
      3 import org.opencv.core.MatOfRect;
      4 import org.opencv.core.Point;
      5 import org.opencv.core.Rect;
      6 import org.opencv.core.Scalar;
      7 import org.opencv.imgcodecs.Imgcodecs;
      8 import org.opencv.objdetect.CascadeClassifier;
      9 
     10 /*
     11  * Detects faces in an image, draws boxes around them, and writes the results
     12  * to "faceDetection.png".
     13  */
     14 public class DetectFaceDemo {
     15     public void run() {
     16         System.out.println("\nRunning DetectFaceDemo");
     17 
     18         // Create a face detector from the cascade file in the resources
     19         // directory.
     20         CascadeClassifier faceDetector = new CascadeClassifier(getClass()
     21                 .getResource("/lbpcascade_frontalface.xml").getPath());
     22         Mat image = Imgcodecs.imread(getClass().getResource(
     23                 "/AverageMaleFace.jpg").getPath());
     24 
     25         // Detect faces in the image.
     26         // MatOfRect is a special container class for Rect.
     27         MatOfRect faceDetections = new MatOfRect();
     28         faceDetector.detectMultiScale(image, faceDetections);
     29 
     30         System.out.println(String.format("Detected %s faces",
     31                 faceDetections.toArray().length));
     32 
     33         // Draw a bounding box around each face.
     34         for (Rect rect : faceDetections.toArray()) {
     35             Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x
     36                     + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
     37         }
     38 
     39         // Save the visualized detection.
     40         String filename = "faceDetection.png";
     41         System.out.println(String.format("Writing %s", filename));
     42         Imgcodecs.imwrite(filename, image);
     43     }
     44 }
     45