无法弄清楚如何编译所有内容并返回我的图像

时间:2018-11-27 22:24:58

标签: python python-3.x python-imaging-library

无法弄清楚如何编译所有内容并返回我的图像。

from PIL import Image

def open_bird():

    filename = 'bird_scrambled.png'             #Call File 
    picture = Image.open(filename)              #Opens file for use 

    return(picture)

def unscramble_left(picture):

    width, height = picture.size                #Call image size, log

    for x in range (0, (width/2)):              # width is /2 
        for y in range (0, height):             # height remains same
            red, green, blue = picture.getpixel((x,y)) # call pixels in x,y grid
            picture.putpixel((x,y), (blue,green,red))  # replace pixels rgb -> bgr

    return(picture)

def unscramble_top(picture):

    width, height = picture.size

    for x in range (0, (width/2)):
        for y in range (0, (height/2)):
            red, green, blue = picture.getpixel((x,y))
            for red in picture:
                if red >= 127:
                    red = red - 127
                else:
                    red = red + 127 
    picture.show()

def put_together():
    open_bird()
    unscramble_left(picture)
    unscramble_top(picture)

所以基本上,我想在每个函数中设置完初始功能后返回它。将照片通过unscramble_left()传递到unscramble_top;最后将其编译到put_together()的最终函数中。但是,每次我尝试运行此命令时,最终都会遇到在最终的put_together函数中未通过返回值Picture的问题。我正在执行最后一个函数,因为所有这些都需要从一个函数中调用。这就是我的问题。它只是不回来。

1 个答案:

答案 0 :(得分:0)

我不确定您要完成什么,但是代码至少现在可以编译。我最后编辑了几件事:

  • 似乎您放在一起的函数是试图成为程序启动时运行的函数。因此它变成了主要的。
  • 我好像您是在尝试传递图片,所以我将其更改为实际上是这样做的。
  • 此外,我编辑了几个for循环的范围。鉴于范围必须从一个整数到另一个整数,我添加了舍入。目前,它使用ceil()将值四舍五入,但您可能想使用floor()将值四舍五入
  • 您似乎正在尝试编辑unscramble_top中的每个像素。因此,我对此进行了编辑。最初,您拥有它是为了尝试遍历该像素,该像素将不起作用,因为每个像素都只有r的一个值,g的一个值和b的一个值。

代码

from PIL import Image
from math import ceil


def open_bird():
    filename = 'Image.jpeg'  # Call File
    picture = Image.open(filename)  # Opens file for use

    return picture


def unscramble_left(picture):
    width, height = picture.size  # Call image size, log

    for x in range(0, ceil(width / 2)):  # width is /2
        for y in range(0, height):  # height remains same
            red, green, blue = picture.getpixel((x, y))  # call pixels in x,y grid
            picture.putpixel((x, y), (blue, green, red))  # replace pixels rgb -> bgr

    return picture


def unscramble_top(picture):
    width, height = picture.size

    for x in range(0, ceil(width / 2)):
        for y in range(0, ceil(height / 2)):
            red, green, blue = picture.getpixel((x, y))
            if red >= 127:
                red = red - 127
            else:
                red = red + 127

    return picture


def main():
    picture = open_bird()
    picture = unscramble_left(picture)
    picture = unscramble_top(picture)
    picture.show()


if __name__ == '__main__':
    main()