Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I have code that detects a face. All I want to do is save the detected face as a jpg

Here is the code for my program:

import numpy as np

import cv2

detector= cv2.CascadeClassifier('haarcascade_fullbody.xml')

cap = cv2.VideoCapture(0)

while(True):

    ret, img = cap.read()

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = detector.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:

        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    cv2.imshow('frame',img)

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break

cap.release()

cv2.destroyAllWindows()

How do I save the detected face? Please help!

2 Answers

0 votes
by (260 points)
if you want to save only the detected faces (not the whole image), try to crop the face using :

for (x,y,w,h) in faces :

   crop_face = img[y:y+h, x:x+w]

then to save it use : cv2.imwrite(crop_face, path)

you'll need to specify the path where you want to save the images
you can use :
path = os.path.sep.join([output_dir, "{}.jpg".format(str(total).zfill(8))])

where total is a counter to increment after each face detected, output_dir is the path of the folder where you want to save the images. generated images will count up incrementally from output_dir/00000000.jpg
0 votes
by (41.4k points)

Here, you should use cv2.imwrite and array slicing:

count = 0

for (x,y,w,h) in faces:

        face = img[y:y+h, x:x+w] #slice the face from the image

        cv2.imwrite(count+'.jpg', face) #save the image

        count+=1

        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

Browse Categories

...