Flip horizontally an image in Python (JES)

*爱你&永不变心* 提交于 2019-12-31 01:28:30

问题


I need to make a function that will copy an image, but mirrored. I created the code to mirror the image, but it isn't working and I don't know why because I traced the code and it should be mirroring the image. Here's the code:

def invert(picture):
 width = getWidth(picture)
 height = getHeight(picture)

 for y in range(0, height):
   for x in range(0, width):
    sourcePixel = getPixel(picture, x, y)
    targetPixel = getPixel(picture, width - x - 1, height - y - 1)
    color = getColor(sourcePixel)
    setColor(sourcePixel, getColor(targetPixel))
    setColor(targetPixel, color)
 show(picture)
 return picture 

def main():
  file = pickAFile()
  picture = makePicture(file)
  newPicture = invert(picture)
  show(newPicture)

Can someone explain to me what is wrong? Thank you.


回答1:


Try this :

def flip_vert(picture):
    width = getWidth(picture)
    height = getHeight(picture)

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

    return picture 


def flip_horiz(picture):
    width = getWidth(picture)
    height = getHeight(picture)

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

    return picture 



回答2:


The problem is that you are looping across the whole image instead of only half of width. You mirror twice your image and get the same image as output as the one you input.

if you mirror across the Y axes the code should be

for y in range(0, height):
for x in range(0, int(width / 2)):


来源:https://stackoverflow.com/questions/17129189/flip-horizontally-an-image-in-python-jes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!