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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21517879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:03:29  来源:igfitidea点击:

Python/PIL Resize all images in a folder

pythonpython-imaging-library

提问by user3237883

I have the following code that I thought would resize the images in the specified path But when I run it, nothing works and yet python doesn't throw any error so I don't know what to do. Please advise. Thanks.

我有以下代码,我认为可以调整指定路径中图像的大小但是当我运行它时,没有任何作用,但是 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()

采纳答案by Sanjar Stone

#!/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()

Your mistake is belong to full path of the files. Instead of itemmust be path+item

您的错误属于文件的完整路径。而不是项目必须是路径+项目

回答by John Ottenlips

In case you want to keep the same aspect ratio of the image you can use this script.

如果您想保持图像的相同纵横比,您可以使用此脚本。

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()

回答by sivi

Expanding on the great solution of @Sanjar Stone

扩展@Sanjar Stone 的出色解决方案

for including subfolders and also avoid DS warnings you can use the glob library:

为了包含子文件夹并避免 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)

回答by Andrei M.

John Ottenlips's solution created pictures with black borders on top/bottom i think because he used

John Ottenlips 的解决方案在顶部/底部创建了带有黑色边框的图片,我认为是因为他使用了

  Image.new("RGB", (final_size, final_size))

which creates a square new image with the final_size as dimension, even if the original picture was not a square.

即使原始图片不是正方形,它也会创建一个以 final_size 为维度的方形新图像。

This fixes the problem and, in my opinion, makes the solution a bit clearer:

这解决了问题,并且在我看来,使解决方案更加清晰:

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()

回答by AQEL AL KHARASANI

This code just worked for me to resize images..

此代码仅适用于我调整图像大小..

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]))

回答by Raevel

For those that are on Windows:

对于那些在 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'))