Search code examples
pythonimagefor-loopflip

Python - Flip Image Horizontally Using For Loop


I'm trying to flip an image horizontally pixel-by-pixel using for-loops. If possible try to correct what I've got, rather than providing a completely different approach (even if more efficient or pythonic), to help me and others learn from my mistakes. Thanks for any help.

def flip(img):
   width = img.size[0]
   height = img.size[1]
   for y in range(height):
       for x in range(width):
           left = img.getpixel((x, y))
           right = img.getpixel((width - 1 - x, y))
           img.putpixel((width - 1 - x, y), left)
           img.putpixel((x, y), right)

Solution

  • You need to stop half way along the X axis. Otherwise you swap all the pixels back to their original positions.

       for x in range(width // 2):