
1.1 图像显示
1.1.1 使用OpenCV显示图像
OpenCV是计算机视觉中经典的专用库,具备支持多语言、跨平台的优点,功能强大。
OpenCV-Python为OpenCV提供了Python接口,这样使用者在Python中能够调用C/C++,从而在保证易读性和运行效率的前提下,实现所需的功能。
使用cv2.imshow(window_name,img)函数在窗口中显示图像,窗口会自动适应不同的图像尺寸。
第一个参数window_name是窗口名称,是一个字符串,使用者可以根据需要创建任意多个窗口;第二个参数img是图像名称。
使用者既可以根据需要创建任意多个窗口,也可以使用不同的窗口名称。
1.1.2 使用Matplotlib显示图像
Matplotlib也是一种常用的图像处理库,可以使用matplotlib.pyplot.imshow(img)函数来显示图像,参数img代表图像对象,相关参数较少,使用便捷。
需要注意的是,使用OpenCV读取的图像的颜色通道为BGR(蓝绿红),而Matplotlib使用的颜色通道为RGB(红绿蓝),所以需要进行颜色通道转换。先将OpenCV读取的BGR(蓝绿红)颜色通道的图像转换为 RGB(红绿蓝)颜色通道的图像,再使用 Matplotlib 正确显示图像。
1.1.3 案例实现——使用OpenCV显示图像
1.实验目标
提供一张图像,使用OpenCV显示该图像。
2.实验环境
实验环境如表1.1所示。
表1.1 实验环境

① 该实验平台可用于各院校和培训机构人工智能课程教学。如果是个人读者阅读本书,也可以在普通计算机上部署与实施案例的代码,不受影响。
3.实验步骤
创建源码文件test01_imshow_opencv.py,用来实现使用OpenCV显示图像。
按照如下步骤编写代码。
步骤一:导入模块

步骤二:读取图像

步骤三:使用OpenCV显示图像

步骤四:运行实验代码
使用如下命令运行实验代码。(注:如果是Ubuntu环境,可能需要运行python3,以下同)

运行效果如图1.1所示。

图1.1 使用OpenCV显示图像
1.1.4 案例实现——使用Matplotlib显示图像
1.实验目标
提供一张图像,使用Matplotlib显示该图像。
2.实验环境
实验环境如表1.2所示。
表1.2 实验环境

3.实验步骤
创建源码文件test02_imshow_matplotlib.py,用来实现使用Matplotlib显示图像。
按照如下步骤编写代码。
步骤一:导入模块

步骤二:读取图像

步骤三:将颜色通道从BGR转换为RGB

步骤四:使用Matplotlib显示图像

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

运行效果如图1.2所示。

图1.2 使用Matplotlib显示图像