在Python(JES)中水平翻转图像

3

我需要制作一个函数来复制一张镜像的图片。我已经编写了镜像图片的代码,但它并不起作用,我也不知道为什么,因为我已经追踪代码,这应该是可以实现镜像图片的。下面是代码:

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)

请问有人能解释一下问题出在哪里吗?谢谢。


显示(图片)应缩进:show(picture),返回图片也应缩进:return picture - bozdoz
请将您的代码块更新为mirror;-),以反映您本地文件中的内容... - Gauthier Boaglio
不,但请修正您问题主体中的缩进,以免混淆了糟糕的缩进(点击底部的“编辑”链接)。 - Gauthier Boaglio
@Golgauth 不好意思,已经修复了!但是有一个奇怪的事情是,当我在y范围中将高度除以2时,它会水平和垂直翻转图片,但是当我将宽度除以2时也会发生同样的事情。我认为如果我在targetPixel中只使用高度而不是高度-y-1,它应该可以工作,但是当我这样做时我的IDE会报错。 - user2387191
@Golgauth 函数传参错误 - user2387191
显示剩余2条评论
2个回答

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 

这太奇怪了,因为我刚刚想出这个代码10分钟前哈哈。但它仍然可以垂直翻转图片,只是不能水平翻转。我试着调整它,但没有产生水平翻转。 - user2387191
好的,我找到了答案,对于x的范围应该是宽度的一半,目标像素应该是width - x - 1,y 谢谢你们的帮助! - user2387191

1
问题在于您遍历整个图像而不是仅限于宽度的一半。您对图像进行了两次镜像,得到的输出图像与输入图像相同。

如果要沿Y轴镜像,则代码应为

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

所以我需要更改 for x in range(0, width): 为 for x in range(0, width / 2): ? 如果是这样的话,当我尝试时,它会水平和垂直翻转图片。我只想水平翻转它。 - user2387191
1
如果您想水平翻转,则应跨越高度的一半。 - Alexandru Barbarosie
是的,但即使我这样做,它仍会给出相同的输出,就像我将宽度除以2一样。 - user2387191
好的,如果我不将任何一个范围除以二,它只会返回我输入的相同图像。如果我在y范围内将高度除以2,它会水平和垂直翻转图片。如果我将宽度除以2,它也会做同样的事情。我希望它只水平翻转图片。 - user2387191
@user2387191 我更新了我的答案。这有什么作用? - Gauthier Boaglio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接