繁体   English   中英

加载到python时调整图像大小

[英]resize images while loading into python

嗨:我想将一个文件夹中的2400张图像加载到用于神经网络的python 3.6中,以下代码可以工作,但是,它转换为原始图像后,会以其原始大小(2443、320、400、3)加载图像。阵列。 如何将其调整为64x96? 因此它是(2443、64、96、3),并且减少了内存负载。 另外,我该如何使用并行处理来做到这一点,因此效率很高。

谢谢!

IMAGE_PATH = 'drive/xyz/data/'
file_paths = glob.glob(path.join(IMAGE_PATH, '*.gif'))

# Load the images
images = [misc.imread(path) for path in file_paths]
images = np.asarray(images)

受此链接的启发,我尝试执行以下操作:

from PIL import Image

basewidth = 96
IMAGE_PATH = 'drive/xyz/data/' 
file_paths = glob.glob(path.join(IMAGE_PATH, '*.gif'))

# Load the images img = [misc.imread(path) for path in file_paths]

wpercent = (basewidth/float(img.size[0])) 
hsize = int((float(img.size[1])*float(wpercent))) 
img = img.resize((basewidth,hsize), Image.ANTIALIAS) 
images = np.asarray(img)

但是,这导致了错误,如下所示。 任何建议将不胜感激。 谢谢。

AttributeError                            Traceback (most recent call last)
<ipython-input-7-56ac1d841c56> in <module>()
      9 img = [misc.imread(path) for path in file_paths]
     10 
---> 11 wpercent = (basewidth/float(img.size[0]))
     12 hsize = int((float(img.size[1])*float(wpercent)))
     13 img = img.resize((basewidth,hsize), Image.ANTIALIAS)

AttributeError: 'list' object has no attribute 'size'

首先,您可能要调整图像大小,然后在给定输出图像文件夹的情况下,可以使用相同的方法初始化数组。

调整图像大小

这使用PIL包来调整图像大小,但是任何库只要提供了调整大小的方法,都应该执行相同的操作。

您可以从此处进一步阅读讨论内容。 如何使用PIL调整图像大小并保持其纵横比?

import os, sys
import Image

size = 128, 128

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".gif"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(outfile, "GIF")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile

并行度示例

关于并行性,您可以将此示例作为基础并从那里继续进行。

这来自python docs https://docs.python.org/3/library/multiprocessing.html

from multiprocessing import Process

    def f(name):
        print('hello', name)

    if __name__ == '__main__':
        p = Process(target=f, args=('bob',))
        p.start()
        p.join()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM