人脸识别Java代码实现
时间: 2023-08-24 15:10:05 浏览: 98
java 实现人脸识别
4星 · 用户满意度95%
以下是一个简单的人脸识别Java代码实现示例:
```java
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_face.FaceRecognizer;
import org.bytedeco.javacpp.opencv_face.LBPHFaceRecognizer;
import org.bytedeco.javacpp.opencv_imgcodecs;
import org.bytedeco.javacpp.opencv_imgproc;
import org.bytedeco.javacpp.opencv_core.RectVector;
import org.bytedeco.javacpp.opencv_core.Size;
import org.bytedeco.javacpp.opencv_objdetect.CascadeClassifier;
public class FaceRecognition {
public static void main(String[] args) throws IOException {
// 加载OpenCV库
Loader.load(org.bytedeco.javacpp.opencv_core.class);
Loader.load(org.bytedeco.javacpp.opencv_imgproc.class);
Loader.load(org.bytedeco.javacpp.opencv_objdetect.class);
Loader.load(org.bytedeco.javacpp.opencv_face.class);
// 加载人脸识别模型
FaceRecognizer recognizer = LBPHFaceRecognizer.create();
recognizer.read("model.xml");
// 加载人脸检测模型
CascadeClassifier faceDetector = new CascadeClassifier("haarcascade_frontalface_alt.xml");
// 加载待识别的图片
Mat image = opencv_imgcodecs.imread("test.jpg");
Mat grayImage = new Mat();
opencv_imgproc.cvtColor(image, grayImage, opencv_imgproc.COLOR_BGR2GRAY);
opencv_imgproc.equalizeHist(grayImage, grayImage);
// 检测人脸
RectVector faces = new RectVector();
faceDetector.detectMultiScale(grayImage, faces, 1.1, 2, 0, new Size(30, 30), new Size());
// 对每个检测到的人脸进行识别
for (int i = 0; i < faces.size(); i++) {
// 裁剪人脸区域
Mat face = new Mat(grayImage, faces.get(i));
// 调整人脸大小
Mat resizedFace = new Mat();
opencv_imgproc.resize(face, resizedFace, new Size(100, 100));
// 识别人脸
int[] label = new int[1];
double[] confidence = new double[1];
recognizer.predict(resizedFace, label, confidence);
// 输出识别结果
System.out.println("人脸" + (i + 1) + ": 标签=" + label[0] + ", 置信度=" + confidence[0]);
}
// 显示原始图片和标注后的图片
opencv_imgcodecs.imwrite("annotated.jpg", image);
for (int i = 0; i < faces.size(); i++) {
opencv_imgproc.rectangle(image, faces.get(i), new org.bytedeco.javacpp.opencv_core.Scalar(0, 255, 0, 0), 2, 8, 0);
}
ImageIO.write(opencv_imgcodecs.toBufferedImage(image), "jpg", new File("annotated.jpg"));
}
}
```
该示例使用了OpenCV的LBPH人脸识别算法和Haar级联分类器进行人脸检测。首先,需要加载OpenCV库和人脸识别模型。然后,加载待识别的图片并进行灰度化和直方图均衡化处理。接着,使用Haar级联分类器检测人脸,并对每个检测到的人脸进行识别。最后,输出识别结果并在原始图片上标注检测到的人脸。
阅读全文