numpy - python, dimension subset of ndimage using indices stored in another image -


i have 2 images following dimensions, x, y, z:

img_a: 50, 50, 100

img_b: 50, 50

i'd reduce z-dim of img_a 100 1, grabbing value coincide indices stored in img_b, pixel pixel, indices vary throughout image.

this should result in third image dimension:

img_c: 50, 50

is there function dealing issue?

thanks, peter

ok updated vectorized method.

here duplicate question solution doesn't work when row , column dimensions not same size.

the code below has method added explicitly creates indices purposes numpy.indices() , loop logic in vectorized way. it's slower (2x) numpy.meshgrid() method think it's easier understand , works unequal row , column sizes.

the timing approximate on system get:

meshgrid time: 0.319000005722 indices time: 0.704999923706 loops time: 13.3789999485 

-

import numpy np import time   x_dim = 5000 y_dim = 5000 channels = 3  # base data = np.random.randint(1, 1000, (x_dim, y_dim, channels)) b = np.random.randint(0, channels, (x_dim, y_dim))   # meshgrid method (from here https://stackoverflow.com/a/27281566/377366 ) start_time = time.time() i1, i0 = np.meshgrid(xrange(x_dim), xrange(y_dim), sparse=true) c_by_meshgrid = a[i0, i1, b] print('meshgrid time: {}'.format(time.time() - start_time))  # indices method (this vectorized method want) start_time = time.time() b_indices = np.indices(b.shape) c_by_indices = a[b_indices[0], b_indices[1], b[b_indices[0], b_indices[1]]] print('indices time: {}'.format(time.time() - start_time))  # loops method start_time = time.time() c_by_loops = np.zeros((x_dim, y_dim), np.intp) in xrange(x_dim):     j in xrange(y_dim):         c_by_loops[i, j] = a[i, j, b[i, j]] print('loops time: {}'.format(time.time() - start_time))   # confirm correctness print('meshgrid method matches loops: {}'.format(np.all(c_by_meshgrid == c_by_loops))) print('loop method matches loops: {}'.format(np.all(c_by_indices == c_by_loops))) 

Comments