用於使用 Java 檢測面部的級聯分類器
Java 的
碼
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.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import org.opencv.objdetect.CascadeClassifier;
public class FaceDetector{
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//Create object
CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource("haarcascade_frontalface_default.xml").getPath());
//Read image
Mat image = Highgui.imread("sourceimage.jpg");
/*
//Or read from webcam
* Mat image=new Mat();
*VideoCapture videoCapture=new VideoCapture(0);
*videoCapture.read(image);
*/
MatOfRect faceDetections = new MatOfRect();
//Result list
faceDetector.detectMultiScale(image, faceDetections);
for (Rect rect : faceDetections.toArray()) {
//Draw rectangle on result
Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
new Scalar(0, 255, 0));
}
//write result
Highgui.imwrite("result.png", image);
System.out.println("Succesfull");
}
}
結果