首页 文章

如何在Jupyter Notebook中显示文件中的图像?

提问于
浏览
123

我想使用IPython notebook作为交互式分析我使用Biopython的GenomeDiagram模块制作的一些基因组图表的方法 . 虽然有大量关于如何使用 matplotlib 在IPython笔记本中内联图形的文档,但是GenomeDiagram使用了ReportLab工具包,我认为它不支持IPython中的内联图形 .

然而,我想,解决这个问题的方法是将绘图/基因组图表写入文件,然后打开内联图像,这将具有相同的结果,如下所示:

gd_diagram.write("test.png", "PNG")
display(file="test.png")

但是,我无法弄清楚如何做到这一点 - 或者知道它是否可行 . 那么有人知道图像是否可以在IPython中打开/显示?

7 回答

  • 3

    this post提供,您可以执行以下操作:

    from IPython.display import Image
    Image(filename='test.png')
    

    official docs

  • 4

    如果您尝试在循环内以这种方式显示图像,则需要将Image构造函数包装在显示方法中 .

    from IPython.display import Image, display
    
    listOfImageNames = ['/path/to/images/1.png',
                        '/path/to/images/2.png']
    
    for imageName in listOfImageNames:
        display(Image(filename=imageName))
    
  • 3

    注意,直到现在发布的解决方案只适用于png和jpg!

    如果您希望在不导入更多库的情况下更容易,或者想要在Ipython Notebook中显示动画或非动画GIF文件 . 将要显示它的行转换为markdown并使用这个漂亮的短黑客!

    ![alt text](test.gif "Title")
    
  • 145

    感谢this页面,我发现上述建议没有:

    import PIL.Image
    from cStringIO import StringIO
    import IPython.display
    import numpy as np
    def showarray(a, fmt='png'):
        a = np.uint8(a)
        f = StringIO()
        PIL.Image.fromarray(a).save(f, fmt)
        IPython.display.display(IPython.display.Image(data=f.getvalue()))
    
  • 25

    您还可以使用PIL在Jupyter Notebook中显示图像文件:

    from PIL import Image
    path = "cats/cat0.jpg"
    display(Image.open(path))
    

    这也适用于循环 .

  • 220

    这将在Jupyter中导入并显示 .jpg 图像(在Anaconda环境中使用Python 2.7进行测试)

    from IPython.display import display
    from PIL import Image
    
    
    path="/path/to/image.jpg"
    display(Image.open(path))
    

    您可能需要安装PIL

    在Anaconda这是通过打字完成的

    conda install pillow
    
  • 0

    当使用 GenomeDiagram 和Jupyter(iPython)时,显示图像的最简单方法是将GenomeDiagram转换为PNG图像 . 这可以使用IPython.display.Image对象进行包装,以使其显示在笔记本中 .

    from Bio.Graphics import GenomeDiagram
    from Bio.SeqFeature import SeqFeature, FeatureLocation
    from IPython.display import display, Image
    gd_diagram = GenomeDiagram.Diagram("Test diagram")
    gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
    gd_feature_set = gd_track_for_features.new_set()
    gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
    gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
                    fragments=1, start=0, end=100)
    Image(gd_diagram.write_to_string("PNG"))
    

    [See Notebook]

相关问题