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);
    }
}
相关推荐
赵英英俊4 分钟前
Python day28
python
2501_922895587 分钟前
基于SpringBoot和Leaflet集成在线天气服务的区县当前天气WebGIS实战
java·spring boot·后端
苹果醋38 分钟前
[MySQL] MySQL 版本不支持 ST_Distance_Sphere替代方案和解决方案
java·运维·spring boot·mysql·nginx
天天摸鱼的java工程师20 分钟前
Spring事务什么时候会失效?常见业务场景详解与修复方案
java·后端·面试
F_D_Z22 分钟前
【解决办法】pip install albumentations安装下载遇19kB/s超级慢细水管
linux·运维·python·pip
mortimer30 分钟前
PyInstaller打包踩坑记:从静默崩溃到柳暗花明
人工智能·python·github
打野二师兄1 小时前
Spring Boot 自动配置:从 2.x 到 3.x 的进化之路
java·spring boot·后端
2zcode1 小时前
基于Matlab图像处理的静态雨滴去除与质量评估系统
开发语言·图像处理·matlab
胎粉仔1 小时前
Objective-c 初阶——异常处理(try-catch)
开发语言·ios·objective-c
Monkey-旭1 小时前
Android JNI 语法全解析:从基础到实战
android·java·c++·c·jni·native