最初的问题是试图在表中进行查找,但是
有些索引越界,我想控制
发生这种情况时的行为。在import numpy as np
lut = np.ones((5,7,11),np.int) # a 3-dimensional lookup table
print("lut.shape = ",lut.shape ) # (5,7,11)
# valid points are in the interior with value 99,
# invalid points are on the faces with value 0
lut[:,:,:] = 0
lut[1:-1,1:-1,1:-1] = 99
# set up an array of indexes with many of them too large or too small
start = -35
arr = np.arange(start,2*11*3+start,1).reshape(2,11,3)
# This solution has the advantage that I can understand what is going on
# and so I can amend it if I need to
# split arr into tuples along axis=2
arrchannels = arr[:,:,0],arr[:,:,1],arr[:,:,2]
# convert into a flat array but clip the values
ravelledarr = np.ravel_multi_index(arrchannels, lut.shape, mode='clip')
# and now turn back into a list of numpy arrays
# (not an array of the original shape )
clippedarr = np.unravel_index( ravelledarr, lut.shape)
print(clippedarr[0].shape,"*",len(clippedarr)) # produces (2, 11) * 3
# and now I can do the lookup with the indexes clipped to fit
print(lut[clippedarr])
# these are more succinct but opaque ways of doing the same
# due to @Divakar and @hjpauli respectively
print( np.take(lut, np.ravel_multi_index(arr.T, lut.shape, mode='clip')).T )
print( lut.flat[np.ravel_multi_index(arr.T, lut.shape, mode='clip')].T )
实际应用是,我有一个rgb图像包含一些纹理木材和一些标记,我已经确定了它的一个补丁。我想在这个补丁中获取一组像素,并标记出整个图像中与其中一个匹配的所有点。256x256x256的存在表太大,所以我对补丁中的像素运行了一个聚类算法,并为每个簇设置了存在表(来自补丁的颜色在rgb或hsv空间形成了一条细线,因此簇周围的框很小)。在
我把存在表做得比需要的稍大一点,并用假表填充每个面。在
一旦我建立了这些小的存在表,我现在可以通过查找表中的每个像素来测试图像的其余部分是否与补丁匹配,并使用剪切使那些通常不会映射到表中的像素实际上映射到表的一个面上(并获得值'False')