Skip to main content
 首页 » 编程设计

python之是否可以在虚拟开发环境中使用 matplotlib 打开图像

2024年10月01日6hnrainll

出于开发目的,我使用 Ubuntu Vagrant box(虚拟环境,无 GUI),我决定尝试使用 Python 进行一些图像识别,但是当我运行以下代码时无法打开图像:

# I'm not sure if I can/should do this import in the same file,  
# but it doesn't give me any errors ... 
import matplotlib 
matplotlib.use('Agg') 
 
from PIL import Image 
import numpy as np 
import matplotlib.pyplot as plt 
 
i = Image.open('images/dotndot.png') 
image_array = np.asarray(i) 
plt.imshow(image_array) 
plt.show() 

即:没有任何反应。没有错误,也没有图像。
所以我想知道我的虚拟开发环境是否是这里的罪魁祸首?

请您参考如下方法:

no GUI

好吧,这就是问题所在。窗口在 Vagrant 中悄然打开,你看不见它。

如果你坚持在 GUI 程序中使用 Vagrant,你需要在你的主机上设置一个 X 服务器,并将显示转发为 mentioned here

如果您需要带有 GUI 的 Linux 环境,只需设置一个带有完整桌面的普通 VM。
否则,如果您的编码主要是 Python,请使用本地 virtualenv