我想将np.array与集合相交,而不必先将np.array转换为列表(将程序减慢到无法工作的水平)。
这是我当前的代码:(请注意,我是从b,g,r rawCapture获取此数据的,而selection_data只是之前的一组。)
def GreenCalculations(data):
data.reshape(1,-1,3)
data={tuple(item) for item in data[0]}
ColourCount=selection_data & set(data)
Return ColourCount
现在,我现在的问题是,由于数据[0],我只比较图片的第一部分。是否可以遍历所有行?
注意:tolist()需要很多时间。
首先是一个样品data
; 我猜这是一个nxnx3数组,带有dtypeuint8
In [791]: data=np.random.randint(0,256,(8,8,3),dtype=np.uint8)
reshape
方法返回具有新形状的新数组,但不会就地更改它:
In [793]: data.reshape(1,-1,3)
data.shape=(1,-1,3)
会就地做到这一点。但是为什么要初始1
呢?
反而:
In [795]: aset={tuple(item) for item in data.reshape(-1,3)}
In [796]: aset
Out[796]:
{(3, 92, 60),
(5, 211, 227),
(6, 185, 183),
(9, 37, 0),
....
In [797]: len(aset)
Out[797]: 64
就我而言,一组64个唯一项-考虑到我是如何生成这些值的,这不足为奇
您无所事事的data.reshape
行,并{tuple(item) for item in data[0]}
说明了为什么它似乎只在图片的第一行起作用。
我猜selection_data
是类似的3项元组,例如:
In [801]: selection_data = {tuple(data[1,3,:]), (1,2,3), tuple(data[5,5,:])}
In [802]: selection_data
Out[802]: {(1, 2, 3), (49, 132, 26), (76, 131, 16)}
In [803]: selection_data&aset
Out[803]: {(49, 132, 26), (76, 131, 16)}
您没有说要在哪里使用tolist
,但我猜测是在生成元组的过程中。
但奇怪的是,tolist
可以加快转换速度:
In [808]: timeit {tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 57.7 µs per loop
In [809]: timeit {tuple(item) for item in data.reshape(-1,3)}
1000 loops, best of 3: 239 µs per loop
In [815]: timeit data.reshape(-1,3).tolist()
100000 loops, best of 3: 19.8 µs per loop
In [817]: timeit {tuple(item.tolist()) for item in data.reshape(-1,3)}
10000 loops, best of 3: 100 µs per loop
因此,为了执行这种列表和设置操作,我们不妨立即跳到列表格式。
numpy
具有一些设置功能,例如np.in1d
。这仅对1d数组进行操作,但是正如某些unique row
问题所证明的那样,我们可以通过将2d数组视为结构化数组来解决这一问题。我必须四处弄弄才能做到这一点:
In [880]: dt=np.dtype('uint8,uint8,uint8')
In [881]: data1=data.reshape(-1,3).view(dt).ravel()
In [882]: data1
Out[882]:
array([(41, 145, 254), (138, 144, 7), (192, 241, 203), (42, 177, 215),
(78, 132, 87), (221, 176, 87), (107, 171, 147), (231, 13, 53),
...
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
构造具有相同结构化数组性质的选择:
In [883]: selection=[data[1,3,:],[1,2,3],data[5,5,:]]
In [885]: selection=np.array(selection,np.uint8).view(dt)
In [886]: selection
Out[886]:
array([[(49, 132, 26)],
[(1, 2, 3)],
[(76, 131, 16)]],
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
因此,在项目selection
是中还发现data1
有:
In [888]: np.in1d(selection,data1)
Out[888]: array([ True, False, True], dtype=bool)
data1
选中的项目是:
In [890]: np.where(np.in1d(data1,selection))
Out[890]: (array([11, 45], dtype=int32),)
或呈散开的形状
In [891]: np.where(np.in1d(data1,selection).reshape(8,8))
Out[891]: (array([1, 5], dtype=int32), array([3, 5], dtype=int32))
与我用来生成的(1,3)和(5,5)相同selection
。
该in1d
时序为竞争力:
In [892]: %%timeit
...: data1=data.reshape(-1,3).view(dt).ravel()
...: np.in1d(data1,selection)
...:
10000 loops, best of 3: 65.7 µs per loop
In [894]: timeit selection_data&{tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 91.5 µs per loop
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句