Cropping with Python and OpenCV to get passport ratio photos

I got the following python code that uses OpenCV to take a given picture and then look for a face and crop that face and save it with the word “Cropped” appended to the file name. Although it’s working great, there’s two things I cannot seem to figure out how to do.

  1. It seems to be cropping very close to the face edges, I’d like to set an offset to convert it so that it fetches a passport like photo from the crop
  2. It seems to also add a red border.

Can anyone kindly advise how I can possibly solve these two issues?

Thanks

import cv2 

img = cv2.imread('testImage.jpg') 
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') 
faces = face_cascade.detectMultiScale(gray, 1.1, 4)

for (x, y, w, h) in faces: 
    cv2.rectangle(img, (x, y), (x+w, y+h),  
                  (0, 0, 255), 2) 

    faces = img[y:y + h, x:x + w] 
    cv2.imwrite('testImage-Cropped.jpg', faces) 

cv2.waitKey()

i love, how you overwrite the faces with the cropped image …

I forgot to mention, i am just using it to detect a single face as the picture will only have a single face

why do you even draw a red rectangle into it ?
(before cropping)

also, if you try to expand the (orig. square !) rect for cropping, be aware, that numpy will silently ‘wrap around’ the image borders if your calculation goes out of bounds.

crosspost: