简体   繁体   中英

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM