Python/PIL调整文件夹中的所有图像大小

52

我有以下代码,本以为可以调整指定路径下的图像大小。但是运行后并没有任何作用,同时Python也没有抛出任何错误,所以我不知道该怎么办。请给予建议。谢谢。

from PIL import Image
import os, sys

path = ('C:\Users\Maxxie\color\complete')

def resize():
for item in os.listdir(path):
    if os.path.isfile(item):
        im = Image.open(item)
        f, e = os.path.splitext(item)
        imResize = im.resize((200,200), Image.ANTIALIAS)
        imResize.save(f + ' resized.jpg', 'JPEG', quality=90)

resize()
10个回答

69
#!/usr/bin/python
from PIL import Image
import os, sys

path = "/root/Desktop/python/images/"
dirs = os.listdir( path )

def resize():
    for item in dirs:
        if os.path.isfile(path+item):
            im = Image.open(path+item)
            f, e = os.path.splitext(path+item)
            imResize = im.resize((200,200), Image.ANTIALIAS)
            imResize.save(f + ' resized.jpg', 'JPEG', quality=90)

resize()

你的错误在于文件的完整路径。应该使用 path+item 而不是 item


没有...什么都没用,我仍然没有收到任何Traceback错误。不过还是谢谢回复。 - user3237883
请再次在Windows上检查PIL。该代码在Linux上完全正常运行。 - Sanjar Stone
5
非常正确。我的路径设置为 path = ('C:\Users\Maxxie\color\complete') ,而不是 path = ('C:\Users\Maxxie\color\complete\\'),现在一切都按预期工作了...非常感谢。 - user3237883
3
你应该使用 os.path.join() 而不是直接连接字符串。这样一来,你就不需要让 path 以路径分隔符结尾了。 - Martijn Pieters
有没有办法只调整宽度,让高度按比例缩放? - user1702965
显示剩余3条评论

9
约翰·奥滕利普的解决方案在图片的顶部和底部创建了带有黑色边框的图片,我认为这是因为他使用了 \ 标签。
  Image.new("RGB", (final_size, final_size))

该操作会创建一个正方形的新图像,其尺寸为final_size,即使原始图片不是正方形。

这种方法修复了问题,并且在我看来,使得解决方案更加清晰明了:

from PIL import Image
import os

path = "C:/path/needs/to/end/with/a/"
resize_ratio = 0.5  # where 0.5 is half size, 2 is double size

def resize_aspect_fit():
    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)

            new_image_height = int(image.size[0] / (1/resize_ratio))
            new_image_length = int(image.size[1] / (1/resize_ratio))

            image = image.resize((new_image_height, new_image_length), Image.ANTIALIAS)
            image.save(file_path + "_small" + extension, 'JPEG', quality=90)


resize_aspect_fit()

8
如果您想保持图像的相同纵横比,可以使用此脚本。
from PIL import Image
import os, sys

path = "/path/images/"
dirs = os.listdir( path )
final_size = 244;

def resize_aspect_fit():
    for item in dirs:
         if item == '.DS_Store':
             continue
         if os.path.isfile(path+item):
             im = Image.open(path+item)
             f, e = os.path.splitext(path+item)
             size = im.size
             ratio = float(final_size) / max(size)
             new_image_size = tuple([int(x*ratio) for x in size])
             im = im.resize(new_image_size, Image.ANTIALIAS)
             new_im = Image.new("RGB", (final_size, final_size))
             new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
             new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
resize_aspect_fit()

5

在@Sanjar Stone的好解决方案基础上,为了包含子文件夹并避免DS警告,您可以使用glob库:

from PIL import Image
import os, sys
import glob

root_dir = "/.../.../.../"


for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
    print(filename)
    im = Image.open(filename)
    imResize = im.resize((28,28), Image.ANTIALIAS)
    imResize.save(filename , 'JPEG', quality=90)

这对我有用。我该如何将新文件保存在名为“resized”的不同目录中?我尝试过imResize.save("./resized/" + filename , 'JPEG', quality=90),但没有成功。(我不常使用Python) - mikey
1
你可以尝试不在开头加上"./",或者检查你的目录结构和Python手册,如果仍然无法解决问题。 - sivi
有时候需要使用"../resized"这个选项来进行快捷操作,如果它们无法正常工作,您就必须编写完整的路径——这会对代码的模块化造成影响。 - sivi

2

这段代码对我来说可以调整图像大小。

from PIL import Image
import glob
import os

# new folder path (may need to alter for Windows OS)
# change path to your path
path = 'yourpath/Resized_Shapes' #the path where to save resized images
# create new folder
if not os.path.exists(path):
    os.makedirs(path)

# loop over existing images and resize
# change path to your path
for filename in glob.glob('your_path/*.jpg'): #path of raw images
    img = Image.open(filename).resize((306,306))
    # save resized images to new folder with existing filename
    img.save('{}{}{}'.format(path,'/',os.path.split(filename)[1]))

2

对于使用Windows的用户:

from PIL import Image
import glob

image_list = []
resized_images = []

for filename in glob.glob('YOURPATH\\*.jpg'):
    print(filename)
    img = Image.open(filename)
    image_list.append(img)

for image in image_list:
    image = image.resize((224, 224))
    resized_images.append(image)

for (i, new) in enumerate(resized_images):
    new.save('{}{}{}'.format('YOURPATH\\', i+1, '.jpg'))

0
如果您想调整文件夹中任何图像的大小,而该文件夹中还存在其他文件,则可以尝试以下方法:
from genericpath import isdir
from PIL import Image
import os, sys

path = "C://...//...//....//...//"
save_path = "C://...//..//...//...//"
images = os.listdir(path)

if not os.path.isdir(save_path):
    os.makedirs(save_path)


for image in images:
    image_path = os.path.join(path, image)
    iamge_save_path = os.path.join(save_path, image)
    if image.split(".")[1] not in ["jpg", "png"]:
        continue
    if os.path.exists(image_path):
        im = Image.open(image_path)
        image_resized = im.resize((224,224))
        image_resized.save(iamge_save_path, quality=90)
        # print("saved")

0

使用pathlib更安全

正如jwal在类似问题的评论中所说的那样, 使用面向对象的相应替代ospathlib

from pathlib import Path

# folder = 'images'
# new_dimension = (width, height)
def resize(folder, new_dimension, new_subdir):
    
    images_folder = Path(folder)
    for child in images_folder.iterdir():
        print("Found image:", child)
        image_path = child.absolute()

        image = Image.open(image_path)
        resized_image = image.resize()  # could also add Image.ANTIALIAS

        # create if the subdir not exists
        subdir = images_folder.join(new_subdir)
        if not subdir.exists():
            subdir.mkdir(parents=True, exist_ok=True)
        
        to_path = subdir.joinpath(child.name)  # join adds the path-separators
        print("Saving resized to:", to_path)
        resized_image.save(to_path)  # could also add save-options like 'JPEG', quality=90

0

在@Sanjar Stone的代码基础上进行了大量借鉴。这段代码在Windows操作系统中运行良好。 可以用于批量调整图像大小并将其组装回其相应的子目录。

Original folder with it subdir:
..\DATA\ORI-DIR
├─Apolo
├─Bailey
├─Bandit
├─Bella

新建带有子目录的文件夹:

..\DATA\NEW-RESIZED-DIR
├─Apolo
├─Bailey
├─Bandit
├─Bella

代码片段链接:https://gist.github.com/justudin/2c1075cc4fd4424cb8ba703a2527958b
from PIL import Image
import glob
import os

# new folder path (may need to alter for Windows OS)
# change path to your path
ORI_PATH = '..\DATA\ORI-DIR'
NEW_SIZE = 224
PATH = '..\DATA\NEW-RESIZED-DIR' #the path where to save resized images

# create new folder
if not os.path.exists(PATH):
    os.makedirs(PATH)

# loop over existing images and resize
# change path to your path
for filename in glob.glob(ORI_PATH+'**/*.jpg'): #path of raw images with is subdirectory
    img = Image.open(filename).resize((NEW_SIZE,NEW_SIZE))
    
    # get the original location and find its subdir
    loc = os.path.split(filename)[0]
    subdir = loc.split('\\')[1]
    
    # assembly with its full new directory
    fullnew_subdir = PATH+"/"+subdir
    name = os.path.split(filename)[1]
    
    # check if the subdir is already created or not
    if not os.path.exists(fullnew_subdir):
        os.makedirs(fullnew_subdir)
    
    # save resized images to new folder with existing filename
    img.save('{}{}{}'.format(fullnew_subdir,'/',name))

0

扩展了Andrei M.的答案,以便仅更改图片的高度并自动调整宽度。

from PIL import Image
import os

path = "D:/.../.../.../resized/"
dirs = os.listdir(path)

def resize():
    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)
            size = image.size

            new_image_height = 190
            new_image_width = int(size[1] / size[0] * new_image_height)

            image = image.resize((new_image_height, new_image_width), Image.ANTIALIAS)
            image.save(file_path + "_small" + extension, 'JPEG', quality=90)


resize()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接