OpenCV Java 示例 - 检测图像中的人脸

喜欢ヅ旅行 2023-10-02 11:18 76阅读 0赞

问题描述

如何使用java检测图像中的人脸。

解决方案

以下是使用java检测图像中人脸的程序。

  1. import org.opencv.core.Core;
  2. import org.opencv.core.Mat;
  3. import org.opencv.core.MatOfRect;
  4. import org.opencv.core.Point;
  5. import org.opencv.core.Rect;
  6. import org.opencv.core.Scalar;
  7. import org.opencv.imgcodecs.Imgcodecs;
  8. import org.opencv.imgproc.Imgproc;
  9. import org.opencv.objdetect.CascadeClassifier;
  10. public class DetectingFaceInAnImage {
  11. public static void main (String[] args) {
  12. //Loading the OpenCV core library
  13. System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
  14. //Reading the Image from the file and storing it in to a Matrix object
  15. String file = "F:/face_detection_input1.jpg";
  16. Mat src = Imgcodecs.imread(file);
  17. //Instantiating the CascadeClassifier
  18. String xmlFile = "F:/haarcascade_frontalface_default.xml";
  19. CascadeClassifier classifier = new CascadeClassifier(xmlFile);
  20. //Detecting the face in the snap
  21. MatOfRect faceDetections = new MatOfRect();
  22. classifier.detectMultiScale(src, faceDetections);
  23. System.out.println(String.format("Detected %s faces",
  24. faceDetections.toArray().length));
  25. //Drawing boxes
  26. for (Rect rect : faceDetections.toArray()) {
  27. Imgproc.rectangle(src, //where to draw the box
  28. new Point(rect.x, rect.y), //bottom left
  29. new Point(rect.x + rect.width, rect.y + rect.height), //top right
  30. new Scalar(0, 0, 255),
  31. 3); //RGB color
  32. }
  33. //Writing the image
  34. Imgcodecs.imwrite("F:/face_detection_output1.jpg", src);
  35. System.out.println("Image Processed");
  36. }
  37. }

输入

watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBAYWxsd2F5Mg_size_17_color_FFFFFF_t_70_g_se_x_16

输出

watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBAYWxsd2F5Mg_size_17_color_FFFFFF_t_70_g_se_x_16 1

发表评论

表情:
评论列表 (有 0 条评论,76人围观)

还没有评论,来说两句吧...

相关阅读