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:\\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");
}
} 입력

출력
No of faces detected: 3