new recruit 21
new recruit 21

Reputation: 111

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)

Upvotes: 2

Views: 14107

Answers (2)

kindall
kindall

Reputation: 184455

You are going all the way across the image, but by the time you have got halfway across, you have already flipped the image. So in going the rest of the way across, you flip it back to the way it was.

So:

for x in range(width//2):

Upvotes: 4

John La Rooy
John La Rooy

Reputation: 304473

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):

Upvotes: 7

Related Questions