三、图像的加载、显示及保存
1、源代码展现
load_display_save.py
from __future__ import print_function
import argparse
import cv2
# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())
# Load the image and show some basic information on it
image = cv2.imread(args["image"])
print("width: {} pixels".format(image.shape[1]))
print("height: {} pixels".format(image.shape[0]))
print("channels: {}".format(image.shape[2]))
# Show the image and wait for a keypress
cv2.imshow("Image", image)
cv2.waitKey(0)
# Save the image -- OpenCV handles converting filetypes
# automatically
cv2.imwrite("newimage.jpg", image)
代码来自Practical Python and OpenCV, 3rd Edition
2、代码解释
①__future__宏包:兼容python 2和python 3的宏包。
②argparse宏包:处理解析命令行参数专用。此外还可以采取sys.argv和getopt的方式来进行参数解析,相比此二者,argparse的可读性更好,也更加灵活。
Line 6
ap = argparse.ArgumentParser( )
创建一个ArgumentParser对象,它将帮助我们将命令行解析成Python数据类型所需的信息。
Line 7
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
添加一个有两个选项的参数(此处的参数可以是位置参数也可以是关键字参数,示例中是位置参数),短参数为-i,长参数为–image。
P.S.位置参数与关键字参数的区别
位置参数:调用函数时根据函数定义的参数位置来传递函数。形参与实参位置必须一一对应
关键字参数:“键-值”形式加以指定。不强调强制的顺序,可读性更好。(优选)
required = True表示参数必需。help选项则提供参数帮助。
Line 8
args = vars(ap.parse_args( ) )
调用vars函数,解析命令行参数,并存储在字典(键值对形式)中。
parse_args( ) 解析添加的命令行参数,不带参数调用,返回Namespace对象。
vars( )函数保存返回对象的属性和属性值形成键值对到字典对象中。在此,字典键为命令行参数的长名称–image(存在两个参数时,必须使用长参数,没有长参数时可以使用短参数作为字典键);字典值为命令行参数提供的字典值(在此示例中为包含路径的图像名【可以使用绝对路径和相对路径】)。
③cv2:OpenCV库
Line 11
image = cv2.imread(args["image"])
调用cv2中的图像读取函数从磁盘上加载图像,返回值为表示图像的Numpy数组
Line 12-14 检查图像尺寸
image.shape[0]:高
image.shape[1]:宽
image.shape[2]:通道数
Line 17-18
cv2.imshow("Image", image)
cv2.waitKey(0)
第一个Image是显示图像窗口的名称,第二个image为代表图像的Numpy数组。
cv2.waitKey的用法:cv2.waitKey([,delay]),0为特殊值,表示永远暂停。
Line22
cv2.imwrite("newimage.jpg", image)
将要保存的图像写入到JPG格式文件,第一个参数为需要保存的文件名称及路径,第二个参数为图像的Numpy数组。
最后,打开Terminal终端,输入python load_display_save.py --image …/images/trex.png(图像所在路径)并运行即可看到打开的图像窗口及新生成的jpg文件。
3、Pycharm中运行
首先,在Configuration中添加Parameter,格式为参数+图片路径,如图所示。
接着,Run一下就可以看到图片显示了。