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.objdetect** 包中的 **CascadeClassifier** 類用於載入分類器檔案。透過傳遞 **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**。

FaceDetection Input

輸出

執行程式後,您將獲得以下輸出:

Detected 3 faces 
Image Processed

如果您開啟指定路徑,則可以觀察到輸出影像如下:

FaceDetection Output
廣告