天天看点

opencv 人脸识别 java版------2

代码下载地址 http://download.csdn.net/detail/u013378306/9656546

1.环境搭建:见上一篇博客

整个项目的结构图:

opencv 人脸识别 java版------2

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  

运行结果:

opencv 人脸识别 java版------2