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

2024-05-17 13:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要做一个功能,将复制一个图像,但镜像。我创建了镜像代码,但它不起作用,我不知道为什么,因为我跟踪了代码,它应该镜像图像。代码如下:

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)

有人能告诉我怎么了吗?谢谢您。


Tags: 代码in图像for镜像defrangewidth
2条回答

试试这个:

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 

问题是你在整个图像中循环,而不是只有一半的宽度。镜像两次图像,得到与输入图像相同的输出图像。

如果你在Y轴上镜像,代码应该是

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

相关问题 更多 >