给定字符串,如何垂直翻转图像?

3 投票
2 回答
2579 浏览
提问于 2025-04-17 06:38

我有一串RGBA格式的图像数据,每个像素占用一个字节。我也知道图像的宽度和高度。现在我想对这串数据进行编辑,让图像上下翻转,也就是说,把第一行的像素变成最后一行,反之亦然,其他行也这样处理。有没有什么快速的方法可以做到这一点?

2 个回答

0

假设你有一个叫做 img 的数组,接下来你可以这样做:

img.reverse();
#also need to flip each row
for row in img:
  row.reverse();
5

要实现你想要的效果,这里有一种方法:

>>> img = 'ABCDEFGHIJKL'
>>> x, y = 4, 3
>>> def chunks(l, n):
...     for i in xrange(0, len(l), n):
...         yield l[i:i+n]
... 
>>> [row for row in chunks(img, x)]
['ABCD', 'EFGH', 'IJKL']
>>> ''.join(reversed([row for row in chunks(img, x)]))
'IJKLEFGHABCD'

不过,除非你的图片非常小,否则你最好使用numpy,因为这比Cpython的数据类型快很多倍。你可以看看flipup这个函数。举个例子:

>>> A
array([[ 1.,  0.,  0.],
       [ 0.,  2.,  0.],
       [ 0.,  0.,  3.]])
>>> np.flipud(A)
array([[ 0.,  0.,  3.],
       [ 0.,  2.,  0.],
       [ 1.,  0.,  0.]])

补充:我想加一个完整的例子,以防你之前没有使用过NumPy。当然,转换只对不是2x2的图片有意义,因为创建数组会有额外的开销……

>>> import numpy as np
>>> img = [0x00, 0x01, 0x02, 0x03]
>>> img
[0, 1, 2, 3]
>>> x = y = 2
>>> aimg = np.array(img).reshape(x, y)
>>> aimg
array([[0, 1],
       [2, 3]])
>>> np.flipud(aimg)
array([[2, 3],
       [0, 1]])

撰写回答