Skip to main content
 首页 » 编程设计

python之使用 numpy 获取查找表索引的最快方法

2025年05月04日9cyq1162

这个问题遵循this other one ,旨在加速以下代码。我(在帮助下)构建了一些代码,这些代码从 m x n x 3 numpy.ndarray 中获取像素值。 (RGB 图像),将像素值与(位置)查找表的像素值进行比较,并输出查找表的像素值索引,如下所示:

img = np.random.randint(0, 9 , (3, 3, 3)) 
lut2 = img[0,0:2,:] 
 
output = [] 
for x in xrange(lut2.shape[0]): 
    if lut2[x] in img: 
            output.append(np.concatenate(np.where( (img == lut2[x]).sum(axis=2) == 3 ))) 
 
print np.array(output) 

输出:

[[0 0] 
 [0 1]] 

bug:如果你得到 lut[x] 将无法正确输出在一个以上的地方 img .也许更好的策略是将输出格式化为嵌套列表,因为任何可索引的都可以。例如:

[[x_px1, y_px1], [[x_px2a, y_px2a], [x_px2b, y_px2b]]] 

哪里px2a和 px2b是 img 中的独立像素具有相同的颜色值。

我一直在摆弄numpy指数化,但我无法取得更好的成绩。虽然上面的部分工作,但由于数组上的迭代,它当然非常慢。如果我给它一个普通尺寸的图像,它会花费 Not Acceptable 时间来完成。

有人可以指点我更快的解决方案吗?


编辑:我瞄准的理想 future 算法的总结:

  an image               all pixels replaced          all indices are 
  (here, single ----->   by index in lut     ----->   reused in digital_scale 
  black pixel)           (here, first pixel)          to output an array of scalars 
 
  [[[0, 0, 0]]]          [[[0, 0]]]                   [[0]] 
 
  array shape:           array shape:                 array shape: 
 
  m X n X 3              m X n X 2                    m X n 

最后m X n数组将用于两件事:

  • 通过将数组存储在数据库中,绘制不同时间间隔的数据。
  • 对由于某些外部事件引起的数组变化进行统计分析

注意: basemap 已经是一种绘图了,但是我没有办法得到数值数据,所以需要把绘图倒过来。


一些(可选的)要求精确说明我的代码的目标:

查找表通常基于像素值,而不是位置。不过在这种情况下,位置会更好(我认为)。 lut上面代码中的数组是一个虚拟的线性色标,表示我需要数字化的速度,如下所示:

由于比例尺的每一层都是统一的颜色,实际上比例尺可以简化为一个维度数组 1 X height X 3 (对于 RGB、HSV 等)。事实上,我可以删除第一个维度并遍历 height X 3 的数组。 .我用来数字化秤的东西是:

  • 它以零为中心
  • 它是对称的
  • 它是线性的
  • 已知最大值和最小值

因此,这个量表的数字表示将是:

digital_scale = np.linspace(-max_speed, max_speed, lut.shape[0]) 

我只需要得到 y我在 lut 中寻找的像素值索引,然后是 y digital_scale 的第一个元素输出我需要的值(标量,参见上面的算法摘要)。

请您参考如下方法:

你可以使用 Kd-tree,这里是一个演示:

import numpy as np 
from scipy import spatial 
 
H, W = 200, 100 
 
np.random.seed(1) 
a = np.random.randint(0, 20, (H, W, 3)) 
b = np.random.randint(0, 20, (20, 3)) 
tree = spatial.cKDTree(a.reshape(-1, 3)) 
res = tree.query_ball_point(b, 0.5, p=1) 
print res 

输出是:

[[] [577, 17471] [14636, 4515, 13693, 10988, 15013] [16935, 8576, 13286] 
 [2443] [7743, 5914] [] [7469, 19736, 13395, 14992, 9083, 15514] 
 [1167, 11416] [3903, 4968] [16504, 2996, 10805, 2264] [] [6725] 
 [14437, 5888] [17667] [4681, 2545, 6442] [15067, 4533] 
 [7876, 2235, 10152, 3288] [15404, 5691, 17216] 
 [15586, 9916, 16938, 15931, 4828, 4069]] 

查看索引2的结果:

rows, cols = np.where(np.all(a == b[None, None, 2], axis=-1)) 
assert np.all(rows * W + cols == sorted(res[2]))