我有一张从文件中读取的图像,形状为 (m,n,3)(即它有 3 个 channel )。我还有一个矩阵来转换尺寸为 (3,3) 的颜色空间。我已经找到了几种不同的方法来将这个矩阵应用于图像中的每个向量;例如,
np.einsum('ij,...j',transform,image)
似乎与以下(慢得多)实现产生相同的结果。
def convert(im: np.array, transform: np.array) -> np.array:
""" Convert an image array to another colorspace """
dimensions = len(im.shape)
axes = im.shape[:dimensions-1]
# Create a new array (respecting mutability)
new_ = np.empty(im.shape)
for coordinate in np.ndindex(axes):
pixel = im[coordinate]
pixel_prime = transform @ pixel
new_[coordinate] = pixel_prime
return new_
但是,在使用 line_profiler 对示例图像进行测试时,我发现以下方法更加有效.
np.moveaxis(np.tensordot(transform, X, axes=((-1),(-1))), 0, 2)
我在这里遇到的问题是使用 just np.tensordot,即不再需要 np.moveaxis。我花了几个小时试图找到解决方案(我猜它在于选择正确的 axes),所以我想我应该向其他人寻求帮助。
请您参考如下方法:
如果您将 image 作为第一个参数,您可以使用 tensordot 简洁地完成此操作:
np.tensordot(image, transform, axes=(-1, 1))
通过使用参数 optimize=True(需要 numpy 1.12 或更高版本),您可以从 einsum 获得更好的性能:
np.einsum('ij,...j', transform, image, optimize=True)
或者(正如 Paul Panzer 在评论中指出的那样),您可以简单地使用矩阵乘法:
image @ transform.T
它们在我的电脑上花费的时间差不多。
