คลาส CascadeClassifier ใช้โหลดไฟล์ classifier และตรวจจับวัตถุในภาพ เมธอด detectMultiScale() ตรวจจับวัตถุหลายขนาด รับพารามิเตอร์:
ออบเจ็กต์
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) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread("D:\\Images\\faces.jpg");
// โหลด classifier
CascadeClassifier classifier = new CascadeClassifier("lbpcascade_frontalface.xml");
// ตรวจจับใบหน้า
MatOfRect faces = new MatOfRect();
classifier.detectMultiScale(src, faces);
System.out.println("Detected " + faces.toArray().length + " faces");
// วาดกรอบรอบใบหน้า
for (Rect rect : faces.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);
}
Imgcodecs.imwrite("D:\\Images\\face_detection.jpg", src);
System.out.println("Image Processed");
}
}
ผลลัพธ์
No of faces detected: 3
ภาพจะแสดงกรอบสีแดงรอบใบหน้าที่ตรวจพบ