如何有效地将阵列旋转±180°?

编程入门 行业动态 更新时间:2024-10-13 02:19:42
本文介绍了如何有效地将阵列旋转±180°?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于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°?

本文发布于:2023-11-30 00:07:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648059.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有效地   阵列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!