对于C语言和派生类(Python,Cython,纯C语言),使用最少的内存和操作,将非正方形M×N数组绕其中心旋转180°的最佳算法是什么?
What is the best algorithm to rotate a non-square M×N array by 180° around its center, using the least memory and operations, for C langages and derivatives (Python, Cython, pure C) ?
推荐答案假定out是array,M和N的行号和列号的初始化副本,并且我们正在使用语言索引从0到(M-1)和(N-1)的数组:
Assuming out is an initialized copy of array, M and N their rows and columns numbers, and we are using a language indexing arrays from 0 to (M-1) and (N-1) :
在Python中:
def rotate_180(array, M, N, out): for i in range(M): for j in range(N): out[i, N-1-j] = array[M-1-i, j]这在4000×3000的阵列上花费了5.82秒.
This takes 5.82 s on a 4000×3000 array.
在使用Memviews的并行Cython + OpenMP中:
In parallelized Cython + OpenMP using Memviews :
cdef void rotate_180(float[:, :] array, int M, int N, float[:, :] out) nogil: cdef size_t i, j with parallel(num_threads=8): for i in prange(M): for j in range(N): out[i, N-1-j] = array[M-1-i, j]这在4000×3000的阵列上需要5.45 s.
This takes 5.45 s on a 4000×3000 array.
相比之下,使用np.rot90(array, 2)的numpy耗时8.58 µs.
In comparison, numpy with np.rot90(array, 2) takes 8.58 µs.
为避免一切皆知,这就是它的作用:
a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) rotate_180(a, 3, 3, b) b = array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) np.rot90(a, 2) out = array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])所以这确实是180°旋转.
So this is indeed a 180° rotation.
np.flip(a, 0) out = array([[7, 8, 9], [4, 5, 6], [1, 2, 3]])是沿最后一行的对称性,而不是旋转.
is a symmetry along the last line, not a rotation.
np.flip(np.flip(a, 1), 0) out = array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])也是180°旋转.
所以,是的,谢谢你,我的代码按照它说的做.
So, yes, thank you, my code does what it says.
更多推荐
如何有效地将阵列旋转±180°?
发布评论