【问题标题】:resize images while loading into python在加载到 python 时调整图像大小
【发布时间】:2018-09-16 21:08:08
【问题描述】:

嗨:我想从一个文件夹中将一些 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)

link 的启发,我尝试执行以下操作:

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'

【问题讨论】:

  • 最后一行的图片是你的输出吗?你想并行化第 3-4 步吗?
  • @IshanBhatt 是的。

标签: python parallel-processing python-imaging-library


【解决方案1】:

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

调整图片大小

这使用 PIL 包来调整图像大小,但任何库都应该这样做,只要它提供调整大小的方法。

你可以从这里How do I resize an image using PIL and maintain its aspect ratio?阅读更多讨论

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

【讨论】:

  • 嗨@UmutGüler,谢谢。我在哪里指定路径?文件名 := "dir/to/myfile/somefile.gif"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 2012-03-20
  • 2014-05-26
  • 2013-02-24
  • 2014-11-08
  • 1970-01-01
  • 2016-08-25
相关资源
最近更新 更多