Flip (reverse) image vertically given its string?

Question:

So I have a string of RGBA image data, each pixel is a byte long. I know the image’s x and y resolution too. Now I want to edit the string in a way which would cause the image to be flipped or reversed vertically, which means have the first “row” of pixels become the last row and the opposite, and like this for all other “rows”. Is there a fast way to do it?

Asked By: user975135

||

Answers:

say you have the image in array img, then do

img.reverse();
#also need to flip each row
for row in img:
  row.reverse();
Answered By: Adithya Surampudi

To do what you want to the letter this is one way to proceed:

>>> 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'

HOWEVER, unless you have very small images, you would be better off passing through numpy, as this is at the very minimum an order of magnitude faster than Cpython datatypes. You should look at at the flipup function. Example:

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

EDIT: thought to add a complete example in case you have never worked with NumPy before. Of course the conversion is worth only for images that are not 2×2, as instantiating the array has an overhead….

>>> 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]])
Answered By: mac