JAVA使用opencv实现人脸识别

1.安装opencv, 官网:https://opencv.org/releases/

  1. 把opencv安装路径下的dll文件复制到jdk的bin目录下

3.创建java的maven工程,配置opencv的jar包

复制代码
    <dependencies>
        <dependency>
            <groupId>org.openpnp</groupId>
            <artifactId>opencv</artifactId>
            <version>4.9.0-0</version> <!-- 根据实际版本调整 -->
        </dependency>
    </dependencies>

4.下载官网预训练的人脸检测模型文件(或者下载附件):

复制代码
haarcascade_frontalface_default.xml

官网git地址:

opencv/data/haarcascades at 4.x · opencv/opencv · GitHub

5.编写代码

复制代码
package org.example;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class FaceRead {
    public static void main(String[] args) {
        // 加载OpenCV库
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        // 读取图片
        String imagePath = "D:\\temp\\face\\1.jpg";
        Mat image = Imgcodecs.imread(imagePath);

        if (image.empty()) {
            System.out.println("Could not open or find the image!");
            System.exit(0);
        }

        // 加载预训练的人脸检测模型
        String xmlPath = "D:\\temp\\opencv-4.x\\opencv-4.x\\data\\haarcascades\\haarcascade_frontalface_default.xml";
        CascadeClassifier faceDetector = new CascadeClassifier(xmlPath);

        if (faceDetector.empty()) {
            System.out.println("Could not load the face detector model!");
            System.exit(0);
        }

        // 检测人脸
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);

        // 遍历检测到的人脸
        for (Rect rect : faceDetections.toArray()) {
            // 在人脸周围绘制矩形框
            Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0), 3);
        }

        // 保存结果图片
        String outputPath = "D:\\temp\\face\\output_image.jpg";
        Imgcodecs.imwrite(outputPath, image);

        System.out.println("Face detection complete. Result saved to " + outputPath);
    }
}
相关推荐
gmaajt4 分钟前
mysql多字段搜索如何设计组合索引_mysql索引查询加速
jvm·数据库·python
2301_777599375 分钟前
MySQL如何快速排查慢查询安全隐患_分析slow_query_log进行优化
jvm·数据库·python
ictI CABL6 分钟前
Tomcat 乱码问题彻底解决
java·tomcat
m0_747854527 分钟前
如何检测受保护链接(如 Twitter)的可访问性
jvm·数据库·python
baidu_340998828 分钟前
宝塔面板如何设置网站访问密码_配置Nginx认证保护目录
jvm·数据库·python
敖正炀8 分钟前
DelayQueue 详解
java
2301_7775993712 分钟前
Python闭包是什么_深入理解Python闭包原理与变量作用域
jvm·数据库·python
HHHHH1010HHHHH12 分钟前
mysql事务回滚与存储引擎的关系_mysql回滚机制分析
jvm·数据库·python
用户83562907805116 分钟前
Python 操作 PowerPoint:添加与设置文本框完整教程
后端·python
InfinteJustice28 分钟前
SQL如何处理分组后的空值统计_善用COALESCE与聚合函数
jvm·数据库·python