php-opencv/php-opencv-examples

Need to crop image to detected face and save to file

jmashore opened this issue · 2 comments

Hello -

This is NOT an issue but a question. While I'm a experienced PHP programmer OpenCV is still a relatively new concept for me. I have successfully compiled the latest version of OpenCV and am currently using this extension in my environment. Going through the examples I've been able to derive a number of answers but I still keep running into a common roadblock.

Once I identify a face, calculate the new beginning and ending x,y coordinates I cannot seem to figure out how to crop that out of the Mat. I apologize of this seems like a obvious answer but it's just not coming to me.

Assuming my code starts like this ... what do I need to do to A) crop around the face, B) if not png convert to png and C) write to disk. I can do all these tasks in PHP but I feel keeping as much of this code native to opencv is important.

$faceClassifier = new CascadeClassifier();
$faceClassifier->load('../models/haarcascades/haarcascade_frontalface_default.xml');

$src = imread($scandir . "/" . $fileName);
$gray = cvtColor($src, COLOR_BGR2GRAY);

$faces = null;
$faceClassifier->detectMultiScale($gray, $faces);

//var_export($eyes);

if ($faces) {
    $scalar = new Scalar(0, 0, 255); //red

    foreach ($faces as $face) {
        $x = $face->x;
        $y = $face->y;
        $w = $face->width;
        $h = $face->height;

        $r = max($w, $h) / 2;
        $centerx = $x + $w / 2;
        $centery = $y + $h / 2;
        $nx = (int)($centerx - $r);
        $ny = (int)($centery - $r);
        $nr = (int)($r * 2);
    }

}

Any help would be greatly appreciated. In the best cases I would like to extract the cropped image from the $gray image but if it's a lot of trouble I can live with simply cropping it out of $src.
TIA

Hi. If I understoud you right you need something like this:
https://github.com/php-opencv/php-opencv-examples/blob/master/recognize_face_by_lbph.php#L23

$grayFace = $gray->getImageROI($face); // face coordinates to image
cv\imwrite("results/gray_face.jpg", $grayFace); // save to file
$srcFace = $src->getImageROI($face); // face coordinates to image
cv\imwrite("results/src_face.jpg", $srcFace); // save to file

Yes. That appears to be exactly right. I don't know how many times I Iooked at this sample and for some reason, I just didn't see it. thank you for taking the time out to point me in the correct direction.