- 计算机视觉应用与实战
- 韩少云等编著
- 786字
- 2022-08-16 14:46:26
1.3 图像保存
1.3.1 使用OpenCV保存图像
在OpenCV中,可以使用cv2.imwrite(dir,img)函数来保存图像。
第一个参数dir是图像存储的位置。
第二个参数img是图像对象。
该函数用于将ndarray(numpy数组)对象保存成图像文件,并返回保存结果。在默认情况下,该函数的保存结果为8位单通道图像和BGR图像。
1.3.2 使用Matplotlib保存图像
在Matplotlib中,可以使用matplotlib.pyplot.imsave(dir,img,**kwargs)函数来保存图像。
第一个参数dir是图像存储的位置。
第二个参数img是图像对象。
第三个参数**kwargs是一个字典参数,内容较多,下面总结了几个常用的参数值。
·format:指明图像格式,可能的格式有png、pdf、svg、etc,支持大多数图像格式。
·dpi:分辨率,用于调整图像的清晰度。
·cmap:颜色映射,对于彩色图像此参数被忽略,只对灰度图像有效。
1.3.3 案例实现——使用OpenCV保存图像
1.实验目标
使用OpenCV读取一张uint8类型的图像,查看不同数据类型下图像的显示效果并保存。
2.实验环境
实验环境如表1.5所示。
表1.5 实验环境

3.实验步骤
创建源码文件test01_imwrite_opencv.py。
按照如下步骤编写代码。
步骤一:导入模块

步骤二:使用OpenCV保存uint8类型的图像

步骤三:使用OpenCV保存float64类型的图像

步骤四:使用OpenCV保存由float64类型转换为uint8类型的图像


步骤五:运行实验代码
使用如下命令运行实验代码。

运行效果分别如图1.7~图1.9所示。

图1.7 使用OpenCV保存uint8类型的图像

图1.8 使用OpenCV保存float64类型的图像

图1.9 使用OpenCV保存由float64类型转换为uint8类型的图像
1.3.4 案例实现——使用Matplotlib保存图像
1.实验目标
使用Matplotlib读取一张uint8类型的图像,分别使用不同的数据类型显示图像并保存。
2.实验环境
实验环境如表1.6所示。
表1.6 实验环境

3.实验步骤
创建源码文件test02_imsave_matplotlib.py。
按照如下步骤编写代码。
步骤一:导入模块

步骤二:使用Matplotlib保存uint8类型的图像

步骤三:使用Matplotlib保存float64类型的图像

步骤四:运行实验代码
使用如下命令运行实验代码。

运行效果分别如图1.10和图1.11所示。

图1.10 使用Matplotlib保存uint8类型的图像

图1.11 使Matplotlib保存float64类型的图像
可见,使用OpenCV和Matplotlib保存的图像在颜色方面存在差异。使用OpenCV保存的float64类型的图像,再次读取出来时图像存在失真现象。