取得图像目录并调整目录中所有图像的大小

时间:2019-03-06 17:54:00

标签: python image image-resizing python-3.7

我正在尝试将高分辨率图像转换为更易于管理的机器学习内容。目前,我有代码将图像调整为所需的高度和宽度,但是我必须一次执行一张图像,这在我只做12-24张图像时还是不错的,但是很快我想按比例放大做几百张图片。 我正在尝试读取目录而不是单个图像,并将新图像保存在新目录中。初始图像将不同于.jpg,.png,.tif等,但是我想像我在代码中一样将所有输出图像都设为.png。

import os
from PIL import Image

filename = "filename.jpg"
size = 250, 250
file_parts = os.path.splitext(filename)

outfile = file_parts[0] + '_250x250' + file_parts[1]
try:
    img = Image.open(filename)
    img = img.resize(size, Image.ANTIALIAS)
    img.save(outfile, 'PNG')
except IOError as e:
    print("An exception occured '%s'" %e)

感谢您提供有关此问题的任何帮助。

7 个答案:

答案 0 :(得分:2)

您可以使用

遍历目录的内容
import os

for root, subdirs, files in os.walk(MY_DIRECTORY):
    for f in files:
        if f.endswith('png'):
            #do something 

答案 1 :(得分:2)

假设您要寻找的解决方案是同时处理多张图片-这是一个解决方案。有关更多信息,请参见here

from multiprocessing import Pool

def handle_image(image_file):
    print(image_file)
    #TODO implement the image manipulation here

if __name__ == '__main__':
    p = Pool(5) # 5 as an example
    # assuming you know how to prepare image file list
    print(p.map(handle_image, ['a.jpg', 'b.jpg', 'c.png'])) 

答案 2 :(得分:2)

您可以使用此:

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

path = "\\path\\to\\files\\"
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,100), Image.ANTIALIAS)
            imResize.save(f+'.png', 'png', quality=80)

resize()

答案 3 :(得分:1)

您可以使用glob浏览目录中的所有图像。然后按照以下步骤或按照opencv的操作用PIL调整图像的大小。

import glob
import cv2
import numpy as np

IMG_DIR='home/xx/imgs'
def read_images(directory):
    for img in glob.glob(directory+"/*.png"):
        image = cv2.imread(img)
        resized_img = cv2.resize(image/255.0  , (250 , 250))

        yield resized_img

resized_imgs =  np.array(list(read_images(IMG_DIR)))

答案 4 :(得分:1)

您可以使用此代码来调整多个图像的大小,并将它们转换后保存在同一文件夹中,例如尺寸为(200,200):

import os
from PIL import Image

f = r' '      #Enter the location of your Image Folder
    
new_d = 200

for file in os.listdir(f):
    f_img = f+'/'+file
    try:
        img = Image.open(f_img)
        img = img.resize((new_d, new_d))
        img.save(f_img)
    except IOError:
        pass

答案 5 :(得分:0)

我用过:

from PIL import Image
import os, sys

path = os.path.dirname(os.path.abspath(__file__))
dirs = os.listdir( path )
final_size = 244
print(dirs)

def resize_aspect_fit():
    for item in dirs:
         if ".PNG" in item:
             print(item)
             im = Image.open(path+"\\"+item)
             f, e = os.path.splitext(path+"\\"+item)
             size = im.size
             print(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))
             print(f)
             new_im.save(f + 'resized.jpg', 'JPEG', quality=400)# png
resize_aspect_fit()

答案 6 :(得分:0)

您可以尝试使用PIL库在python中调整图像大小

import PIL
import os
import os.path
from PIL import Image


path = r'your images path here'
for file in os.listdir(path): 
    f_img = path+"/"+file
    img = Image.open(f_img)
    img = img.resize((100, 100)) #(width, height)
    img.save(f_img)