在Python中浏览并显示图像文件

时间:2015-07-16 12:26:21

标签: python image matplotlib

我正在尝试编写一个简单的Python函数,它打开一个图像文件并在窗口中显示它。 我需要能够浏览我的文件,但我无法找到修复我得到的一些错误。

这是代码:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
import numpy as np
import pywt as pw
import tkFileDialog as tk
from PIL import Image

def fct(fisier):
    img = mpimg.imread(fisier)
    arr=np.array(img, dtype=np.float)
    plt.imshow(arr, cmap=cm.Greys_r)
    plt.show()
    print(arr)
    return arr, img
file = tk.askopenfile(initialdir='C:/temp')
fct(file)

错误是:

Traceback (most recent call last):
  File "E:/Disertatie/Python/Resources/ASCII/ASCII.py/CHM", line 17, in <module>
    fct(file)
  File "E:/Disertatie/Python/Resources/ASCII/ASCII.py/CHM", line 10, in fct
    img = mpimg.imread(fisier)
  File "C:\Python27\ArcGISx6410.3\lib\site-packages\matplotlib\image.py", line 1242, in imread
    im = pilread(fname)
  File "C:\Python27\ArcGISx6410.3\lib\site-packages\matplotlib\image.py", line 1225, in pilread
    image = Image.open(fname)
  File "C:\Python27\ArcGISx6410.3\lib\site-packages\PIL\Image.py", line 2290, in open
    % (filename if filename else fp))
IOError: cannot identify image file <open file u'E:/Disertatie/Date/Results/chm.tif', mode 'r' at 0x0000000007726300>

3 个答案:

答案 0 :(得分:2)

该文件需要以二进制模式打开(&#34; rb&#34;)

tk文件对话框应该能够采用以此模式打开文件的参数而不是默认(r)

答案 1 :(得分:1)

您的对话框将打开文件并返回文件对象。您可以使用tk.askopenfilename代替(只返回文件名)并将其传递给imread函数。

答案 2 :(得分:0)

from scipy import misc
f = misc.face()
misc.imsave('e:/beauty.png', f) # uses the Image module (PIL)
import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()