一、如果系统里没有安装PIL库的,请先到命令提示符输入“pip install pillow”进行安装
二、之后就可以参考以下的代码
1 from PIL import Image 2 from pylab import * 3 4 # 添加中文字体支持 5 from matplotlib.font_manager import FontProperties 6 font = FontProperties(fname=r"c:windowsfontsSimSun.ttc", size=14) 7 figure() 8 9 pil_im = Image.open('E:pythonPython Computer VisionImage dataempire.jpg') 10 gray() 11 subplot(121) 12 title(u'原图',fontproperties=font) 13 axis('off') 14 imshow(pil_im) 15 16 pil_im = Image.open('E:pythonPython Computer VisionImage dataempire.jpg').convert('L') 17 subplot(122) 18 title(u'灰度图',fontproperties=font) 19 axis('off') 20 imshow(pil_im) 21 22 show()
三,可以观看效果
四、其还可以进行旋转等操作
1 from PIL import Image 2 from pylab import * 3 4 # 添加中文字体支持 5 from matplotlib.font_manager import FontProperties 6 7 font = FontProperties(fname=r"c:windowsfontsSimSun.ttc", size=14) 8 figure() 9 10 # 显示原图 11 pil_im = Image.open('E:/python/Python Computer Vision/Image data/empire.jpg') 12 print(pil_im.mode, pil_im.size, pil_im.format) 13 subplot(231) 14 title(u'原图', fontproperties=font) 15 axis('off') 16 imshow(pil_im) 17 18 # 显示灰度图 19 pil_im = Image.open('E:/python/Python Computer Vision/Image data/empire.jpg').convert('L') 20 gray() 21 subplot(232) 22 title(u'灰度图', fontproperties=font) 23 axis('off') 24 imshow(pil_im) 25 26 # 复制并粘贴区域 27 pil_im = Image.open('E:/python/Python Computer Vision/Image data/empire.jpg') 28 box = (100, 100, 400, 400) 29 region = pil_im.crop(box) 30 region = region.transpose(Image.ROTATE_180) 31 pil_im.paste(region, box) 32 subplot(233) 33 title(u'复制粘贴区域', fontproperties=font) 34 axis('off') 35 imshow(pil_im) 36 37 # 缩略图 38 pil_im = Image.open('E:/python/Python Computer Vision/Image data/empire.jpg') 39 size = 128, 128 40 pil_im.thumbnail(size) 41 print(pil_im.size) 42 subplot(234) 43 title(u'缩略图', fontproperties=font) 44 axis('off') 45 imshow(pil_im) 46 pil_im.save('E:/python/Python Computer Vision/Image data/empire thumbnail.jpg')# 保存缩略图 47 48 #调整图像尺寸 49 pil_im=Image.open('E:/python/Python Computer Vision/Image data/empire thumbnail.jpg') 50 pil_im=pil_im.resize(size) 51 print(pil_im.size) 52 subplot(235) 53 title(u'调整尺寸后的图像',fontproperties=font) 54 axis('off') 55 imshow(pil_im) 56 57 #旋转图像45° 58 pil_im=Image.open('E:/python/Python Computer Vision/Image data/empire thumbnail.jpg') 59 pil_im=pil_im.rotate(45) 60 subplot(236) 61 title(u'旋转45°后的图像',fontproperties=font) 62 axis('off') 63 imshow(pil_im) 64 65 show()
查看效果: