Finding local maxima in large 3D Numpy arrays
我正在处理一些三维numpy数组中存在的大体积图像数据。我将用两个小的一维数组来解释我的任务。我有一张图片:
1 | img = [5, 6, 70, 80, 3, 4, 80, 90] |
以及该图像的一个分割和标记版本:
1 | labels = [0, 0, 1, 1, 0, 0, 2, 2] |
号
[5、6、70、80、3、4、80、90]
我现在要做的是找出每个物体的最大值的位置,在这个例子中是
1 2 3 4 5 | for label in range(1, num_labels + 1): imgcp = np.copy(img) imgcp[labels != label] = 0 max_pos = np.argmax(imgcp) max_coords = np.unravel_index(pos, imgcp.shape) |
这种方法的一个问题是,在每个步骤中复制
这里有一种使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | # small 2d example >>> data = np.array([[0,1,4,0,0,2,1,0],[0,4,1,3,0,0,0,0]]) >>> segments = np.array([[0,1,1,0,0,2,2,0],[0,1,1,1,0,0,0,0]]) >>> # discard zeros >>> nz = np.where(segments) >>> segc = segments[nz] >>> dac = data[nz] # count object sizes >>> cnts = np.bincount(segc) >>> bnds = np.cumsum(cnts) # use counts to partition into objects >>> idx = segc.argpartition(bnds[1:-1]) >>> dai = dac[idx] # find maxima per object >>> mx = np.maximum.reduceat(dai, bnds[:-1]) # find their positions >>> am, = np.where(dai==mx.repeat(cnts[1:])) # translate positions back to coordinate space >>> im = idx[am] >>> am = *(n[im] for n in nz), >>> >>> # result # coordinates, note that there are more points than objects because # the maximum 4 occurs twice in object 1 >>> am (array([1, 0, 0]), array([1, 2, 5])) # maxima >>> data[am] array([4, 4, 2]) # labels >>> segments[am] array([1, 1, 2]) |