![](/img/trans.png)
[英]Read all images from subfolder, resize them and save them with their original name in Python?
[英]How to read all images from subfolder, resize them and save them with their original name in Python?
如何從子文件夾中讀取所有圖像,調整它們的大小並將它們以原始名稱保存在 Python 中? 請幫我。 我想讀取不同子文件夾中的所有圖像,並希望調整它們的大小並使用它們的原始圖像名稱保存它們。
from PIL import Image
import os
path = "C:/Users/aunglay/PycharmProjects/Face Recognition using cnn/Face_database"
size = 112
def resize_images():
dirs = os.listdir(path)
for item in dirs:
if item == '.jpg':
continue
if os.path.isfile(path+item):
image = Image.open(path+item)
file_path, extension = os.path.splitext(path+item)
image = image.resize((size, size), Image.ANTIALIAS)
image.save(file_path + "_resized" + extension, 'JPEG', quality=90)
resize_images()
使用下划線或破折號,但避免目錄名稱使用空格。 要通過文件夾和子文件夾來發現文件,我建議您使用os.walk
而不是os.listdir
。 這可能會導致很多嵌套的fors
但它應該可以完成工作
from PIL import Image
import fnmatch
import os
thumbnail = (112,112)
def resize_images(path,size):
dirs = os.walk(path)
for folders in dirs:
for files in folders:
for file in files:
if fnmatch.fnmatch(*jpeg):
image = Image.open(item)
image = image.resize(size)
image.save(f"item{_resized}")
else:
continue
resize_images("C:/Users/aunglay/PycharmProjects/Face_Recognition_using_cnn/Face_database", thumbnail)
這種級別的嵌套 for 循環的替代方法是使用map()
高階函數。 當然,您必須進行一些更改以適合您的文件夾和目錄結構
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.