Mirror Image Diagonally in Python

user2054546 picture user2054546 · Feb 8, 2013 · Viewed 13.5k times · Source

I'm taking a programming class on python, and we're working on mirroring images by defining a mirror point and then copying a pixel from one side to the other using nested for loops. For example, mirroring an image vertically would use the following code:

def mirrorVertical(source):
 mirrorPoint = getWidth(source) / 2
 width = getWidth(source)
 for y in range(0,getHeight(source)):
   for x in range(0,mirrorPoint):
     leftPixel = getPixel(source,x,y)
     rightPixel = getPixel(source,width - x - 1,y)
     color = getColor(leftPixel)
     setColor(rightPixel,color)

I'm currently working on an assignment question asking us to mirror an image diagonally so that the top left side gets reflected onto the bottom right side. Every example and answer that I've found so far only works for square images, and I need to be able to apply this to any image, preferably by defining a diagonal mirror point. I've been trying to define the mirror point using a y = mx + b style equation, but I can't figure out how to tell Python to make that a line. Any help not specific to square images would be appreciated!

Note: since I'm brand new here, I can't post images yet, but the diagonal mirror point would run from the bottom left to the top right. The image in the top left triangle would be reflected to the bottom right.

Answer

bogatron picture bogatron · Feb 8, 2013

You can swap upper left with lower right of a non-square array like this:

height = getHeight(source)
width = getWidth(source)
for i in range(height - 1):
    for j in range(int(width * float(height - i) / height)):
        # Swap pixel i,j with j,i

This works for mirroring along the diagonal. You appear to imply that you may want to mirror along some arbitrary location. In that case, you will need to decide how to fill in pixels that don't have a matching pixel on the opposite side of the mirror line.

You mention you are working on an assignment so you probably are required to do the loops explicitly but note that if you put your data into a numpy array, you can easily (and more efficiently) achieve what you want with a combination of the numpy functions fliplr, flipud, and transpose.

Note also that in your code example (mirroring left/right), you are copying the left pixel to the right side, but not vice versa so you are not actually mirroring the image.