org.opencv.videoio包的video capture類包含使用系統攝像機捕獲視頻的類和方法。讓我們一步一步地學習怎麼做。
Step 1: Load the OpenCV native library
在使用OpenCV庫編寫Java代碼時,首先需要使用load library()加載OpenCV的本機庫。加載OpenCV本機庫,如下所示。
// Loading the core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Step 2: Instantiate the CascadeClassifier class
包org.opencv.objdetect的cascadescifier類用於加載分類器文件。通過傳遞xml文件lbpcascade_frontalface.xml來實例化這個類,如下所示。
// Instantiating the CascadeClassifier String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml"; CascadeClassifier classifier = new CascadeClassifier(xmlFile);
Step 3: Detect the faces
可以使用名爲cascadescifier的類的方法detectMultiScale()檢測圖像中的面。該方法接受包含輸入圖像的Mat類對象和MatOfRect類對象來存儲檢測到的面。
// Detecting the face in the snap MatOfRect faceDetections = new MatOfRect(); classifier.detectMultiScale(src, faceDetections);
Example
下面的程序演示如何檢測圖像中的人臉。
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 FaceDetectionImage { public static void main (String[] args) { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap23/facedetection_input.jpg"; Mat src = Imgcodecs.imread(file); // Instantiating the CascadeClassifier String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml"; CascadeClassifier classifier = new CascadeClassifier(xmlFile); // Detecting the face in the snap MatOfRect faceDetections = new MatOfRect(); classifier.detectMultiScale(src, faceDetections); System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // Drawing boxes for (Rect rect : faceDetections.toArray()) { Imgproc.rectangle( src, // where to draw the box new Point(rect.x, rect.y), // bottom left new Point(rect.x + rect.width, rect.y + rect.height), // top right new Scalar(0, 0, 255), 3 // RGB colour ); } // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap23/facedetect_output1.jpg", src); System.out.println("Image Processed"); } }
假設下面是上面程序中指定的輸入圖像facedetection_input.jpg。
Output
在執行程序時,您將得到以下輸出&負;
Detected 3 faces Image Processed
如果您打開指定的路徑,您可以按以下方式觀察輸出圖像−