我想从不同的子文件夹中读取所有图像,调整它们的大小,并用它们的原始名称保存它们。但是,我得到如下所示的错误。如何修复此错误
示例代码:
from PIL import Image
import os
size = (112, 112)
def resize_img(path,dest_path):
name_list = []
label_list = []
resized_list = []
if not os.path.exists(dest_path):
os.makedirs(dest_path)
folder_list = os.listdir(path)
for num_imgs,folder in enumerate(folder_list):
print(str(num_imgs) + " : " + folder)
files_path = path + "/" + folder
image_list = os.listdir(files_path)
name_list.append(folder)
for image_name in image_list:
image_path = path + "/" + folder + "/" + image_name
print(image_path)
img = Image.open(image_path)
label_list.append(img)
for image in label_list:
image = image.resize((112, 112))
resized_list.append(image)
for (i,new) in enumerate (resized_list):
new.save('{}{}{}'.format(dest_path+'/'+str(label_list)+str('_'), i+1, '.jpg'))
resize_img('C:/Users/aunglay/PycharmProjects/FR_using_cnn/Face_database',
'C:/Users/aunglay/PycharmProjects/FR_using_cnn/resized_images')
出现错误:
Traceback (most recent call last):
File "C:/Users/aunglay/PycharmProjects/FR_using_cnn/smaple2.py", line 30, in <module>
'C:/Users/aunglay/PycharmProjects/FR_using_cnn/resized_images')
File "C:/Users/aunglay/PycharmProjects/FR_using_cnn/smaple2.py", line 27, in resize_img
new.save('{}{}{}'.format(dest_path+'/'+str(label_list)+str('_'), i+1, '.jpg'))
File "C:\Users\aunglay\Anaconda3\envs\tensorflow_env\lib\site-packages\PIL\Image.py", line 2099, in save
fp = builtins.open(filename, "w+b")
OSError: [Errno 22] Invalid argument: 'C:/Users/aunglay/PycharmProjects/FR_using_cnn/resized_images/[<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=64x64 at 0x2D7ACFD508>]_1.jpg'
问题似乎出现在代码的最后一行:
具体来说,label_list是图像对象的列表,不包含您刚刚读取的图像的名称。另外,我认为最后两个for循环是不必要的。您可以更改代码:
致:
这应该实现你所描述的
编辑: 关于评论中提出的问题:
这应该实现您所描述的内容。您需要为要创建的每个子文件夹调用os.mkdir(),因此它必须位于第一个for循环中
相关问题 更多 >
编程相关推荐