1

我有两个具有以下尺寸的图像,x,y,z:

img_a: 50, 50, 100

img_b: 50, 50

我想将 img_a 的 z-dim 从 100 减少到 1,只获取与存储在 img_b 中的索引一致的值,逐个像素,因为索引在整个图像中有所不同。

这应该会产生具有以下尺寸的第三张图像:

img_c: 50, 50

是否已经有处理此问题的功能?

谢谢,彼得

4

1 回答 1

0

好的,用矢量化方法更新。

是一个重复的问题,但是当行和列的尺寸不同时,解决方案目前不起作用。

下面的代码具有我添加的方法,该方法显式创建索引以用于查找目的,numpy.indices()然后执行循环逻辑,但以矢量化方式。它比该方法稍慢(2x),numpy.meshgrid()但我认为它更容易理解,并且它也适用于不相等的行和列大小。

时间是近似的,但在我的系统上我得到:

Meshgrid time: 0.319000005722
Indices time: 0.704999923706
Loops time: 13.3789999485

-

import numpy as np
import time


x_dim = 5000
y_dim = 5000
channels = 3

# base data
a = 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 is the vectorized method that does what you 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)
for i in xrange(x_dim):
    for 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)))
于 2015-09-26T11:02:47.803 回答