Java OpenCV應用範例
Java OpenCV應用範例
簡介 |
使用Java OpenCV實現人臉辨識 |
作者 |
羅伊辰 |
前言:
目的:
開始前準備:
2. Eclipse
3. 至官網下載安裝檔:opencv-3.1.0.exe
搭建環境:
1. 執行opencv-3.1.0.exe進行安裝作業,將工具解壓縮在D:\目錄

2. 解壓縮後的目錄如下

3. 下載opencv-310.jar 檔案,並放置在以下路徑,並在本地端java project匯入

1 public class DetectFaceTest { 2 3 static{ 4 // 載入opencv的庫 5 String opencvDllName = 6 :\\test_workspace\\test\\opencv\\build\\java\\x64\\"+Core.NATIVE_LIBRA7 _NAME + ".dll"; 8 System.load(opencvDllName); 9 } 10 11 12 /** 13 * opencv人臉辨識 14 * @param imagePath 15 * @param outFile 16 * @throws Exception 17 */ 18 public static void detectFace(String imagePath, String outFile) throws 19 Exception 20 { 21 22 System.out.println("Running DetectFace ... "); 23 // 從設定檔lbpcascade_frontalface.xml中創建一個人臉識別器,該檔位於 24 opencv安裝目錄中 25 CascadeClassifier faceDetector = new 26 26eClassifier("D:\\opencv\\sources\\data\\haarcascades\\haarcascade_fron27lface_alt.xml"); 28 29etector.load("D:\\opencv\\sources\\data\\haarcascades\\haarcascade_fro30lface_default.xml"); 31 32 Mat image = Imgcodecs.imread(imagePath); 33 34 // 在圖片中檢測人臉 35 MatOfRect faceDetections = new MatOfRect(); 36 37 faceDetector.detectMultiScale(image, faceDetections); 38 39 System.out.println(String.format("Detected %s faces", 40ceDetections.toArray().length)); 41 42 Rect[] rects = faceDetections.toArray(); 43 if(rects != null && rects.length > 1){ 44 throw new RuntimeException("超過一個臉"); 45 } 46 // 在每一個識別出來的人臉周圍畫出一個方框 47 Rect rect = rects[0]; 48 49 Imgproc.rectangle(image, new Point(rect.x-2, rect.y-2), 50 new Point(rect.x + rect.width, rect.y + 51ct.height), 52 new Scalar(0, 255, 0)); 53 54 Imgcodecs.imwrite(outFile, image); 55 System.out.println(String.format("人臉識別成功,人臉圖片檔為: %s", 56tFile)); 57 58 59 } 60 61 62 public static void main(String[] args) throws Exception { 63 //人臉識別 64 detectFace("D:\\person2.jpg", "D:\\personFaceDetect2.png"); 65 66 } 67 } |
5. 程式內容說明 (行3 ~行89):
->載入OpenCV函式庫
static{
// 載入opencv的庫
String opencvDllName = "D:\\test_workspace\\test\\opencv\\build\\java\\x64\\"+Core.NATIVE_LIBRARY_NAME + ".dll";
System.load(opencvDllName);
}
6. 程式內容說明 (行23 ~行28):
->從設定檔lbpcascade_frontalface.xml中創建一個人臉識別器,該檔位於安裝目錄中
CascadeClassifier faceDetector = new CascadeClassifier("D:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml");
faceDetector.load("D:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml");
7. 程式內容說明 (行49 ~行52):
->在辨識出的人臉周圍畫出方框
Imgproc.rectangle(image, new Point(rect.x-2, rect.y-2),
new Point(rect.x + rect.width, rect.y + rect.height),
new Scalar(0, 255, 0));
Imgcodecs.imwrite(outFile, image);
8. 程式內容說明 (行64):
->呼叫人臉辨識FUNCTION,傳入參數為輸入圖檔及輸出圖檔
detectFace("D:\\person2.jpg", "D:\\personFaceDetect2.png");
運行結果:

