作者:waiwaiwai | 来源:互联网 | 2023-09-18 13:07
效果展示 原照片 识别后照片
实现过程 Demo开发编译环境 IDE:Eclipse JDK:1.8 OpenCV:2.4.6 Eclipse配置OpenCV环境 查看我的另外一篇博文:《Java如何引入OpenCV包》。
人脸识别Demo代码 package main ; 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. imgcodecs. Imgcodecs ; import org. opencv. imgproc. Imgproc ; import org. opencv. objdetect. CascadeClassifier ; public class OpenCVTest { public static void main ( String [ ] args) { System . out. println ( "face detector application." ) ; System . loadLibrary ( Core . NATIVE_LIBRARY_NAME) ; new DetectFaceDemo ( ) . run ( ) ; } } class DetectFaceDemo { public void run ( ) { System . out. println ( "detectFace application is running ..." ) ; CascadeClassifier faceDetector = new CascadeClassifier ( System . getProperty ( "user.dir" ) + "/resources/lbpcascade_frontalface.xml" ) ; Mat imread = Imgcodecs . imread ( System . getProperty ( "user.dir" ) + "/resources/3.jpg" ) ; MatOfRect faceDetections = new MatOfRect ( ) ; faceDetector. detectMultiScale ( imread, faceDetections) ; System . out. println ( String . format ( "Detected %s face" , faceDetections. toArray ( ) . length) ) ; for ( Rect rect : faceDetections. toArray ( ) ) { Imgproc . rectangle ( imread, new Point ( rect. x, rect. y) , new Point ( rect. x + rect. width, rect. y + rect. height) , new Scalar ( 0 , 255 , 0 ) ) ; } String fileName = "faceDetection.png" ; System . out. println ( String . format ( "Writing %s" , fileName) ) ; Imgcodecs . imwrite ( fileName, imread) ; } }
注意事项 上面代码中需要注意的是lbpcascade_frontalface.xml
文件,它的位置在opencv安装目录里,例如我将opencv解压到C盘下的env目录,那么该文件可在下面的路径中找到
C:\ env\ opencv\ opencv\ sources\ data\ lbpcascades
上面的文件路径问题也需要注意,如果路径没有指定到对应文件可能会报如下的错误:
Exception in thread "main" CvException [ org.opencv.core.CvException: cv::Exception: OpenCV( 4.5 .4) C:\ build\ master_winpack-bindings-win64-vc14-static\ opencv\ modules\ objdetect\ src\ cascadedetect.cpp:1689: error: ( -215:Assertion failed) ! empty( ) in function 'cv::CascadeClassifier::detectMultiScale' ] at org.opencv.objdetect.CascadeClassifier.detectMultiScale_5( Native Method) at org.opencv.objdetect.CascadeClassifier.detectMultiScale( CascadeClassifier.java:255) at main.DetectFaceDemo.run( OpenCVTest.java:33) at main.OpenCVTest.main( OpenCVTest.java:18)
出现上述错误大概率是文件路径没有指定对,我这里的文件目录结构如下: