如何使用Java OpenCV库在图像中检测人脸?

CascadeClassifier类用于加载分类器文件并在图像中检测所需的对象。

该类的detectMultiScale()方法可以检测不同大小的多个对象。该方法接受 −

  • 一个Mat类对象,用于保存输入图像。

  • 一个MatOfRect类对象,用于存储检测到的人脸。

要获取图像中的人脸数量 −

  • 使用CascadeClassifier类加载lbpcascade_frontalface.xml文件。

  • 调用detectMultiScale()方法。

  • 将MatOfRect对象转换为数组。

  • 数组的长度就是图像中的人脸数量。

示例

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 FaceDetection { public static void main (String[] args) { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the Image from the file String file ="D:Imagesfaces.jpg"; Mat src = Imgcodecs.imread(file); //Instantiating the CascadeClassifier String xmlFile = "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, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 0, 255), 3 ); } //Writing the image Imgcodecs.imwrite("D:Imagesface_Detection.jpg", src); System.out.println("Image Processed"); } }登录后复制