问题描述
下面的代码从单个图像中提取人脸,然后将这些人脸输出到文件夹中。如何输入包含图像的目录并执行相同的操作?我似乎无法在图像中添加目录-face_recognition.load_image_file(C:/ directory),因为它不断返回,并显示权限被拒绝错误。有没有一种方法可以要求它遍历特定目录中的所有图像,然后将其输出到我的路径?
from PIL import Image
import face_recognition
image = face_recognition.load_image_file(r"C:\Users\Julio\Desktop\Face Extraction\Input\IMG_0421.JPG")
path = r"C:\Users\Julio\Desktop\Face Extraction\Output\face"
face_locations = face_recognition.face_locations(image)
print("I found {} face(s) in this photograph.".format(len(face_locations)))
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
解决方法
我最近做了一些类似的事情,希望对您有所帮助。我基本上将路径设置为变量,然后将该路径的listdir设置为名为img_list的变量,然后循环遍历该变量:
# media thumbnails
path = "/media/default_thumbnails/"
img_list = listdir(path)
for image in img_list:
"""
Need to open an image file from the directory as a PIL Image.
Then create a BytesIO and save that as the thumbnail.
"""
try:
img = PILImage.open(path + image)
rawfile = BytesIO()
img.save(rawfile,format='jpeg')
mt = MediaThumbnail.objects.create()
mt.thumbnail.save(image,rawfile)
rawfile.close()
except:
print(f" skipping {image}")
print(" thumbnails created")
要将其集成到您的代码中,您可以执行以下操作:
from PIL import Image
import face_recognition
path = "C:\Users\Julio\Desktop\Face Extraction\Input"
img_list = listdir(path)
for input_img in img_list:
image = face_recognition.load_image_file(input_img)
[.... the rest of your code ]
,
好吧,经过robline的建议,这是我到目前为止的代码:
from PIL import Image
import face_recognition
from os import listdir
path = r"C:\Users\Julio\Desktop\Face Extraction\Input"
img_list = listdir(path)
for input_img in img_list:
image = face_recognition.load_image_file(input_img)
face_locations = face_recognition.face_locations(image)
print("I found {} face(s) in this photograph.".format(len(face_locations)))
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
这会产生以下错误-multi2.jpeg只是C:\ Users \ Julio \ Desktop \ Face Extraction \ Input中的文件(唯一)
回溯(最近通话最近): 在第9行的文件“ C:/ Users / Julio / PycharmProjects / test /从照片test.py提取面部” 图片= face_recognition.load_image_file(input_img) 在load_image_file中,文件“ C:\ Users \ Julio \ PycharmProjects \ test \ venv \ lib \ site-packages \ face_recognition \ api.py”,第86行 我= PIL.Image.open(文件) 打开文件“ C:\ Users \ Julio \ PycharmProjects \ test \ venv \ lib \ site-packages \ PIL \ Image.py”,行2878 fp = builtins.open(文件名,“ rb”) FileNotFoundError:[错误2]没有这样的文件或目录:'multi2.jpeg'
以退出代码1完成的过程