Serek
Serek

Reputation: 11

Saving faces openCV

I have a code to crop faces and I'm trying to to save cropped images. My code saves only one image. Can you please help me expand functionality so program saves all the faces into separate files

import cv2
import os


def facecrop(image):
    facedata = "haarcascade_frontalface_alt.xml"
    cascade = cv2.CascadeClassifier(facedata)

    img = cv2.imread('class.jpg')

    minisize = (img.shape[1], img.shape[0])
    miniframe = cv2.resize(img, minisize)

    faces = cascade.detectMultiScale(miniframe)

    for f in faces:
        x, y, w, h = [v for v in f]
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255))

        sub_face = img[y:y + h, x:x + w]
        fname, ext = os.path.splitext(image)
        cv2.imwrite(fname + "_cropped_" + ext, sub_face)

    return

facecrop("1.jpg")

Upvotes: 1

Views: 1215

Answers (1)

Karthik
Karthik

Reputation: 400

You just need to have a counter and add it in your file name. What happening is, you are overwriting the images with the same filename. Hence you are getting only one image. Below is the code snippet

import cv2
import os


def facecrop(image):
    facedata = "haarcascade_frontalface_alt.xml"
    cascade = cv2.CascadeClassifier(facedata)

    img = cv2.imread('class.jpg')

    minisize = (img.shape[1], img.shape[0])
    miniframe = cv2.resize(img, minisize)

    faces = cascade.detectMultiScale(miniframe)
    counter = 1

    for f in faces:
        x, y, w, h = [v for v in f]
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255))

        sub_face = img[y:y + h, x:x + w]
        fname, ext = os.path.splitext(image)
        cv2.imwrite(fname + "_cropped_" + str(counter) + ext, sub_face)
        counter = counter + 1

    return

Hope it helps!

Upvotes: 3

Related Questions