1. Environment setup: see the previous blog
Structure of the entire project:
2. Compile detectfacedemo. Java with the following code:
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 (); // note: the path of the source program will print one more '/', so the following error always appears/** 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 * // Therefore, we remove the first character from 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: 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. Compile the test class:
Package COM. njupt. ZHB. test; 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 () ;}/// running result: // hello, opencv /// running detectfacedemo // E: /eclipse_jee/workspace/javaopencv246/bin/COM/njupt/ZHB/test/lbpcascade_frontalface.xml // detected 8 faces // writing facedetection.png
Running result:
Source code download: http://download.csdn.net/detail/nuptboyzhb/5961985
Not for commercial purposes without permission