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);
    }
}
相关推荐
Haoea!6 分钟前
Flink03-学习-套接字分词流自动写入工具
开发语言·学习
YYXZZ。。12 分钟前
PyTorch——线性层及其他层介绍(6)
pytorch·python·深度学习
哆啦A梦的口袋呀17 分钟前
基于Python学习《Head First设计模式》第三章 装饰者模式
python·学习·设计模式
哆啦A梦的口袋呀18 分钟前
基于Python学习《Head First设计模式》第五章 单件模式
python·学习·设计模式
天天摸鱼的java工程师18 分钟前
CTO新项目直接上MySQL 8.0,老系统仍是5.7
java·后端·mysql
bxlj_jcj20 分钟前
解锁Java多级缓存:性能飞升的秘密武器
java·缓存·面试·架构
未来并未来22 分钟前
Redis 缓存问题及其解决方案
java·redis·缓存
love530love25 分钟前
【笔记】Windows 下载并安装 ChromeDriver
人工智能·windows·笔记·python·深度学习
@Turbo@38 分钟前
【QT】在Qt6的`QTextEdit`中,同一行更新内容
开发语言·qt
showmeyourcode0.o41 分钟前
QT常用控件(1)
开发语言·c++·qt