Search code examples
androidcameraandroid-cameraface-detection

Take photo when face detected


I have the following code and i want to automatic take only one photo when a face is detected. I have achieve to automatic take photo but it takes many photos without time to process them because it continuously detect the face. How can i make it to search every x minutes to find a face or every x minutes to take photo? Thank you in advance.

FaceDetectionListener faceDetectionListener
= new FaceDetectionListener(){

    @Override
    public void onFaceDetection(Face[] faces, Camera camera) {

        if (faces.length == 0){
            prompt.setText(" No Face Detected! ");
        }else{
            //prompt.setText(String.valueOf(faces.length) + " Face Detected :) ");
              try{
                camera.takePicture(myShutterCallback,myPictureCallback_RAW, myPictureCallback_JPG);

               }
               catch(Exception e){

               }
        }


    }};

Solution

  • FaceDetectionListener faceDetectionListener
    = new FaceDetectionListener(){
    
        private boolean processing = false;
    
        public void setProcessing(boolean processing) {
            this.processing = processing;
        }
    
        @Override
        public void onFaceDetection(Face[] faces, Camera camera) {
            if (processing) return;
    
            if (faces.length == 0){
                prompt.setText(" No Face Detected! ");
            }else{
                //prompt.setText(String.valueOf(faces.length) + " Face Detected :) ");
                  try{
                       camera.takePicture(myShutterCallback,myPictureCallback_RAW, myPictureCallback_JPG);
                       processing = true;
                   }
                   catch(Exception e){
    
                   }
            }
    
    
        }};
    

    Then you can do whatever processing you want in myShutterCallback and call faceDetectionListener.setProcessing(false) to take another picture. This will guarantee that only one photo will be taken at a time.