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);
    }
}
相关推荐
右恩7 分钟前
centos中anconda的一些操作
python
Stark、7 分钟前
使用C++在Qt框架下调用DeepSeek的API接口实现自己的简易桌面小助手
开发语言·qt·deepseek
宇宙无敌花心大萝卜18 分钟前
使用BAT批处理加PYTHON进行WORD批量文字删除
python·word·bat·批处理
Hanson Huang33 分钟前
23种设计模式-工厂方法(Factory Method)设计模式
java·设计模式·工厂方法模式
web_1553427465640 分钟前
【MyBatisPlus】MyBatisPlus介绍与使用
java
moxiaoran57531 小时前
python学习笔记--实现简单的爬虫(二)
python
小样vvv1 小时前
Java 中的多线程:核心概念与应用场景
java·开发语言
Awesome Baron1 小时前
LeetCode hot 100 每日一题(13)——73. 矩阵置零
java·算法·leetcode·职场和发展
zybishe1 小时前
免费送源码:Java+springboot+MySQL 房屋租赁系统小程序的设计与实现 计算机毕业设计原创定制
android·java·spring boot·mysql·docker·zookeeper·小程序
码熔burning1 小时前
MyBatis-Plus 自动填充:优雅实现创建/更新时间自动更新!
java·mybatis·springboot·mybatis-plus