【发布时间】:2017-03-22 23:50:14
【问题描述】:
我有一个 3D 数组(一个 2D 向量数组),我想用一个旋转矩阵来转换其中的每个向量。旋转位于两个独立的 2D 弧度角度值数组中,称为 cols 和 rows。
我已经能够让 NumPy 为我计算角度,而无需 Python 循环。现在我正在寻找一种让 NumPy 也生成旋转矩阵的方法,希望能极大地提升性能。
size = img.shape[:2]
# Create an array that assigns each pixel the percentage of
# the correction (value between -1 and 1, distributed linearly).
cols = np.array([np.arange(size[1]) for __ in range(size[0])]) / (size[1] - 1) * 2 - 1
rows = np.array([np.arange(size[0]) for __ in range(size[1])]).T / (size[0] - 1) * 2 - 1
# Atan distribution based on F-number and Sensor size.
cols = np.arctan(sh * cols / (2 * f))
rows = np.arctan(sv * rows / (2 * f))
### This is the loop that I would like to remove and find a
### clever way to make NumPy do the same operation natively.
for i in range(size[0]):
for j in range(size[1]):
ah = cols[i,j]
av = rows[i,j]
# Y-rotation.
mat = np.matrix([
[ np.cos(ah), 0, np.sin(ah)],
[0, 1, 0],
[-np.sin(ah), 0, np.cos(ah)]
])
# X-rotation.
mat *= np.matrix([
[1, 0, 0],
[0, np.cos(av), -np.sin(av)],
[0, np.sin(av), np.cos(av)]
])
img[i,j] = img[i,j] * mat
return img
有没有什么巧妙的方法来重写 NumPy 操作中的循环?
【问题讨论】:
-
其中一个旋转矩阵应该使用
av? -
@kennytm 没错,感谢您发现此错误!
标签: python arrays numpy matrix