【发布时间】:2020-10-30 13:08:45
【问题描述】:
我想旋转图像。
start 和 normal 的形状是 (429, 1024, 3) 腐烂的形状是 (3, 3) 以下代码运行正常,但需要一些时间才能完成。
#rotation 30 degree
s = numpy.sin(numpy.pi * 30 / 180)
c = numpy.cos(numpy.pi * 30 / 180)
rot = [[1.0, 0.0, 0.0],
[0.0, c, s],
[0.0, -s, c]]
for i in range(height):
for j in range(width):
for arr in [start, norm]:
x = arr[i,j,0]
y = arr[i,j,1]
z = arr[i,j,2]
for d in range(3):
arr[i,j,d] = rot[d][0] * x + rot[d][1] * y + rot[d][2] * z
我尝试对代码进行矢量化,但有条件使用 numpy.einsum 作为每个像素的矢量需要相乘。
#Moving 30 degree
s = numpy.sin(numpy.pi * 30 / 180)
c = numpy.cos(numpy.pi * 30 / 180)
rot = numpy.array([[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]])
start[:,:,:3] = numpy.einsum('ij,j',rot[:3,0],start[:,:,0]) +
numpy.einsum('ij,j',rot[:3,1],start[:,:,1]) + numpy.einsum('ij,j',rot[:3,2],start[:,:,2])
norm[:,:,:3] = numpy.einsum('ij,j',rot[:3,0],norm[:,:,0]) +
numpy.einsum('ij,j',rot[:3,1],norm[:,:,1]) + numpy.einsum('ij,j',rot[:3,2],norm[:,:,2])
上面的代码给出了错误“einstein sum subscripts string contains too many subscripts for operand 0”。
我应该对矢量化形式的代码做哪些更改??
【问题讨论】:
-
这不是
start.dot(rot)的一种非常复杂的做法吗? -
这看起来不像传统意义上的图像旋转。它会旋转颜色空间中单个像素的颜色。
-
好收获@QuangHoang
-
rot[:3,0]是一维数组,因此您不能指定ij作为其下标。einsum不“知道”rot是 2d,它只看到索引的结果。start[:,:,0]是 2d,因此仅在下标j上不起作用。使用einsum时,索引表达式必须与参数兼容。密切关注!