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);
    }
}
相关推荐
daidaidaiyu4 小时前
一文学习 工作流开发 BPMN、 Flowable
java
ZTLJQ4 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
2401_891482174 小时前
多平台UI框架C++开发
开发语言·c++·算法
H5css�海秀4 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
SuniaWang5 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
sheji34165 小时前
【开题答辩全过程】以 基于springboot的扶贫系统为例,包含答辩的问题和答案
java·spring boot·后端
阿贵---5 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
88号技师5 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751285 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神5 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先