轉載ide
正對着攝像頭效果能夠,可是頭歪着就識別不到了ui
OpenCV-4.net
package com.pingpang.ImageTest; 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.highgui.HighGui; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; import org.opencv.videoio.VideoCapture; public class TestFace { static { // 在使用OpenCV前必須加載Core.NATIVE_LIBRARY_NAME類,不然會報錯 System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } public static void main(String[] args) { videoFace(); } /** * OpenCV-4.0.0 實時人臉識別 * * @return: void * @date: 2019年5月7日12:16:55 */ public static void videoFace() { VideoCapture capture = new VideoCapture(0); Mat image = new Mat(); int index = 0; if (capture.isOpened()) { while (true) { capture.read(image); HighGui.imshow("實時人臉識別", getFace(image)); index = HighGui.waitKey(1); if (index == 27) { break; } } } return; } /** * OpenCV-4.0.0 人臉識別 * * @date: 2019年5月7日12:16:55 * @param image 待處理Mat圖片(視頻中的某一幀) * @return 處理後的圖片 * */ public static Mat getFace(Mat image) { // 1 讀取OpenCV自帶的人臉識別特徵XML文件 CascadeClassifier facebook = new CascadeClassifier( "E:\\opencv\\opencv\\sources\\data\\haarcascades_cuda\\haarcascade_frontalface_alt.xml"); // 2 特徵匹配類 MatOfRect face = new MatOfRect(); // 3 特徵匹配 facebook.detectMultiScale(image, face); Rect[] rects = face.toArray(); System.out.println("匹配到 " + rects.length + " 我的臉"); // 4 爲每張識別到的人臉畫一個圈 for (int i = 0; i < rects.length; i++) { Imgproc.rectangle(image, new Point(rects[i].x, rects[i].y), new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height), new Scalar(0, 255, 0)); Imgproc.putText(image, "Human", new Point(rects[i].x, rects[i].y), Imgproc.FONT_HERSHEY_SCRIPT_SIMPLEX, 1.0, new Scalar(0, 255, 0), 1, Imgproc.LINE_AA, false); // Mat dst=image.clone(); // Imgproc.resize(image, image, new Size(300,300)); } return image; } }