java opencv人脸识别_java+opencv+intellij idea实现人脸识别
首先當然是需要安裝opencv了,我用的是opencv2.4.13。下載完之后就可以直接安裝了,安裝過程也很簡單,直接下一步下一步就好,我就不上圖了。
接下來在opencv下找到jar包,比如我直接安裝在c盤,我的jar包在C:\opencv\build\java中。
然后將jar包拷貝到lib目錄中,并且在idea中配置
接著在opencv的路徑下找到lbpcascade_frontalface.xml。比如我的就是C:\opencv\sources\data\lbpcascades。然后將其拷貝到src目錄下。
這樣該有的環境就已經搭建好了,就可以開始寫代碼了。
直接上代碼
public static void main(String[] args) {
// Load the native library.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String url ="G:\\web\\uploadPicture\\src\\main\\resources\\assets\\4.jpg";
new DetectFaceDemo().go(url,"G:\\1.jpg");
}
public void go(String srcFileName,String newPath) {
Mat image = null;
CascadeClassifier faceDetector = null;
String xmlfilePath = DetectFaceDemo.class.getClassLoader().getResource("lbpcascade_frontalface.xml").getPath().substring(1);
try {
faceDetector = new CascadeClassifier(xmlfilePath);
image = Highgui.imread(srcFileName);
}catch (Exception e){
e.printStackTrace();
}
// Detect faces in the image.
// MatOfRect is a special container class for Rect.
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
// Draw a bounding box around each face.
for (Rect rect : faceDetections.toArray()) {
Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
}
// Save the visualized detection.
System.out.println(String.format("Writing %s", newPath));
Highgui.imwrite(newPath, image);
}
這樣你就可以直接運行呢,但是會報錯。
這時你可以打開edit,如圖
修改vm option?-Djava.library.path=C:\opencv\build\java\x64
接著再運行就可以了。
如果要部署到服務器上的話opencv的jar包一定要放在lib下,我之前在lib下新建了個文件夾吧jar包放在里面,一直報classnotfound的異常。
然后在tomcat的vm options中添加路徑即可
但是這樣有個致命的問題,他必須是一個文件路徑,opencv沒有提供對于流處理的封裝,這不符合java的思想,也不滿足項目的需求,尤其是現在許多的圖片都是base64位的流。所以這又需要用stormcv這個jar包了了,再次感謝Apache。
這樣我們就可以把識別的函數改為。
public void run(String imgStr) {
BASE64Decoder decoder = new BASE64Decoder();
Mat image = null;
CascadeClassifier faceDetector = null;
String xmlfilePath = DetectFaceDemo.class.getClassLoader().getResource("lbpcascade_frontalface.xml").getPath().substring(1);
try {
faceDetector = new CascadeClassifier(xmlfilePath);
byte[] b = decoder.decodeBuffer(imgStr); //將base64位流解碼為二進制文件
image = ImageUtils.bytes2Mat(b); //將二進制文件轉化為mat
}catch (Exception e){
e.printStackTrace();
}
// Detect faces in the image.
// MatOfRect is a special container class for Rect.
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
}
好了,大功告成
原文:http://www.cnblogs.com/cgy96/p/6236244.html
總結
以上是生活随笔為你收集整理的java opencv人脸识别_java+opencv+intellij idea实现人脸识别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MailBee.NET Objects发
- 下一篇: [转]一个人脸检测器