代碼下載下傳位址 http://download.csdn.net/detail/u013378306/9656546
1.環境搭建:見上一篇部落格
整個項目的結構圖:

2.編寫detectfacedemo.java,代碼如下:
package com.njupt.zhb.test;
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.objdetect.cascadeclassifier;
//
// detects faces in an image, draws boxes around them, and writes the results
// to "facedetection.png".
public class detectfacedemo {
public void run() {
system.out.println("\nrunning detectfacedemo");
system.out.println(getclass().getresource("lbpcascade_frontalface.xml").getpath());
// create a face detector from the cascade file in the resources
// directory.
//cascadeclassifier facedetector = new cascadeclassifier(getclass().getresource("lbpcascade_frontalface.xml").getpath());
//mat image = highgui.imread(getclass().getresource("lena.png").getpath());
//注意:源程式的路徑會多列印一個‘/’,是以總是出現如下錯誤
/*
* detected 0 faces writing facedetection.png libpng warning: image
* width is zero in ihdr libpng warning: image height is zero in ihdr
* libpng error: invalid ihdr data
*/
//是以,我們将第一個字元去掉
string xmlfilepath=getclass().getresource("lbpcascade_frontalface.xml").getpath().substring(1);
cascadeclassifier facedetector = new cascadeclassifier(xmlfilepath);
mat image = highgui.imread(getclass().getresource("we.jpg").getpath().substring(1));
// 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.
string filename = "facedetection.png";
system.out.println(string.format("writing %s", filename));
highgui.imwrite(filename, image);
}
}
3.編寫測試類:
public class testmain {
public static void main(string[] args) {
system.out.println("hello, opencv");
// load the native library.
system.loadlibrary("opencv_java246");
new detectfacedemo().run();
//運作結果:
//hello, opencv
//running detectfacedemo
///e:/eclipse_jee/workspace/javaopencv246/bin/com/njupt/zhb/test/lbpcascade_frontalface.xml
//detected 8 faces
//writing facedetection.png
運作結果: