python - 无法弄清楚如何编译所有内容并返回我的图像
问题描述
无法弄清楚如何编译所有内容并返回我的图像。
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() 的最终函数中编译。不过,每次我尝试运行它时,我都会遇到返回值 Picture 没有出现在最终 put_together 函数中的问题。我正在做最后一个函数,因为它都需要从一个函数中调用。所以这是我的问题。它只是不回来了。
解决方案
我不完全确定您要完成什么,但代码至少现在可以编译。我最终编辑了一些东西:
- 看起来你的组合函数是试图成为程序启动时运行的函数。因此它变成了主要的。
- 我好像你试图传递图片,所以我把它改成了这样做。
- 此外,我编辑了几个 for 循环的范围。鉴于范围必须从一个整数到另一个整数,我添加了舍入。目前它用于
ceil()
向上舍入值,但您可能希望使用floor()
向下舍入值 - 似乎您正在尝试编辑
unscramble_top
. 所以我编辑它这样做。最初,您有它,因此它试图迭代像素,这将不起作用,因为每个单独的 pizel 只有一个 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()