脚本宝典收集整理的这篇文章主要介绍了不同方式对图像进行输入/输出和显示,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
(1)使用PIL读取、保存和显示图像
先安装pillow库,安装命令为 pip install pillow
常用的函数有:oPEn(),save(),show()以及convert(),分别对应读取图像,保存图像,显示图像和转换图像。
From PIL import Image, ImageFont, ImageDraw im = Image.open('./images/a.jpg') # 打开图像 # width: 图像宽, height: 图像高, mode: 图像的模式(RGB,GRAY或者别的), format: 图片格式(jpeg,...) PRint(im.width, im.height, im.mode, im.format, type(im)) im_gray = im.convert('L') # 将当前图像转换成灰度图 im_gray.save('./images/a_gray.jpg') #在指定路径保存图像 Image.open('./images/a_gray.jpg').show() # 在打开图像的同时显示图像
(2)使用Matlibplot读取、保存和显示图像
安装matplotlib:pip install matplotlib
import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np im = mpimg.imread('./images/b.jpg') # Shape: (h,w,c)-> 高,宽,通道数, dtype: 图像在内存中像素值的类型(unIT8,float32...), type(im): <class 'numpy.ndarray'> print(im.shape, im.dtype, type(im)) plt.figure(figsize=(30, 30)) # figSize: 表示figure的大小 plt.imshow(im) plt.axis('off') # 关闭坐标轴 plt.show() # 显示图像 # 将图像保存为较暗的图像 im1 = np.array(im) im1.flags.writeable = True im1[im1 < 100] = 0 plt.imshow(im1) plt.axis('off') plt.tight_layout() plt.show() plt.savefig('./images/b_dark.jpg') # 保存图像
_, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 10))ax1.imshow(im)ax2.imshow(im1)plt.tight_layout()plt.show()
使用matplotlib对图像进行插值:
import matplotlib.image as mpimg import matplotlib.pyplot as plt im = mpimg.imread('./images/c.jpg') methods = ['none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'lanczos'] # [未插值,最近邻,双线性,双三次,16样条,兰索斯] fig, axes = plt.subplots(1, 6, figsize=(15, 30), subplot_kw={'xticks': [], 'yticks': []}) fig.subplots_adjust(hspace=0.05, wspace=0.5) for ax, interp_method in zip(axes.flat, methods): ax.imshow(im, interpolation=interp_method) ax.set_title(str(interp_method), size=20) plt.tight_layout() plt.savefig('./images/c_inter.jpg') plt.show()
(3)使用scikit-image读取保存和显示图像
安装scikit-image: pip install scikit-image
分别使用imread,imsave,imshow和show函数来执行操作。
from skimage.io import imread, imsave, imshow, show from skimage import color import matplotlib.pyplot as plt im = imread("./images/b.jpg") #(300, 541, 3) unit8 <class 'numpy.ndarray'> print(im.shape, im.dtype, type(im)) hsv = color.rgb2hsv(im) hsv[:, :, 1] = 0.5 im1 = color.hsv2rgb(hsv) imsave('./images/b_hsv.jpg', im1) im = imread("./images/b_hsv.jpg") plt.axis('off'), imshow(im), show()
以上是脚本宝典为你收集整理的不同方式对图像进行输入/输出和显示全部内容,希望文章能够帮你解决不同方式对图像进行输入/输出和显示所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。