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

红太狼 2023-10-02 11:23 46阅读 0赞
  1. import org.opencv.core.*;
  2. import org.opencv.highgui.HighGui;
  3. import org.opencv.objdetect.CascadeClassifier;
  4. import org.opencv.videoio.VideoCapture;
  5. import static org.opencv.core.CvType.CV_8UC1;
  6. import static org.opencv.core.CvType.CV_8UC3;
  7. import static org.opencv.imgproc.Imgproc.COLOR_BGR2GRAY;
  8. import static org.opencv.imgproc.Imgproc.cvtColor;
  9. import static org.opencv.imgproc.Imgproc.rectangle;
  10. import static org.opencv.videoio.Videoio.CAP_PROP_FPS;
  11. import static org.opencv.videoio.Videoio.CAP_PROP_FRAME_HEIGHT;
  12. import static org.opencv.videoio.Videoio.CAP_PROP_FRAME_WIDTH;
  13. public class FaceDetect {
  14. static {
  15. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  16. }
  17. public static void main(String[] args) {
  18. String xmlFileName = "F:\\opencv\\build\\etc\\lbpcascades\\lbpcascade_frontalface_improved.xml";
  19. CascadeClassifier cascadeClassifier = new CascadeClassifier(xmlFileName);
  20. if (cascadeClassifier.empty()) {
  21. System.out.println("加载xml模型文件失败!");
  22. } else {
  23. VideoCapture capture = new VideoCapture(0);
  24. if (!capture.isOpened()) {
  25. System.out.println("打开相机失败!");
  26. } else {
  27. // 设置相机参数
  28. capture.set(CAP_PROP_FRAME_WIDTH, 640);
  29. capture.set(CAP_PROP_FRAME_HEIGHT, 480);
  30. capture.set(CAP_PROP_FPS, 30);
  31. Mat frame = new Mat(new Size(640, 480), CV_8UC3);
  32. Mat frameGray = new Mat(new Size(640, 480), CV_8UC1);
  33. MatOfRect objectsRect = new MatOfRect();
  34. while (true) {
  35. // 读取图像
  36. if (!capture.read(frame)) {
  37. System.out.println("读取相机数据失败!");
  38. break;
  39. }
  40. // 转为灰度
  41. cvtColor(frame, frameGray, COLOR_BGR2GRAY);
  42. // 人脸检测
  43. cascadeClassifier.detectMultiScale(frameGray, objectsRect);
  44. if (!objectsRect.empty()) {
  45. // 绘制矩形
  46. Rect[] rects = objectsRect.toArray();
  47. for (Rect r : rects) {
  48. rectangle(frame, r.tl(), r.br(), new Scalar(0, 255, 255), 2);
  49. }
  50. System.out.println("检测到人脸个数=" + rects.length);
  51. }
  52. // 显示
  53. HighGui.imshow("facedetect", frame);
  54. if (HighGui.waitKey(33) == 'q') {
  55. break;
  56. }
  57. }
  58. }
  59. }
  60. }
  61. }

发表评论

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

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

相关阅读