【Java】 OpenCV ~ 基本編 / 顔検出 ~

■ はじめに

https://dk521123.hatenablog.com/entry/2016/06/27/234046

の続き。設定は、上記の関連記事を参照のこと。

■ サンプル

使用する画像
http://www.cs.cmu.edu/~chuck/lennapg/playboy_backups/lena_lg.jpg

 顔検出

OpenCV v3.1系

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class FaceDetector {

  public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    String input = "C:/temp/lena_lg.jpg";
    String output = "C:/temp/result2.jpg";

    CascadeClassifier faceDetector = new CascadeClassifier(
        "C:/work/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");
    Mat image = Imgcodecs.imread(input);

    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

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

    // 見つかった顔を矩形で囲む
    for (Rect rect : faceDetections.toArray()) {
      Imgproc.rectangle(image, rect.tl(), rect.br(), new Scalar(0, 255, 0, 255), 3);
    }

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

    System.out.println("Done!");
  }
}

OpenCV v2.4系

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.objdetect.CascadeClassifier;

public class FaceDetector {

  public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    String input = "C:/temp/lena_lg.jpg";
    String output = "C:/temp/result2.jpg";

    CascadeClassifier faceDetector = new CascadeClassifier(
        "C:/work/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");
    Mat image = Highgui.imread(input);

    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

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

    // 見つかった顔を矩形で囲む
    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));
    }

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

    System.out.println("Done!");
  }
}

 出力結果

Detected 1 faces
Writing C:/temp/result2.jpg
Done!

関連記事

OpenCV ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2016/06/27/234046