【问题标题】:Python - Faster way to load several images?Python - 加载多个图像的更快方法?
【发布时间】:2016-08-09 19:13:08
【问题描述】:

我的项目中的一项任务是加载数据集 (chars74k) 并为每个图像设置标签。在这个实现中,我已经有一个包含其他图像的矩阵和一个带有各自标签的列表。为了完成任务,我编写了以下代码:

#images: (input/output)matrix of images
#labels: (input/output)list of labels
#path:   (input)path to my root folder of images. It is like this:
# path
#   |-folder1
#   |-folder2
#   |-folder3
#   |-...
#   |-lastFolder

def loadChars74k(images, labels, path):
    # list of directories
    dirlist = [ item for item in os.listdir(path) if os.path.isdir(os.path.join(path, item)) ]

    # for each subfolder, open all files, append to list of images x and set path as label in y
    for subfolder in dirlist:   
        imagePath = glob.glob(path + '/' + subfolder +'/*.Bmp')
        print "folder ", subfolder, " has ",len(imagePath), " images and matrix of images is:", images.shape, "labels are:", len(labels)
        for i in range(len(imagePath)):
            anImage = numpy.array(Image.open(imagePath[i]).convert('L'), 'f').ravel()
            images = numpy.vstack((images,anImage))
            labels.append(subfolder)

它运行良好,但耗时太长(大约 20 分钟)。我想知道是否有更快的方法来加载图像和设置标签。

问候。

【问题讨论】:

  • 我猜大部分处理时间在Image.open(...)。你真的需要记住所有这些吗?也许只是保留对图像路径的引用并在必要时读取文件?
  • 另外,你为什么要for i in range(len(imagePath)): ... imagePath[i]?不要循环遍历列表的索引,然后索引该列表:只需遍历列表本身。
  • 好吧,我想我正在循环并打开所有图像以加载到 numpy.array 中,然后将图像附加到“图像”。这有什么问题?
  • 这需要很长时间,几乎可以肯定,因为您要打开这么多图像。你需要所有的图像数据吗?
  • 如果图像大小不变,您应该预先分配正确大小的数组并直接写入正确的位置,从而节省对vstack的昂贵调用。

标签: python numpy


【解决方案1】:

经过一番研究,我能够以这种方式改进代码:

def loadChars74k(images, labels, path):
    # list of directories
    dirlist = [ item for item in os.listdir(path) if os.path.isdir(os.path.join(path, item)) ]

    # for each subfolder, open all files, append to list of images x and set path as label in y
    for subfolder in dirlist:   
        imagePath = glob.glob(path + '/' + subfolder +'/*.Bmp')
        im_array = numpy.array( [numpy.array(Image.open(imagePath[i]).convert('L'), 'f').ravel() for i in range(len(imagePath))] )
        images = numpy.vstack((images, im_array))
        for i in range(len(imagePath)):
            labels.append(subfolder)

    return images, labels

我很确定可以进一步改进,但现在没关系!现在需要33秒!

【讨论】:

  • 如何提高速度?
  • 哈哈!这段代码是绝对错误的!图像读取部分在循环之外。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-30
  • 1970-01-01
  • 2019-12-11
  • 2012-05-22
  • 1970-01-01
  • 2018-10-18
相关资源
最近更新 更多