45

我正在运行一个 python 脚本,但它不会显示图片。

我在这个程序的目录中有一个 apple.jpg 图像,它应该显示图片,但它没有。这是代码:

#!/usr/bin/env python

from PIL import Image

Apple = Image.open("apple.jpg")
Apple.show()

我的操作系统是 Ubuntu,这个程序刚刚完成,没有显示任何错误。

4

9 回答 9

57

它适用于我在 Ubuntu 上。它使用 Imagemagick 显示图像。试试这个:

sudo apt-get install imagemagick
于 2013-04-29T13:36:39.913 回答
14

我知道,这是一个老问题,但这是我在 Ubuntu 中修复它的方法,以防有人遇到同样的问题并且不想安装 imagemagick(无论如何它都不能解决问题的根本原因)。

可以使用终端中的命令“eog”启动 Ubuntu 上的默认查看器。Pillow 默认只搜索命令“xv”和“display”,后者由 imagemagick 提供。因此,如果你安装了 imagemagick,调用“display”确实会打开图像。但是为什么不使用我们已经拥有的查看器呢?

打开查看器的 Python 代码可以在 lib/python3.4/site-packages/PIL/ImageShow.py (或 Python 安装的等价物)中找到。向下滚动到第 155 行下面,找到代码块:

class DisplayViewer(UnixViewer):
    def get_command_ex(self, file, **options):
        command = executable = "display"
        return command, executable

if which("display"):
    register(DisplayViewer)

复制该块并将其粘贴到正下方,将“display”命令更改为 Ubuntu 的“eog”命令:

class DisplayViewer(UnixViewer):
    def get_command_ex(self, file, **options):
        command = executable = "eog"
        return command, executable

if which("eog"):
    register(DisplayViewer)

保存 ImageShow.py 后,Pillow 应该在默认查看器中正确显示()图像。

于 2015-01-21T14:39:38.127 回答
5

这是一个老问题,但是,它困扰了我一段时间。这是我的解决方案:

我在 Linux Mint 上运行 Python 2.7,调用时Image.show()没有任何反应。在我的系统上,默认查看器是“Image Viewer”,在 bash 中称为“eog”。我的 Python 认为我使用了其他东西,可能是“xv”。所以,打开一个终端并运行

sudo gedit /usr/lib/python2.7/dist-packages/PIL/ImageShow.py

搜索“xv”并将其替换为“eog”。

保存文件并Image.show()正常工作(用于调试目的)。

于 2015-07-23T19:09:40.710 回答
3

我希望我在这里找到的内容可以对某人有所帮助,它对我有用。它解释了当默认查看器不接受命令行图像文件时,您可以使用 webbrowser 模块显示图像:

import Image

# Apple = Image.open("apple.jpg")    
# Apple.show()
# instead of using .open and .show(), 
# save the image to show it with the webbrowser module

filename = "apple.jpg"
import webbrowser
webbrowser.open(filename)
于 2015-05-11T13:45:07.757 回答
2

对我有用的是:

brew install imagemagick
于 2018-01-25T18:10:06.120 回答
0

可能是您没有设置默认的图像查看器。尝试在程序之外打开图像文件,看看它是否要求您选择一个程序或只是在另一个程序中打开。

于 2013-04-29T13:39:56.123 回答
0

就我而言,我在 Windows 上使用 Ubuntu,使用 Pillow 时无法显示图像。

我们需要做两件事:

  1. 在您的 Windows 上安装 X 服务器,例如xming
  2. 按照@Lennart Regebro 的建议,在 Windows 上的 Ubuntu 中安装图像查看器(不是在 Windows 上,这很重要!),例如imagemagick 。

然后将以下设置添加到您的.bashrc并获取它:

export DISPLAY=:0

现在,您应该能够看到成功显示的图像。

于 2019-02-15T08:21:33.780 回答
0

Mint19.3 的默认查看器是 xviewer(我不知道 Ubunutu 是否如此)您可以通过键入来确认您的系统: xviewer /path/to/test_image.jpg 查看器应该启动

虽然我使用 xviewer 作为示例,但如果您知道从命令行启动它的命令,这种方法应该适用于任何查看器

通过键入which xviewer,我知道 xviewer 位于:/usr/bin/xviewer

  • 如果您在此页面上,我认为当前未分配,您可以通过检查没有返回任何内容display来确认。which diplay如果它返回一个路径,那么您可能需要检查以确保另一个已安装的程序没有将该命令用于其他目的。

要为 python 分配一个新的(不更改源代码),您可以使用符号链接分配displayxviewer

sudo ln -T /usr/bin/xviewer /usr/bin/display

于 2020-05-25T08:26:07.737 回答
-2

PIL 在这一点上几乎是废弃软件。您应该考虑使用它的后继者pillow,可以通过 easy_install 或 pip 下载。

在 ubuntu 上,我建议如下:

  1. 如果您还没有 pip,请通过 apt-get 安装它: sudo apt-get install python-pip
  2. 安装枕头: pip install pillow --user

从那里,您应该能够安装枕头并Image以相同的方式使用它的类。

于 2013-04-29T13:58:21.267 回答