Python:沿垂直轴镜像图像的最有效方法 [英] Python: most efficient way to mirror an image along its vertical axis

查看:109
本文介绍了Python:沿垂直轴镜像图像的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多图像(需要即时翻转),因此我正在寻找使用Python做到这一点的最快方法.

I have a lot of images that I will need to flip (on the fly) and so am looking for the fastest way possible to do this using Python.

最有效的方法是什么?

我在磁盘上有映像文件,并尝试了一些方法,下面在我自己的答案中显示了这些文件,但是这些文件以Numpy数组开头,因此可能不是最佳选择.有更好的方法吗?

I have image files on disk and have tried to ways, shown in my own answer below, but these start with Numpy arrays and so may not be optimal. Are there better ways?

推荐答案

您可以简单地使用slicing翻转倒数第二个轴,以使等效的翻转视图进入图像输入数组,这样就不会创建任何图像内存中的新数据,因此是一种高效的数据,就像这样-

You can simply use slicing to flip the second last axis to get equivalent flipped view into the input array of images, as such won't be creating any new data in memory and hence an efficient one, like so -

images[...,::-1,:]

如果您仍然需要进行复制,请在此处使用.copy,它仍然比np.fliplr更有效,并且在较小/适当大小的阵列中很明显.

If you still need to make a copy, use .copy there, which would still be more efficient than np.fliplr and noticeable with small/decent sized arrays.

运行时测试-

NumPy似乎是赢家,所以我将与那个人进行比较.

It seems NumPy is the winner, so I will test it out against that one.

In [64]: images = np.random.randint(0,255,(3,200,400,3))

In [65]: out1 = np.array([np.fliplr(images[i]) for i in range(3)])

In [66]: out2 = images[...,::-1,:]

In [67]: np.allclose(out1, out2)
Out[67]: True

In [68]: %timeit np.array([np.fliplr(images[i]) for i in range(3)])
1000 loops, best of 3: 1.38 ms per loop

In [69]: %timeit images[...,::-1,:]
1000000 loops, best of 3: 259 ns per loop # virtually free

如果您需要复制-

In [76]: images = np.random.randint(0,255,(3,10,10,3))

In [77]: %timeit np.array([np.fliplr(images[i]) for i in range(3)])
100000 loops, best of 3: 5.76 µs per loop

In [78]: %timeit images[...,::-1,:].copy()
100000 loops, best of 3: 2.23 µs per loop

In [79]: images = np.random.randint(0,255,(3,100,100,3))

In [80]: %timeit np.array([np.fliplr(images[i]) for i in range(3)])
10000 loops, best of 3: 159 µs per loop

In [81]: %timeit images[...,::-1,:].copy()
10000 loops, best of 3: 152 µs per loop

这篇关于Python:沿垂直轴镜像图像的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆