Flipping Image Python

user3956566 picture user3956566 · Jul 3, 2013 · Viewed 19.4k times · Source

I am trying to flip an image horizontally.

From this:

Original Pic

To This:

Flipped Pic

But I keep getting it mirrored half way.

Like This:

Result I get

I am trying to reverse the x-axis index and I don't understand why it is being divided.

def flip(picture):
    height = getHeight(picture)
    width = getWidth(picture)
    newPicture = makeEmptyPicture(width, height)
    x2 = width-1
    for x in range(0, width):
        y2 = 0
        for y in range(0, height):
            pxl = getPixel(picture, x, y)
            newPxl = getPixel(picture, x2, y2)
            color = getColor(pxl)
            setColor(newPxl, color)
            y2 = y2+1
        x2 = x2-1
    return picture

The rest of my code:

def d():    
    f = pickAFile()
    picture = makePicture(f)        
    newPicture = copy(picture)        
    writePictureTo(newPicture, r"D:\FOLDER\newPic4.jpg")
    explore(newPicture)

Answer

Alfe picture Alfe · Jul 3, 2013
def flip(picture):
  height = getHeight(picture)
  width = getWidth(picture)
  newPicture = makeEmptyPicture(width, height)
  for x in range(width):
    for y in range(height):
      color = getColor(getPixel(picture, x, y))
      setColor(getPixel(newPicture, width-1-x, y), color)
  return newPicture

How about this? I just removed the x2/y2 stuff which didn't seem necessary to me. Otherwise it should work this way. I found no true bug in your code, just the returning of the picture instead of newPicture at the end. But that should not have lead to a mirroring either.