Search code examples
python-3.xpython-imaging-libraryface-recognition

Saving output (multiple files) of PIL to directory


I am doing a basic project which requires me to take an image and separate the faces (only) from that image and output them to a separate folder. So far I have written the code below (new to coding and Python). The only problem with this code is that it only saves one picture when I know there are multiple faces. If I replace the last line with the commented section, pil_image.show(), then it shows me all the faces by opening a separate file for each one, but doesn't save the output anywhere.

I need help with pointing the software so that it saves all the output in a directory.

from PIL import Image
import face_recognition

path = r"C:\Users\Julio\Desktop\Output\new"
image = face_recognition.load_image_file("MultiPeople/twopeople.jpeg")
count = 0

face_locations = face_recognition.face_locations(image)

print("I found {} face(s) in this photograph.".format(len(face_locations)))

for face_location in face_locations:
    top, right, bottom, left = face_location
    print("I found a face in image location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

    face_image = image[top:bottom, left:right]
    pil_image = Image.fromarray(face_image)
    pil_image.save(str(path) + ".jpg")

    #pil_image.show()

Solution

  • Error is in the line.. pil_image.save(str(path) + ".jpg") , as all the files are written on the same file path in a loop.

    You may try this.

    face_counter = 0
    for face_location in face_locations:
        top, right, bottom, left = face_location
        print("I found a face in image location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
    
        face_image = image[top:bottom, left:right]
        pil_image = Image.fromarray(face_image)
        pil_image.save(str(path) + str(face_counter) + ".jpg")
        face_counter += 1