【问题标题】:I'm trying to display an image in Python 3.7.0 using Jupyter Notebook. Why isn't it working?我正在尝试使用 Jupyter Notebook 在 Python 3.7.0 中显示图像。为什么它不起作用?
【发布时间】:2019-05-15 09:38:34
【问题描述】:

图片名为“pythontest.png”。我正在尝试使用以下代码显示图像:

from IPython.display import Image
img = 'pythontest.png'
Image(url=img)
print(Image)

但是当我运行程序时它只是显示:

<class 'IPython.core.display.Image'>

这是什么意思,如何让它显示实际图像?谢谢。

【问题讨论】:

  • 我刚刚尝试过,但它仍然显示 。还有其他建议吗?
  • 尝试删除print(Image)这一行。 Image(url=img) 应该处理笔记本中的显示。 (并且笔记本默认只显示最后一个值)。
  • @S.Naj 如果您想在循环或其他内容中显示它,请使用image_instance = Image(url=img) display(image_instance)
  • 还是不行。不知道为什么。

标签: python python-3.x jupyter-notebook jupyter


【解决方案1】:

还有一个使用Matplotlib的替代方法

Matplotlib 是 Python 编程语言及其数值数学扩展 NumPy 的绘图库

import matplotlib.pyplot as plt #for showing the image
import matplotlib.image as mpimg #for reading the image
import numpy as np #just to be safe...lol
%matplotlib inline
#the above is a magic function to have images show in your notebook

image = mpimg.imread('pythontest.png') #loading/reading the image

plt.imshow(image) #displaying the image

【讨论】:

    【解决方案2】:

    假设图像存储在 pics 文件夹中。这对我有用:

    from IPython.display import Image
    import os
    
    Image(filename=os.path('pics', 'pythontest.png'))
    

    【讨论】:

    • 这不起作用,因为它说“名称'os'未定义'。我在Mac上使用Python 3.7.0。还有其他建议吗?
    • 别忘了导入模块“os”
    【解决方案3】:

    您的打印语句已打印您的图像的类型类别。要在 Jupiter notebook 中显示图像,只需将原始代码更改为以下内容:

    from IPython.display import Image
    imgUrl = 'pythontest.png'            # setup path and filename
    img = Image(url=imgUrl)              # create the image object
    img                                  # display the image
    

    此代码适用于我的 Python 3.7 设置。不确定与其他版本的兼容性。

    【讨论】:

      猜你喜欢
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      相关资源
      最近更新 更多