代码之家  ›  专栏  ›  技术社区  ›  Night Programmer

如何使用OpenCV和Java保存面子和识别?

  •  1
  • Night Programmer  · 技术社区  · 7 年前

    我对OpenCV完全陌生。我可以从网络摄像头中检测到这张脸。我有点困惑如何保存检测到的脸,如果那个人再次出现在摄像机前,如何保存和识别。

    检测代码

    private void detectAndDisplay(Mat frame)
    {
        MatOfRect faces = new MatOfRect();
        Mat grayFrame = new Mat();
    
        // convert the frame in gray scale
        Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);
        // equalize the frame histogram to improve the result
        Imgproc.equalizeHist(grayFrame, grayFrame);
    
        // compute minimum face size (20% of the frame height, in our case)
        if (this.absoluteFaceSize == 0)
        {
            int height = grayFrame.rows();
            if (Math.round(height * 0.2f) > 0)
            {
                this.absoluteFaceSize = Math.round(height * 0.2f);
            }
        }
    
        // detect faces
        this.faceCascade.detectMultiScale(grayFrame, faces, 1.1, 2, 0 | Objdetect.CASCADE_SCALE_IMAGE,
                new Size(this.absoluteFaceSize, this.absoluteFaceSize), new Size());
    
        // each rectangle in faces is a face: draw them!
        Rect[] facesArray = faces.toArray();
        for (int i = 0; i < facesArray.length; i++)
            Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0), 3);
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Renee    7 年前

    如果您想保存检测到的人脸图像,也许可以尝试以下操作

    for (int i = 0; i < facesArray.length; i++)
    {   
         Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0), 3);
         Rect rect(facesArray[i].tl().x, facesArray[i].tl().y, facesArray[i].br().x - facesArray[i].tl().x, facesArray[i].br().y - facesArray[i].tl().y);
         Mat cropFace = frame(rect);
         imwrite("./face"+i+".jpg", cropFace);
    }
    
        2
  •  0
  •   Night Programmer    7 年前

    我有办法了

          for (Rect rect : facesArray) {
                Imgproc.rectangle(frame, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
                        new Scalar(0, 255, 0)); // frame is Mat
                rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
    
                Mat image_roi = new Mat(frame,rectCrop);
                 Imgcodecs.imwrite("./face"+ i +".jpg",image_roi);
                 i++;
            }
    

    现在,我可以裁剪多个面