【发布时间】:2013-01-07 15:02:36
【问题描述】:
编辑我把我面临的更复杂的问题保留在下面,但是我在np.take 的问题可以更好地总结如下。假设您有一个形状为(planes, rows) 的数组img 和另一个形状为(planes, 256) 的数组lut,并且您想使用它们创建一个形状为(planes, rows) 的新数组out,其中out[p,j] = lut[p, img[p, j]] .这可以通过花哨的索引来实现,如下所示:
In [4]: %timeit lut[np.arange(planes).reshape(-1, 1), img]
1000 loops, best of 3: 471 us per loop
但是,如果您不使用花哨的索引,而是使用 take 并在 planes 上使用 python 循环,则可以大大加快速度:
In [6]: %timeit for _ in (lut[j].take(img[j]) for j in xrange(planes)) : pass
10000 loops, best of 3: 59 us per loop
lut 和 img 可以以某种方式重新排列,以便在没有 python 循环的情况下进行整个操作,而是使用numpy.take(或替代方法)而不是传统的花式索引来保持速度优势?
原始问题
我有一组要在图像上使用的查找表 (LUT)。保存 LUT 的数组的形状为 (planes, 256, n),图像的形状为 (planes, rows, cols)。两者都属于dtype = 'uint8',与LUT 的256 轴相匹配。这个想法是通过LUT的p-th平面中的每个n LUT运行图像的p-th平面。
如果我的lut 和img 如下:
planes, rows, cols, n = 3, 4000, 4000, 4
lut = np.random.randint(-2**31, 2**31 - 1,
size=(planes * 256 * n // 4,)).view('uint8')
lut = lut.reshape(planes, 256, n)
img = np.random.randint(-2**31, 2**31 - 1,
size=(planes * rows * cols // 4,)).view('uint8')
img = img.reshape(planes, rows, cols)
使用像这样的精美索引后,我可以实现自己的目标
out = lut[np.arange(planes).reshape(-1, 1, 1), img]
这给了我一个形状数组 (planes, rows, cols, n) ,其中out[i, :, :, j] 持有img 的i-th 平面,穿过j-th LUT 的i-th LUT 平面...
一切都很好,除了这个:
In [2]: %timeit lut[np.arange(planes).reshape(-1, 1, 1), img]
1 loops, best of 3: 5.65 s per loop
这是完全不可接受的,特别是因为我使用np.take 有以下所有看起来不太好看的替代品,而不是运行得更快:
-
单个平面上的单个 LUT 运行速度大约快 70 倍:
In [2]: %timeit np.take(lut[0, :, 0], img[0]) 10 loops, best of 3: 78.5 ms per loop -
运行所有所需组合的 python 循环完成速度几乎快 x6:
In [2]: %timeit for _ in (np.take(lut[j, :, k], img[j]) for j in xrange(planes) for k in xrange(n)) : pass 1 loops, best of 3: 947 ms per loop -
即使在 LUT 和图像中运行所有平面组合,然后丢弃
planes**2 - planes不需要的平面组合,也比花哨的索引更快:In [2]: %timeit np.take(lut, img, axis=1)[np.arange(planes), np.arange(planes)] 1 loops, best of 3: 3.79 s per loop -
我能想到的最快的组合是一个 python 循环在平面上迭代并更快地完成 x13:
In [2]: %timeit for _ in (np.take(lut[j], img[j], axis=0) for j in xrange(planes)) : pass 1 loops, best of 3: 434 ms per loop
当然,问题是如果没有任何 python 循环就没有办法用np.take 做到这一点?理想情况下,需要的任何重塑或调整大小都应该发生在 LUT 上,而不是图像上,但我愿意接受你们能想到的任何事情......
【问题讨论】:
-
你的 sn-p 中的
bkpt是什么 - 无需解释,我只是想提醒你,以防万一是错字 - 我想应该是lut? -
...整行不应该是
lut = lut.reshape(planes, 256, 4),所以最后一个暗处是4? -
@TheodrosZelleke 感谢您抓到这些!我的
lut实际上是一个断点表,所以在我的代码中它被称为bkpt,而我在为问题翻译它时错过了它。 -
真的,不知道。看起来一切都很丑陋。一件事,
np.take目前只有在两个输入都是 c 连续的(否则它会复制它们)时才快。您可能可以手动将二维数组转换为一维数组,但如果img真的很大,它可能并不重要,如果它值得玩转...... -
嗨,你应该给出一个完整的例子,如果太长,那么只需在 github 上创建一个 gist。否则人们很难重现您的问题并尝试提供帮助。