2

我需要水平翻转图片,不使用反向功能,我以为我做对了,但返回的图像只是图片的右下角,它没有翻转。

我的代码是

def Flip(image1, image2):
    img = graphics.Image(graphics.Point(0, 0), image1)
    X = img.getWidth()
    Y = img.getHeight()
    for y in range(Y):
        for x in range(X):
            A = img.getPixel(x,y)
            r = A[0]
            g = A[1]
            b = A[2]
            color = graphics.color_rgb(r,g,b)
            img.setPixel(X-x,y,color)
    img = graphics.Image(graphics.Point(0,0), image2)
    win = graphics.GraphWin(image2, img.getWidth(), img.getHeight())
    img.draw(win)

我哪里做错了?

4

1 回答 1

2

这里有一些我认为可以改进的地方:

def Flip(image1, image2):
    img = graphics.Image(graphics.Point(0, 0), image1)
    X = img.getWidth()
    Y = img.getHeight()
    for y in range(Y):
        for x in range(X):
            A = img.getPixel(x,y)
            r = A[0]
            g = A[1]
            b = A[2]
            color = graphics.color_rgb(r,g,b)

这个任务可能更pythonic

            r, g, b = img.getPixel(x,y)
            color = graphics.color_rgb(r,g,b)

            img.setPixel(X-x,y,color)

img现在图像被翻转了一半。发生这种情况是因为您在同一图像源上编写内容,任何时候都会丢失旧内容,直到您到达中间。(请注意,这X-x会将图像大小增加 1 个像素。如果图像宽度为 100,在第一次迭代中X-x = 100 - 0 = 100,因为它从 0 开始,所以图像会变宽 1 个像素。)然后,您开始复制回来。此外,您不使用该内容是因为:

    img = graphics.Image(graphics.Point(0,0), image2)

这就是问题所在:您只是覆盖了 的内容而img没有给予任何使用。之后:

    win = graphics.GraphWin(image2, img.getWidth(), img.getHeight())
    img.draw(win)

这似乎与函数的目的(翻转图像)无关。我会做的是:

import graphics
import sys

def Flip(image_filename):
    img_src = graphics.Image(graphics.Point(0, 0), image_filename)
    img_dst = img_src.clone()
    X, Y = img_src.getWidth(), img_src.getHeight()
    for x in range(X):
        for y in range(Y):
            r, g, b = img_src.getPixel(x, y)
            color = graphics.color_rgb(r, g, b)
            img_dst.setPixel(X-x-1, y, color)

    return img_dst

if __name__ == '__main__':
    input = sys.argv[1] or 'my_image.ppm'
    output = 'mirror-%s' % input
    img = Flip (input)
    img.save(output)

请注意,该功能Flip只负责翻转图像,在功能之外您可以做任何您需要图像的事情,正如您在“主”程序中看到的那样。

如果您只想使用一张图像,则可能且效率更高。为此,您可以使用相同的原则在变量之间交换值:

def Flip(image_filename):
    img = graphics.Image(graphics.Point(0, 0), image_filename)
    X, Y = img.getWidth(), img.getHeight()
    for x in range(X/2):
        for y in range(Y):
            r_1, g_1, b_1 = img.getPixel(x, y)
            color_1 = graphics.color_rgb(r_1, g_1, b_1)

            r_2, g_2, b_2 = img.getPixel(X-x-1, y)
            color_2 = graphics.color_rgb(r_2, g_2, b_2)

            img.setPixel(X-x-1, y, color_1)
            img.setPixel(x, y, color_2)

    return img
于 2013-04-15T01:25:03.110 回答