Jython/Python - 将图片水平翻转

3

我正在尝试将一张图片“切”成两半并水平翻转两侧。请参见下面的链接。

http://imgur.com/a/FAksh

原始图片:

enter image description here

输出需要是什么:

enter image description here

我得到的是

enter image description here

这是我所拥有的,但它只能将图片水平翻转。
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)

那么我该如何水平翻转每一面,使其看起来像第二张图片呢?


你正在使用哪个图片处理模块?(提供 getPixelsetColor 和其他方法的是什么?) - jsbueno
几乎可以肯定是 JES。 - nneonneo
逻辑不太对,但从一开始就有一个看起来不对的地方:你修改了一个像素,然后修改它的对应像素,而当 Python 到达那里时,它实际上是自己。假设你有两个像素,topbottom。在一次迭代中,你将修改 top,将其分配给 bottom。然后,当你到达 bottom 时,你尝试将其设置为 top 的颜色,只是现在 top bottom。因此,你的图片将有一半未被修改。避免这种情况的简单方法是创建一个具有相同尺寸的不同图像,并将原始图像映射到该图像上。 - NullUserException
2个回答

1
一种方法是定义一个函数来水平翻转图像的一部分:
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)

希望这能给你一个开始。
提示:您可能需要交换两个像素;为此,您需要使用一个临时变量。

我认为这个问题和我在评论中指出的一样。 - NullUserException
1
我假设图片需要进行原地修改(这需要交换)。如果 OP 可以创建新的图像,则创建一个新的图像并填充它会更容易。 - nneonneo
我认为这个方法会起作用,但是我需要函数仅接受一个输入,该输入为图片。哦,而且我不太熟悉交换图片。我只是试图将其编辑为所需输出。 - John Calzone
“mirrorHorizontal” 只需要一个输入参数。 “mirrorRowsHorizontal” 是一个辅助函数。 - nneonneo
没关系,我还是想不出来。@nneonneo,你能再给我一点提示吗?我感觉自己太蠢了,怎么都想不明白。 - John Calzone

0
一年后,我认为我们可以给出答案:
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)

从垂直翻转这里获取。

带有3条纹的示例:

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

之前:

enter image description here

之后:

enter image description here


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