How to crop a single desired face out of multiple detected faces in java.

asked 2018-05-30 00:28:21 -0600

nikshita gravatar image

here is my code which detects and crops the image: import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier;

public class FaceDetections {

public static void main(String[] args)
{

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);


    CascadeClassifier faceDetector = new CascadeClassifier();

faceDetector.load("C:\myproject\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml"); System.out.println ( "Working" ); // Input image Mat image = Imgcodecs.imread("D:\input4.jpg");

    // Detecting faces
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    // Creating a rectangular box showing faces detected
    Rect rectCrop=null;
    for (Rect rect : faceDetections.toArray())
    {
        Imgproc.rectangle(image, new Point(rect.x, rect.y),
         new Point(rect.x + rect.width, rect.y + rect.height),
                                       new Scalar(0, 255, 0));
        rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
    }

    // Saving the output image
    String filename = "Ouput4.jpg";
    Imgcodecs.imwrite("D:\\"+filename, image);

    Mat markedImage = new Mat(image,rectCrop);
    Imgcodecs.imwrite("D:\\cropimage_914.jpg",markedImage );
}

}

edit retag flag offensive close merge delete

Comments

that's the same broken code from your last question.

berak gravatar imageberak ( 2018-05-30 02:04:39 -0600 )edit

Yes this is the entire code but it crops only one detected face not the other one or the desired one . i mean what if we want another face to be cropped in the same input image. It definitely detects all three images but returns cropped image of only one face.

nikshita gravatar imagenikshita ( 2018-05-30 05:35:55 -0600 )edit

sure, because you overwrite rectCrop each time, you only get the last

berak gravatar imageberak ( 2018-05-30 05:48:51 -0600 )edit