将PIL的输出多个文件保存到目录

问题描述

我正在做一个基本项目,需要我拍摄一张图像,并将该面部(仅)与该图像分开,然后将其输出到单独的文件夹中。到目前为止,我已经写了下面的代码(是编码和Python的新手)。此代码的唯一问题是,当我知道有多张面孔时,它只会保存一张图片。如果我用带注释的部分pil_image.show()替换最后一行,那么它将通过为每个人打开一个单独的文件显示所有面孔,但不会在任何地方保存输出

我需要指向软件的帮助,以便将所有输出保存在目录中。

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,right))

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

    #pil_image.show()

解决方法

该行中有错误。pil_image.save(str(path) + ".jpg"),因为所有文件都在循环中写在同一文件路径上。

您可以尝试这个。

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,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