该类的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:\images\faces.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:\images\face_detection.jpg", src); system.out.println("image processed"); }}
input
outputno of faces detected: 3
以上就是如何使用java opencv库在图像中检测人脸?的详细内容。
