使用Java+OpenCV实现照片人脸识别Demo

效果展示

原照片
在这里插入图片描述
识别后照片
在这里插入图片描述

实现过程

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 ...");
		// 创建脸部识别器
		// lbpcascade_frontalface.xml 文件在下载的opencv安装目录下可以找到(..\opencv\sources\data\lbpcascades)
		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);
		//faceDetections.toArray().length 识别到脸部的数量
		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)

出现上述错误大概率是文件路径没有指定对,我这里的文件目录结构如下:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@胡海龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值