OpenCV - 使用摄像头进行人脸检测

以下程序演示了如何使用系统摄像头检测人脸并使用 JavaFX 窗口显示它。

示例

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;

import java.io.FileNotFoundException;
import java.io.IOException;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

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;
import org.opencv.videoio.VideoCapture;

public class faceDetectionJavaFXX extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws FileNotFoundException, IOException {
        // 从相机捕获快照
        faceDetectionJavaFXX obj = new faceDetectionJavaFXX();
        WritableImage writableImage = obj.capureFrame();
        
        // 保存图像
        obj.saveImage();
        
        // 设置图像视图
        ImageView imageView = new ImageView(writableImage);
        
        // 设置图像视图的适合高度和宽度
        imageView.setFitHeight(400);
        imageView.setFitWidth(600);
        
        // 设置图像视图的保留比例
        imageView.setPreserveRatio(true);
        
        // 创建 Group 对象
        Group root = new Group(imageView);
        
        // 创建场景对象
        Scene scene = new Scene(root, 600, 400);
        
        // 设置舞台标题
        stage.setTitle("Capturing an image");
        
        // 将场景添加到舞台
        stage.setScene(scene);
        
        // 显示舞台内容
        stage.show();
   }
   public WritableImage capureFrame() {
      WritableImage writableImage = null;

      // 加载 OpenCV 核心库
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      // 实例化 VideoCapture 类(摄像头:: 0)
      VideoCapture capture = new VideoCapture(0);

      // 从摄像头读取下一个视频帧
      Mat matrix = new Mat();
      capture.read(matrix);

      // 如果相机已打开
      if(!capture.isOpened()) {
         System.out.println("camera not detected");
      } else
         System.out.println("Camera detected ");
           
      // 如果有下一个视频帧
      if (capture.read(matrix)) {
         /////// Detecting the face in the snap /////
         String file = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
         CascadeClassifier classifier = new CascadeClassifier(file);

         MatOfRect faceDetections = new MatOfRect();
         classifier.detectMultiScale(matrix, faceDetections);
         System.out.println(String.format("Detected %s faces",
            faceDetections.toArray().length));

         // Drawing boxes
         for (Rect rect : faceDetections.toArray()) {
            Imgproc.rectangle(
               matrix,                                   //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)                                 //RGB colour
            );
         }
         // 从矩阵创建 BuffredImage
         BufferedImage image = new BufferedImage(matrix.width(), matrix.height(),
            BufferedImage.TYPE_3BYTE_BGR);
         
         WritableRaster raster = image.getRaster();
         DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
         byte[] data = dataBuffer.getData();
         matrix.get(0, 0, data);

         this.matrix = matrix;
           
         // 创建可写图像
         writableImage = SwingFXUtils.toFXImage(image, null);
      }
      return writableImage;
   }
   public void saveImage() {
      // 保存图像
      String file = "E:/OpenCV/chap23/facedetected.jpg";

      // 实例化 imagecodecs 类
      Imgcodecs imageCodecs = new Imgcodecs();

      // 再次保存
      imageCodecs.imwrite(file, matrix);
   }
   public static void main(String args[]) {
      launch(args);
   }
}

输出

执行程序后,您将获得以下输出。

使用相机进行人脸检测

如果打开指定路径,您可以看到保存为 jpg 图像的相同快照。