python IOError: cannot identify image file

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_25704999/article/details/50118465

python 做图像处理,输出一副图片的大小。代码如下:

import Image
im=Image.open('D:\\pythonword\\tt.jpg')
print im.size

运行报错:IOError: cannot identify image file ‘D:\pythonword\tt.jpg’
这里写图片描述
逐步分析报错原因:
(1)首先确定自己pillow文件成功安装(用easy_install和pip安装,具体安装步骤可参考我的另外一篇博客:http://blog.csdn.net/sinat_25704999/article/details/49976137
(2)python中文件路径需要将\改写为/或者\,在上述代码中D:\pythonword\tt.jpg写法是正确的,tt.jpg是正常的图片,在浏览器中输入此地址也可以正常打开该图片,所以文件路径没有问题。
这里写图片描述
(3)不只是JPEG的格式,PNG等图片文件格式都报同样的错误。

用from PIL import Image代替import Image后,代码运行成功,显示了图片的大小。
这里写图片描述

总结:
PIL(Python Imaging Library)因常年没有更新,也不能适用于新版本的python,于是Pillow应运而生。但是Pillow由PIL而来,所以导入相关文件(以Image为例)不能写作:import Image,而是要写成 from PIL import Image。

猜你喜欢

转载自blog.csdn.net/sinat_25704999/article/details/50118465