Opencv-face-detection-in-picture

提供:Dev Guides
移動先:案内検索

OpenCV-画像内の顔検出

*org.opencv.videoio* パッケージの *VideoCapture* クラスには、システムカメラを使用してビデオをキャプチャするクラスとメソッドが含まれています。 段階的に行って、その方法を学びましょう。

ステップ1:OpenCVネイティブライブラリをロードする

OpenCVライブラリを使用してJavaコードを作成する場合、最初に行う必要があるステップは、* loadLibrary()*を使用してOpenCVのネイティブライブラリをロードすることです。 以下に示すように、OpenCVネイティブライブラリをロードします。

//Loading the core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

ステップ2:CascadeClassifierクラスをインスタンス化する

パッケージ org.opencv.objdetectCascadeClassifier クラスは、分類子ファイルをロードするために使用されます。 以下に示すように、 xml ファイル lbpcascade_frontalface.xml を渡すことにより、このクラスをインスタンス化します。

//Instantiating the CascadeClassifier
String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);

ステップ3:顔を検出する

*CascadeClassifier* という名前のクラスの* detectMultiScale()*メソッドを使用して、画像内の顔を検出できます。 このメソッドは、入力画像を保持する *Mat* クラスのオブジェクトと *MatOfRect* クラスのオブジェクトを受け入れて、検出された顔を保存します。
//Detecting the face in the snap
MatOfRect faceDetections = new MatOfRect();
classifier.detectMultiScale(src, faceDetections);

次のプログラムは、画像内の顔を検出する方法を示しています。

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.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class FaceDetectionImage {
   public static void main (String[] args) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap23/facedetection_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Instantiating the CascadeClassifier
      String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
      CascadeClassifier classifier = new CascadeClassifier(xmlFile);

     //Detecting the face in the snap
      MatOfRect faceDetections = new MatOfRect();
      classifier.detectMultiScale(src, faceDetections);
      System.out.println(String.format("Detected %s faces",
         faceDetections.toArray().length));

     //Drawing boxes
      for (Rect rect : faceDetections.toArray()) {
         Imgproc.rectangle(
            src,                                              //where to draw the box
            new Point(rect.x, rect.y),                           //bottom left
            new Point(rect.x + rect.width, rect.y + rect.height),//top right
            new Scalar(0, 0, 255),
            3                                                    //RGB colour
         );
      }

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap23/facedetect_output1.jpg", src);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 facedetection_input.jpg が次のものであると仮定します。

顔検出入力

出力

プログラムを実行すると、次の出力が得られます-

Detected 3 faces
Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

顔検出出力