Search code examples
pythonopencvcrop

Crop the region inside the rectangular face detection box using the top-left corner and bottom-right corner of rectangle


I want to crop faces which are boxed using cv2.rectangle.

I tried :

faces = face_cascade.detectMultiScale(gray_image, 1.25, 6)

but this code is detecting only 1 face for this image but when I used another code :

boxes = face_recognition.face_locations(rgb,model="hog")

it returned me 3 faces with values top,right,bottom,left but I dont know how to crop an image using these values(top,right,bottom,left). Any help will be appreciated.

I am using:

Python- 2.7

OpenCv- 3.1.0


Solution

  • In the question, boxes have the top, right, bottom, left values of the detected face, so to crop that area with the given top, right, bottom, left values I used PIL.Image.crop():

    Then the code will be like this:

        from PIL import Image
        img = Image.open("path/to/file")       
        crop_pic = img.crop( ( left, top, right, bottom ) )        
        crop_pic.show()