答:
首先检测人脸需要一个图像输入,一个分类器去识别人脸区域,一个输出来标注出人脸,所以 detectface 的思路就很清楚了。
// Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
// 输入图像
String file ="E:/OpenCV/chap23/facedetection_input.jpg";
Mat src = Imgcodecs.imread(file);
// 选择分类器,例如选取 lbp 特征来检测人脸
String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);
// 检测出的人脸区域
MatOfRect faceDetections = new MatOfRect();
classifier.detectMultiScale(src, faceDetections);
// 输出检测到几个人脸
System.out.println(String.format("Detected %s faces",
faceDetections.toArray().length));
// 画出人脸区域
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
);
}
// 输出图像
Imgcodecs.imwrite("E:/OpenCV/chap23/facedetect_output1.jpg", src);