【问题标题】:Flip horizontally an image in Python (JES)在 Python (JES) 中水平翻转图像
【发布时间】:2013-06-16 00:33:02
【问题描述】:

我需要创建一个可以复制图像的函数,但是是镜像的。我创建了镜像镜像的代码,但它不起作用,我不知道为什么,因为我跟踪了代码,它应该镜像镜像。代码如下:

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 应该缩进
  • 请将您的代码块更新为mirror ;-) 您在本地文件中的内容...
  • @boazdoz 当我这样做时,它会给我一个错误,试图将参数传递给函数。
  • @Golgauth 我不知道你的意思......我正在学习的这门课程是为初学者准备的 jython,所以如果这就是你所指的,我还没有被介绍过任何 python API .
  • 不,但要修复问题正文中的缩进,这样我们就不会与不良缩进混淆(点击底部的edit 链接)

标签: python jython flip mirror jes


【解决方案1】:

试试这个:

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 分钟前才想出那个代码哈哈。但它仍然垂直翻转图片,而不是水平翻转。我试着摆弄它,但它没有产生水平翻转。
  • 好吧,我找到了答案,因为范围内的 x 应该是 width / 2,而 targetPixel 应该有 width - x - 1,谢谢你们的帮助!
【解决方案2】:

问题是您循环遍历整个图像,而不是仅一半宽度。您将图像镜像两次,并获得与您输入的图像相同的输出图像。

如果你在 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): ?如果是这样,当我尝试它时,它会水平和垂直翻转图片。我只想水平翻转它
  • 如果你想水平翻转它应该穿过一半的高度。
  • 是的,但即使我这样做,它也会给我同样的输出,如果我将宽度除以 2 会发生什么。
  • 好的,所以如果我不将任一范围除以二,它只会吐回我输入的同一张图像。如果我在 y 范围内将高度除以 2,它会水平和垂直翻转图片。如果我将宽度除以 2,它会做同样的事情。我想要它让图片只水平翻转。
  • @user2387191 更新了我的答案。这给了什么?
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2019-10-18
  • 2019-11-26
  • 2011-06-09
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多