python opencv 调用摄像头并显示
以下实例调用设备默认摄像头并显示,可通过传入cam_url改变显示的摄像头,显示时按q或ESC退出
示例代码
import cv2
def catch_video(name='my_video', video_index=0):
cv2.namedWindow(name)
# 传入地址为0时调用默认摄像头
cap = cv2.VideoCapture(video_index)
if not cap.isOpened():
# 如果没有检测到摄像头,报错
raise Exception('Check if the camera is on.')
while cap.isOpened():
catch, frame = cap.read() # 读取每一帧图片
cv2.imshow(name, frame) # 在window上显示图片
key = cv2.waitKey(10)
if (key & 0xFF == ord('q')) or key == 27:
# 按q退出 按ESC键退出
break
# 释放摄像头
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
# cam_url = 'rtsp://admin:CvsJ1vml@192.168.101.19'
catch_video()