คลาส CascadeClassifier ของใช้เพื่อโหลดไฟล์ตัวแยกประเภทและตรวจจับวัตถุที่ต้องการในภาพ
DetecMultiScale() ของคลาสนี้ตรวจจับวัตถุหลายชิ้นที่มีขนาดต่างกัน วิธีนี้ยอมรับ -
-
วัตถุของคลาส Mat ถือภาพอินพุต
-
วัตถุของคลาส MatOfRect เพื่อเก็บใบหน้าที่ตรวจพบ
เพื่อให้ได้จำนวนใบหน้าในภาพ −
-
โหลดไฟล์ lbpcascade_frontalface.xml โดยใช้คลาส CascadeClassifier
-
เรียกใช้เมธอด 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