Trying to make a Passport Photo using OpenCV-Python

Viewed 2350

Apologies in advance as i am newbie to OpenCV-Python. I set myself a task to create a Passport type image from the video capture.

Using a head and shoulders Haar Cascade i was able to create a portrait photo but i now want to turn the background to a white background (leaving the head and shoulders portrait in the foreground).

Just not sure how/ best way to do this. Any help would be welcome.

Many thanks in advance.

Here is the code:

import numpy as np
import cv2

# face file
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# eye file
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
# head shoulders file
hs_cascade = cv2.CascadeClassifier('HS.xml')

cap = cv2.VideoCapture(1)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    headshoulders = hs_cascade.detectMultiScale(gray, 1.3, 3)

    # find the head and shoulders
    for (x,y,w,h) in headshoulders:
        # variable change to make portrait orientation
        x = int(x*1.5)
        w = int(w/1.5)
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

        # crop the image
        crop_img = img[y: y + h, x: x + w]

        # show original and crop
        cv2.imshow('crop', crop_img)
        cv2.imshow('img', img)

    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
    elif k == ord('s'):
        # save out the portrait image
        cv2.imwrite('cropimage.png',crop_img)

# release the camera
cap.release()
cv2.destroyAllWindows()
1 Answers
Related