Search code examples
javaimageopencvface-detectioncascade-classifier

How to setting cropping size in CascadeCalssifier with Java


public BufferedImage detectAndDisplay(BufferedImage img, CascadeClassifier faceCascade) {
    Mat frameGray = new Mat();
    BufferedImage imgout = null;

    Mat image = ImagePreProcessing.bufferedImageToMat(img);

    // -- Detect faces
    MatOfRect faces = new MatOfRect();
    faceCascade.detectMultiScale(image, faces);

    List<Rect> listOfFaces = faces.toList();
    for (Rect face : listOfFaces) {
        Point center = new Point(face.x + face.width / 2, face.y + face.height / 2);
        Imgproc.ellipse(image, center, new Size(face.width / 2, face.height / 2), 0, 0, 360,
                new Scalar(255, 0, 255), 3);

        Mat faceROI = image.submat(face);
        imgout = ImagePreProcessing.Mat2BufferedImage(faceROI);
        System.out.println("OpenCV: " +center);

    }
    return imgout;
}

that code I have..but I don't know where the code for setting crop output image. I want to have the picture like original version with circle template..NOT to be crop Can give me suggestion, please:)

input: input

output: output


Solution

  • In your code, you returned a cropped image of the original image, so if you want the original image, draw the circle and convert it to the BufferedImage and return.

    for (Rect face : listOfFaces) {
            Point center = new Point(face.x + face.width / 2, face.y + face.height / 2);
            Imgproc.ellipse(image, center, new Size(face.width / 2, face.height / 2), 0, 0, 360,
                    new Scalar(255, 0, 255), 3);
    
            // dot not crop!!!
            /*Mat faceROI = image.submat(face);
            imgout = ImagePreProcessing.Mat2BufferedImage(faceROI);*/
    
            System.out.println("OpenCV: " +center);
            imgout = ImagePreProcessing.Mat2BufferedImage(image);
    
        }