源自OpenCV官方免费新手教程:https://opencv.org/free-crash-course/
./05_Accessing_the_Camera/05_Camera.py
#!/usr/bin/python
# License Agreement
# 3-clause BSD License
#
# Copyright (C) 2018, Xperience.AI, all rights reserved.
#
# Third party copyrights are property of their respective owners.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the names of the copyright holders nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# This software is provided by the copyright holders and contributors "as is" and
# any express or implied warranties, including, but not limited to, the implied
# warranties of merchantability and fitness for a particular purpose are disclaimed.
# In no event shall copyright holders or contributors be liable for any direct,
# indirect, incidental, special, exemplary, or consequential damages
# (including, but not limited to, procurement of substitute goods or services;
# loss of use, data, or profits; or business interruption) however caused
# and on any theory of liability, whether in contract, strict liability,
# or tort (including negligence or otherwise) arising in any way out of
# the use of this software, even if advised of the possibility of such damage.
import cv2
import sys
s = 0 # 摄像头设备号
# sys.argv为执行python脚本时的所有参数,当前执行文件为第0个参数,即sys.argv[0]==05_Camera.py
if len(sys.argv) > 1: # 判断执行当前py脚本时,是否存在额外的执行参数
s = int(sys.argv[1]) # 如何是,则将摄像头设备号替换为执行参数。这样便实现了在命令行执行时用执行参数指定摄像头设备号的功能。
source = cv2.VideoCapture(s) #打开流(创建流对象):可以是摄像头,也可以是视频文件
win_name = 'Camera Preview' #设置窗口标题
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL) #创建窗口对象:设置窗口属性:标题、大小、位置等
# 实现在按键盘上某个键之前,窗口持续显示。
#while cv2.waitKey(1) != 27: # Escape
while cv2.waitKey(1) != ord('q'): # 返回q的ASCII码
has_frame, frame = source.read() #souce.read()返回流对象的两个值:当前帧数据,以及是否存在当前帧(布尔值)
if not has_frame: # 如果流对象当前帧存在状态为False,则退出循环。
break
cv2.imshow(win_name, frame) #在win_name窗口对象中显示当前帧数据
source.release() #释放设备占用
cv2.destroyWindow(win_name) #结束窗口对象
键位与ASCII码对应表