Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีตรวจจับใบหน้าในภาพด้วย Java OpenCV

คลาส CascadeClassifier ใช้โหลดไฟล์ classifier และตรวจจับวัตถุในภาพ เมธอด detectMultiScale() ตรวจจับวัตถุหลายขนาด รับพารามิเตอร์:

  • ออบเจ็กต์ Mat ภาพอินพุต

  • ออบเจ็กต์ MatOfRect เก็บตำแหน่งใบหน้าที่ตรวจพบ

ขั้นตอนการตรวจจับ

  1. โหลดไฟล์ lbpcascade_frontalface.xml ด้วย CascadeClassifier
  2. เรียก detectMultiScale()
  3. แปลง MatOfRect เป็นอาร์เรย์
  4. ความยาวอาร์เรย์ = จำนวนใบหน้า

ตัวอย่างโค้ด

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

ภาพจะแสดงกรอบสีแดงรอบใบหน้าที่ตรวจพบ