python - 将数千张图像读入一个大 numpy 数组的最快方法

标签 python image performance numpy

我正在尝试找到将一堆图像从目录读取到 numpy 数组中的最快方法。我的最终目标是计算所有这些图像中像素的最大、最小和第 n 个百分位数等统计数据。当所有图像的像素都在一个大的 numpy 数组中时,这是简单而快速的,因为我可以使用内置的数组方法,例如 .max.min,并且np.percentile 函数。

以下是 25 张 tiff 图像(512x512 像素)的几个示例时序。这些基准来自在 jupyter-notebook 中使用 %%timit。差异太小,仅对 25 张图片没有任何实际意义,但我打算在未来阅读数千张图片。

# Imports
import os
import skimage.io as io
import numpy as np
  1. 添加到列表

    %%timeit
    imgs = []    
    img_path = '/path/to/imgs/'
    for img in os.listdir(img_path):    
        imgs.append(io.imread(os.path.join(img_path, img)))    
    ## 32.2 ms ± 355 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
  2. 使用字典

    %%timeit    
    imgs = {}    
    img_path = '/path/to/imgs/'    
    for img in os.listdir(img_path):    
        imgs[num] = io.imread(os.path.join(img_path, img))    
    ## 33.3 ms ± 402 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    

对于上面的列表和字典方法,我尝试用相应的理解替换循环,在时间上具有相似的结果。我还尝试过预分配字典键,但所用时间没有显着差异。要将图像从列表中获取到大数组,我会使用 np.concatenate(imgs),它只需要大约 1 毫秒。

  1. 沿第一维预分配一个 numpy 数组

    %%timeit    
    imgs = np.ndarray((512*25,512), dtype='uint16')    
    img_path = '/path/to/imgs/'    
    for num, img in enumerate(os.listdir(img_path)):    
        imgs[num*512:(num+1)*512, :] = io.imread(os.path.join(img_path, img))    
    ## 33.5 ms ± 804 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
  2. 沿第三个维度预分配一个 numpy

    %%timeit    
    imgs = np.ndarray((512,512,25), dtype='uint16')    
    img_path = '/path/to/imgs/'    
    for num, img in enumerate(os.listdir(img_path)):    
        imgs[:, :, num] = io.imread(os.path.join(img_path, img))    
    ## 71.2 ms ± 2.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    

我最初认为 numpy 预分配方法会更快,因为循环中没有动态变量扩展,但情况似乎并非如此。我发现最直观的方法是最后一种方法,其中每个图像沿数组的第三轴占据一个单独的维度,但这也是最慢的。花费的额外时间不是由于预分配本身,它只需要大约 1 毫秒。

我对此有三个问题:

  1. 为什么 numpy 预分配方法不比字典和列表解决方案快?
  2. 将数千张图像读入一个大型 numpy 数组的最快方法是什么?
  3. 我可以从 numpy 和 scikit-image 之外寻找更快的图像读取模块吗?我试过 plt.imread(),但是 scikit-image.io 模块更快。

最佳答案

A 部分:访问和分配 NumPy 数组

按照 NumPy 数组中元素按行优先顺序存储的方式,在每次迭代中沿最后一个轴存储这些元素时,您是在做正确的事情。这些将占用连续的内存位置,因此对于访问和分配值来说将是最有效的。因此像 np.ndarray((512*25,512), dtype='uint16') 这样的初始化或 np.ndarray((25,512,512), dtype='uint16')正如评论中提到的那样,效果最好。

在将它们编译为函数以测试时序并输入随机数组而不是图像之后 -

N = 512
n = 25
a = np.random.randint(0,255,(N,N))

def app1():
    imgs = np.empty((N,N,n), dtype='uint16')
    for i in range(n):
        imgs[:,:,i] = a
        # Storing along the first two axes
    return imgs

def app2():
    imgs = np.empty((N*n,N), dtype='uint16')
    for num in range(n):    
        imgs[num*N:(num+1)*N, :] = a
        # Storing along the last axis
    return imgs

def app3():
    imgs = np.empty((n,N,N), dtype='uint16')
    for num in range(n):    
        imgs[num,:,:] = a
        # Storing along the last two axes
    return imgs

def app4():
    imgs = np.empty((N,n,N), dtype='uint16')
    for num in range(n):    
        imgs[:,num,:] = a
        # Storing along the first and last axes
    return imgs

时间安排 -

In [45]: %timeit app1()
    ...: %timeit app2()
    ...: %timeit app3()
    ...: %timeit app4()
    ...: 
10 loops, best of 3: 28.2 ms per loop
100 loops, best of 3: 2.04 ms per loop
100 loops, best of 3: 2.02 ms per loop
100 loops, best of 3: 2.36 ms per loop

这些时间证实了开始时提出的性能理论,尽管我预计最后一次设置的时间将介于 app3 之间。和 app1 ,但也许从最后一个轴到第一个轴进行访问和分配的效果不是线性的。对此进行更多调查可能会很有趣(follow up question here)。

为了明确说明,假设我们正在存储图像数组,表示为 x (图 1)和 o (图 2),我们会:

应用程序1:

[[[x 0]
  [x 0]
  [x 0]
  [x 0]
  [x 0]]

 [[x 0]
  [x 0]
  [x 0]
  [x 0]
  [x 0]]

 [[x 0]
  [x 0]
  [x 0]
  [x 0]
  [x 0]]]

因此,在内存空间中,它将是:[x,o,x,o,x,o..]遵循行主要顺序。

应用程序2:

[[x x x x x]
 [x x x x x]
 [x x x x x]
 [o o o o o]
 [o o o o o]
 [o o o o o]]

因此,在内存空间中,它将是:[x,x,x,x,x,x...o,o,o,o,o..] .

App3:

[[[x x x x x]
  [x x x x x]
  [x x x x x]]

 [[o o o o o]
  [o o o o o]
  [o o o o o]]]

因此,在内存空间中,它会与前一个相同。


B 部分:从磁盘读取图像作为数组

现在,关于读取图像的部分,我看到了 OpenCV 的 imread更快。

作为测试,我从 wiki 页面下载了蒙娜丽莎的图像并测试了图像读取性能 -

import cv2 # OpenCV

In [521]: %timeit io.imread('monalisa.jpg')
100 loops, best of 3: 3.24 ms per loop

In [522]: %timeit cv2.imread('monalisa.jpg')
100 loops, best of 3: 2.54 ms per loop

关于python - 将数千张图像读入一个大 numpy 数组的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078327/

相关文章:

Python win32com - 自动化 Word - 如何替换文本框中的文本?

c# - 旧的注释代码和代码中的大量空格会降低性能吗?

java - 使用 BufferedImage 时 Swing HTML 渲染发生变化

php - 在故事中间动态添加图像

node.js - 使用 perf_events 的 nodejs/v8 火焰图中的未知事件

MYSQL:连接表性能缓慢

python - 如何在 Python 中设置嵌套类的显示名称?

c# - 不同网络平台/网络产品之间常见的同音异义词和同义词有哪些?

python - 读取 CSV 并绘制彩色折线图

java - 在 Java 中的 GridLayout 上叠加图像