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 FaceDetector {
public static void main(String[] args) {
//加載本地的OpenCV庫,這樣就可以用它來調用Java API。
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
System.out.println("\nRunning FaceDetector");
//創建實例CascadeClassifier,將已加載的分類器的文件名傳遞給它。
CascadeClassifier faceDetector = new CascadeClassifier("haarcascade_frontalface_default.xml");
// System.out.println(FaceDetector.class.getResource("haarcascade_frontalface_default.xml").getPath());
String pathf = "E:\\Application\\opencv\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml";
faceDetector.load(pathf);
//將圖片轉化成Java API能夠接受使用Imgcodecs類的格式,鋪墊在OpenCV C++的n維密集數組類上邊。
Mat image = Imgcodecs.imread("E:\\Application\\Eclipse\\workspace\\202004061323\\src\\lena.png");
// System.out.println(FaceDetector.class.getResource("lena.png").getPath());
MatOfRect faceDetections = new MatOfRect();
//調用分類器上的detectMultiScale方法傳遞給它圖象和MatOfRect對象。這個過程之後,MatOfRect將有面部檢測。
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
// 遍歷所有的臉部檢測並用矩形標記圖像。
for (Rect rect : faceDetections.toArray()) {
Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 255));
}
String filename = "ouput1.png";
System.out.println(String.format("Writing %s", filename));
//將圖像寫入輸出的 .png 文件裏
Imgcodecs.imwrite(filename, image);
}
}
前提條件:
準備好haarcascade_frontalface_default.xml文件和opencv-420.jar