Image 在Jupyter笔记本中输出图像

Image 在Jupyter笔记本中输出图像,image,scipy,ipython,jupyter,Image,Scipy,Ipython,Jupyter,以下代码能够打印/输出Jupyter笔记本中预期的图像: from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" from IPython import display from scipy.misc import toimage import numpy as np n = 3 for _ in range(n): (toima

以下代码能够打印/输出Jupyter笔记本中预期的图像:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython import display
from scipy.misc import toimage
import numpy as np

n = 3
for _ in range(n):
    (toimage(np.random.rand(32, 32, 3)))
    print("----------------------------")
但是,一旦我将其放入函数中,它就会停止工作。为什么?我怎样才能修好它

def print_images(n=3):
    for _ in range(n):
        (toimage(np.random.rand(32, 32, 3)))
        print("----------------------------")

print_images()

display.display\u png
works:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython import display
from scipy.misc import toimage
import numpy as np

n = 3
for _ in range(n):
    display.display_png(toimage(np.random.rand(32, 32, 3)))
    print("----------------------------")

def print_images(n=3):
    for _ in range(n):
        display.display_png(toimage(np.random.rand(32, 32, 3)))
        print("----------------------------")

print_images()
你可以阅读更多关于为什么这种方法有效,而另一种方法在未来失败的信息

细节
toimage
返回的对象有一个
\u repr\u png\u
方法。这就是笔记本电脑用来产生你实际看到的图像的功能。无论出于何种原因(我相信你可以通过挖掘文档来发现),只要调用
toimage
在单元格顶部范围内生成任何实例
x
,笔记本就会自动调用
x.\u repr\u png()
。但是,如果
toimage
在嵌套更深的范围内运行,则不会自动调用
\u repr\u png\u
。相反,你必须通过显式调用
display来手动使用相同的显示机制。display\u png

我用它来编写一个用于图像机器学习的函数,当我不能进行函数编程时,我讨厌它。但现在我可以了,多亏了你。