我有一个从形状为(m,n,3)
的文件中读取的图像(即它有 3 个通道(。我还有一个矩阵来转换尺寸为(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)
我在这里遇到的问题是只使用一个np.tensordot
,即消除对np.moveaxis
的需求。我花了几个小时试图找到解决方案(我猜它在于选择正确的axes
(,所以我想我会向其他人寻求帮助。
如果你image
第一个参数,你可以简洁地用tensordot
做到这一点:
np.tensordot(image, transform, axes=(-1, 1))
您可以使用参数optimize=True
从einsum
获得更好的性能(需要 numpy 1.12 或更高版本(:
np.einsum('ij,...j', transform, image, optimize=True)
或者(正如Paul Panzer在评论中指出的那样(,您可以简单地使用矩阵乘法:
image @ transform.T
它们在我的计算机上花费的时间大致相同。