Jython/Python - Flipping a picture horizontally

2.5k Views Asked by At

I'm trying to "cut" a picture in half and flip both sides horizontally. See link below.

https://i.stack.imgur.com/mg9Qg.jpg

Original picture:

enter image description here

What the output needs to be:

enter image description here

What I'm getting

enter image description here

This is what I have, but all it does is flip the picture horizontally

def mirrorHorizontal(picture):
  mirrorPoint = getHeight(picture)/2
  height = getHeight(picture)
  for x in range(0, getWidth(picture)):
    for y in range(0, mirrorPoint):
      topPixel = getPixel(picture, x, y)
      bottomPixel = getPixel(picture, x, height - y - 1)
      color = getColor(topPixel)
      setColor(bottomPixel, color)

So how do I flip each side horizontally so that so that it comes out looking like the second picture?

2

There are 2 best solutions below

5
On

One approach would be to define a function for flipping part of an image horizontally:

def mirrorRowsHorizontal(picture, y_start, y_end):
    ''' Flip the rows from y_start to y_end in place. '''
    # WRITE ME!

def mirrorHorizontal(picture):
    h = getHeight(picture)
    mirrorRowsHorizontal(picture, 0, h/2)
    mirrorRowsHorizontal(picture, h/2, h)

Hopefully, that gives you a start.

Hint: You may need to swap two pixels; to do this, you'll want to use a temporary variable.

0
On

One year later, I think we can give the answer :

def mirrorRowsHorizontal(picture, y_start, y_end):
    width = getWidth(picture)

    for y in range(y_start/2, y_end/2):
        for x in range(0, width):
            sourcePixel = getPixel(picture, x, y_start/2 + y)
            targetPixel = getPixel(picture, x, y_start/2 + y_end - y - 1)
            color = getColor(sourcePixel)
            setColor(sourcePixel, getColor(targetPixel))
            setColor(targetPixel, color)

def mirrorHorizontal(picture):
    h = getHeight(picture)
    mirrorRowsHorizontal(picture, 0, h/2)
    mirrorRowsHorizontal(picture, h/2, h)

Taken from vertical flip here.

Example with 3 stripes :

mirrorRowsHorizontal(picture, 0, h/3)
mirrorRowsHorizontal(picture, h/3, 2*h/3)
mirrorRowsHorizontal(picture, 2*h/3, h)

Before :

enter image description here

After :

enter image description here