opencv 人脸识别 java版------2
代码下载地址http://download.csdn.net/detail/u013378306/9656546 1.环境搭建:见上一篇博客 整个项目的结构图: 2.编写DetectFaceDemo.java,代码如下: packagecom.njupt.zhb.test; importorg.opencv.core.Core; importorg.opencv.core.Mat; importorg.opencv.core.MatOfRect; importorg.opencv.core.Point; importorg.opencv.core.Rect; importorg.opencv.core.Scalar; importorg.opencv.highgui.Highgui; importorg.opencv.objdetect.CascadeClassifier; // //Detectsfacesinanimage,drawsboxesaroundthem,andwritestheresults //to"faceDetection.png". // publicclassDetectFaceDemo{ publicvoidrun(){ System.out.println("\nRunningDetectFaceDemo"); System.out.println(getClass().getResource("lbpcascade_frontalface.xml").getPath()); //Createafacedetectorfromthecascadefileintheresources //directory. //CascadeClassifierfaceDetector=newCascadeClassifier(getClass().getResource("lbpcascade_frontalface.xml").getPath()); //Matimage=Highgui.imread(getClass().getResource("lena.png").getPath()); //注意:源程序的路径会多打印一个‘/’,因此总是出现如下错误 /* *Detected0facesWritingfaceDetection.pnglibpngwarning:Image *widthiszeroinIHDRlibpngwarning:ImageheightiszeroinIHDR *libpngerror:InvalidIHDRdata */ //因此,我们将第一个字符去掉 StringxmlfilePath=getClass().getResource("lbpcascade_frontalface.xml").getPath().substring(1); CascadeClassifierfaceDetector=newCascadeClassifier(xmlfilePath); Matimage=Highgui.imread(getClass().getResource("we.jpg").getPath().substring(1)); //Detectfacesintheimage. //MatOfRectisaspecialcontainerclassforRect. MatOfRectfaceDetections=newMatOfRect(); faceDetector.detectMultiScale(image,faceDetections); System.out.println(String.format("Detected%sfaces",faceDetections.toArray().length)); //Drawaboundingboxaroundeachface. for(Rectrect:faceDetections.toArray()){ Core.rectangle(image,newPoint(rect.x,rect.y),newPoint(rect.x+rect.width,rect.y+rect.height),newScalar(0,255,0)); } //Savethevisualizeddetection. Stringfilename="faceDetection.png"; System.out.println(String.format("Writing%s",filename)); Highgui.imwrite(filename,image); } } 3.编写测试类: packagecom.njupt.zhb.test; publicclassTestMain{ publicstaticvoidmain(String[]args){ System.out.println("Hello,OpenCV"); //Loadthenativelibrary. System.loadLibrary("opencv_java246"); newDetectFaceDemo().run(); } } //运行结果: //Hello,OpenCV // //RunningDetectFaceDemo ///E:/eclipse_Jee/workspace/JavaOpenCV246/bin/com/njupt/zhb/test/lbpcascade_frontalface.xml //Detected8faces //WritingfaceDetection.png 运行结果: