我正在运行一个 python 脚本,但它不会显示图片。
我在这个程序的目录中有一个 apple.jpg 图像,它应该显示图片,但它没有。这是代码:
#!/usr/bin/env python
from PIL import Image
Apple = Image.open("apple.jpg")
Apple.show()
我的操作系统是 Ubuntu,这个程序刚刚完成,没有显示任何错误。
我正在运行一个 python 脚本,但它不会显示图片。
我在这个程序的目录中有一个 apple.jpg 图像,它应该显示图片,但它没有。这是代码:
#!/usr/bin/env python
from PIL import Image
Apple = Image.open("apple.jpg")
Apple.show()
我的操作系统是 Ubuntu,这个程序刚刚完成,没有显示任何错误。
它适用于我在 Ubuntu 上。它使用 Imagemagick 显示图像。试试这个:
sudo apt-get install imagemagick
我知道,这是一个老问题,但这是我在 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 应该在默认查看器中正确显示()图像。
这是一个老问题,但是,它困扰了我一段时间。这是我的解决方案:
我在 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()
正常工作(用于调试目的)。
我希望我在这里找到的内容可以对某人有所帮助,它对我有用。它解释了当默认查看器不接受命令行图像文件时,您可以使用 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)
对我有用的是:
brew install imagemagick
可能是您没有设置默认的图像查看器。尝试在程序之外打开图像文件,看看它是否要求您选择一个程序或只是在另一个程序中打开。
就我而言,我在 Windows 上使用 Ubuntu,使用 Pillow 时无法显示图像。
我们需要做两件事:
然后将以下设置添加到您的.bashrc
并获取它:
export DISPLAY=:0
现在,您应该能够看到成功显示的图像。
Mint19.3 的默认查看器是 xviewer(我不知道 Ubunutu 是否如此)您可以通过键入来确认您的系统:
xviewer /path/to/test_image.jpg
查看器应该启动
虽然我使用 xviewer 作为示例,但如果您知道从命令行启动它的命令,这种方法应该适用于任何查看器
通过键入which xviewer
,我知道 xviewer 位于:/usr/bin/xviewer
display
来确认。which diplay
如果它返回一个路径,那么您可能需要检查以确保另一个已安装的程序没有将该命令用于其他目的。要为 python 分配一个新的(不更改源代码),您可以使用符号链接分配display
给xviewer
:
sudo ln -T /usr/bin/xviewer /usr/bin/display
PIL 在这一点上几乎是废弃软件。您应该考虑使用它的后继者pillow
,可以通过 easy_install 或 pip 下载。
在 ubuntu 上,我建议如下:
sudo apt-get install python-pip
pip install pillow --user
从那里,您应该能够安装枕头并Image
以相同的方式使用它的类。