java利用openCV进行人脸识别,采集照片和训练模型(二)

填坑来了,继续上次的java使用openCV,本篇讲下训练模型

首先,训练模型的目的在于完成人脸对比,之前我们已经可以框出人脸了,那么现在要做的就是把框框里边人脸的图片采集并且保存下来,然后通过FaceRecognizer类中的train()方法去训练人脸模型文件,会输出一个Yml文件。这里边是Java封装类直接调用到openCV底层c++的函数

运行CollectData采集人脸的图片到本地,训练模型需要多一点样本,这里采样50张

CollectData.java

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

import face.util.VideoPanel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;

public class CollectData {

  private static int startFrom = 0;

  private static int sample = 0;

//配置保存路径
  public static String path = "F:/face/imagedb";

  public static String id = "";

  static AtomicBoolean start = new AtomicBoolean(false);

  public static long startTime;

  public static void main(String[] args) throws IOException {

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    CascadeClassifier faceCascade = new CascadeClassifier();
    faceCascade.load("F:/face/install/etc/haarcascades/haarcascade_frontalface_alt.xml");
//控制台输入对象名
    System.out.println("Please input person name: ");
    Scanner scanner = new Scanner(System.in);
    id = scanner.next();
    System.out.println("collecting images for : " + id);

    VideoCapture capture = new VideoCapture();
    capture.open(0);
// 新建窗口
    VideoPanel videoPanel = VideoPanel.show("Collect Data", 640, 480);
    Mat img = new Mat();
    try {
      startTime = System.currentTimeMillis();
      while (true) {
        capture.read(img);
        detectAndCollect(img, faceCascade);
        videoPanel.setImageWithMat(img);
      }
    } finally {
      capture.release();
    }

  }

/**
 * 采集人脸并保存到本地的方法
 **/
  public static void detectAndCollect(Mat frame, CascadeClassifier faceCascade) {
    MatOfRect faces = new MatOfRect();
    Mat grayFrame = new Mat();

    Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);

    // 采集人脸
    faceCascade.detectMultiScale(grayFrame, faces);

    Rect[] facesArray = faces.toArray();

// 连续采集50张,并保存
    if (facesArray.length >= 1) {
      if ((sample == 0 && System.currentTimeMillis() - startTime > 10000) || (sample > 0
          && sample < 50 && System.currentTimeMillis() - startTime > 300)) {
        startTime = System.currentTimeMillis();
        sample++;
        System.out.println("image: " + sample);
        Imgcodecs.imwrite(path + "/image." + id + "." + (startFrom + sample) + ".jpg",
            frame.submat(facesArray[0]));
      }
    }

    for (int i = 0; i < facesArray.length; i++) {
      Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0), 2);
    }
  }

}

采集好以后就可以训练模型了,启动Train.java来训练模型

Train.java

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfInt;
import org.opencv.face.FaceRecognizer;
import org.opencv.face.LBPHFaceRecognizer;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class Train {

  public static void main(String[] args) throws IOException {
	  train("F:/face/imagedb",
		        "F:/face/model");
  }

/**
 * 训练模型的方法,传入人脸图片所在的文件夹路径,和模型输出的路径
 * 训练结束后模型文件会在模型输出路径里边
 **/
  public static void train(String imageFolder, String saveFolder)
      throws IOException {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    FaceRecognizer faceRecognizer = LBPHFaceRecognizer.create();
    CascadeClassifier faceCascade = new CascadeClassifier();
// opencv的模型
    faceCascade.load("F:/face/install/etc/haarcascades/haarcascade_frontalface_alt.xml");
// 读取文件于数组中
    File[] files = new File(imageFolder).listFiles();
    Map<String, Integer> nameMapId = new HashMap<String, Integer>(10);
// 图片集合
    List<Mat> images = new ArrayList<Mat>(files.length);
// 名称集合
    List<String> names = new ArrayList<String>(files.length);
    List<Integer> ids = new ArrayList<Integer>(files.length);
    for (int index = 0; index < files.length; index++ ) {
// 解析文件名 获取名称
      File file = files[index];
      String name = file.getName().split("\\.")[1];
      Integer id = nameMapId.get(name);
      if (id == null) {
        id = names.size();
        names.add(name);
        nameMapId.put(name, id);
        faceRecognizer.setLabelInfo(id, name);
      }

      Mat mat = Imgcodecs.imread(file.getCanonicalPath());
      Mat gray = new Mat();
// 图片预处理
      Imgproc.cvtColor(mat, gray, Imgproc.COLOR_BGR2GRAY);
      images.add(gray);
      System.out.println("add total " + images.size());
      ids.add(id);
    }
    int[] idsInt = new int[ids.size()];
    for (int i = 0; i < idsInt.length; i++) {
      idsInt[i] = ids.get(i).intValue();
    }
// 显示标签
    MatOfInt labels = new MatOfInt(idsInt);
// 调用训练方法
    faceRecognizer.train(images, labels);
// 输出持久化模型文件 训练一次后就可以一直调用
    faceRecognizer.save(saveFolder + "/face_model.yml");
  }

}

这个就是训练好的

 

打开的话,差不多是长这样,文件存储了训练后图像的数字化信息,不禁感叹一下openCV还是很强大

 

那今天先唠到这里了,下回有空的话,讲讲人脸对比~

 

相关博客:

java调起本地摄像头,利用openCV进行人脸识别(一)

java利用openCV进行人脸对比(三)

  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 27
    评论
好的,关于人脸识别,我们可以使用Java调用OpenCV库来实现。首先,需要下载安装OpenCV库,并将其添加到Java项目中。 接下来,可以通过以下步骤来进行人脸识别: 1. 加载人脸检测器模型 使用OpenCV提供的CascadeClassifier类,可以加载已经训练好的人脸检测器模型,例如: ``` CascadeClassifier faceDetector = new CascadeClassifier("haarcascade_frontalface_alt.xml"); ``` 2. 加载图像 使用OpenCV提供的imread方法,可以加载需要进行人脸识别的图像,例如: ``` Mat image = Imgcodecs.imread("test.jpg"); ``` 3. 进行人脸检测 使用之前加载的人脸检测器模型,调用detectMultiScale方法,可以检测图像中的人脸,并返回人脸的位置和大小,例如: ``` MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); ``` 4. 绘制人脸框 使用OpenCV提供的rectangle方法,可以在图像上绘制出人脸框,例如: ``` 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)); } ``` 5. 显示图像 使用OpenCV提供的imshow方法,可以显示出处理后的图像,例如: ``` Imgcodecs.imwrite("result.jpg", image); ``` 以上就是利用Java调用OpenCV进行人脸识别的基本步骤。需要注意的是,人脸检测器模型和测试图像的路径需要根据实际情况进行调整。
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值