import numpy as np channels_last = np.random.random((150, 150, 40)) channels_first = np.random.random((40, 150, 150)) def gradient_channels_first(image_data): g = np.empty((image_data.shape[0] * 2,) + image_data.shape[1:]) for i in xrange(image_data.shape[0]): gx, gy = np.gradient(image_data[i]) g[2 * i] = gx g[2 * i + 1] = gy return g def gradient_channels_last(image_data): g = np.empty(image_data.shape[:2] + (image_data.shape[2] * 2,)) for i in xrange(image_data.shape[2]): gx, gy = np.gradient(image_data[..., i]) g[..., 2 * i] = gx g[..., 2 * i + 1] = gy return g %timeit gradient_channels_first(channels_first) %timeit gradient_channels_last(channels_last)