PIL库
参考:http://www.cnblogs.com/yinxiangnan-charles/p/5928689.html
import numpy as np
from PIL import Image
# 打开图像
im = Image.open('E:/liuying/Pictures/test.png')
im.show()
print("the datatype of im", type(im)) # 读取的数据类型
print("the size of im: ", im.size) # 数据的大小
im_array = np.array(im) # 转换为array数组
print("the datatype of im_array",type(im_array))
# 转换为灰度图像
im_gray = im.convert('L')
im_gray.show()
结果得到:
the datatype of im <class 'PIL.PngImagePlugin.PngImageFile'>
the size of im: (203, 137)
the datatype of im_array <class 'numpy.ndarray'>
![](https://i-blog.csdnimg.cn/blog_migrate/e17b2c9461f5e041e35bffdf1e7750c0.png)
![](https://i-blog.csdnimg.cn/blog_migrate/e7cc621793e5cc806cb33fa61f53b242.png)
并排显示参考:https://blog.csdn.net/qq_21808961/article/details/80666589
这里会有个问题,就是在将显示的图片另存为的时候,只能保存格式BMP,有点疑惑,而且保存的图片无法正常查看。
skimage库
参考:https://www.jianshu.com/p/e8d058767dfa
from skimage import io
im = io.imread('E:/liuying/Pictures/test.png')
io.imshow(im)
print("the datatype of im", type(im)) # 读取的数据类型
print("the shape of img: ", im.shape) # 数据的大小
结果:
the datatype of im <class 'numpy.ndarray'>
the shape of img: (137, 203, 4)
可以看到,显示图像时自动加了坐标轴。
matplotlib库
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
im = mpimg.imread('E:/liuying/Pictures/test.png')
print("the datatype of im", type(im)) # 读取的数据类型
print("the shape of img: ", im.shape) # 数据的大小
plt.imshow(im) # 显示图片
结果如下:
the datatype of im <class 'numpy.ndarray'>
the shape of img: (137, 203, 4)
如果不想看到坐标轴,可以采用以下方法去掉:
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
%matplotlib inline # 本来是想让python notebook显示图像的时候嵌入到显示框下,但好像不用也不影响,暂且先放着
im = mpimg.imread('E:/liuying/Pictures/test.png')
print("the datatype of im", type(im)) # 读取的数据类型
print("the shape of img: ", im.shape) # 数据的大小
plt.figure("image")
plt.imshow(im) # 显示图片
plt.axis('off') # 不显示坐标轴
plt.show() # 不加好像也不影响结果