import cv2
import numpy as np
创建一个窗口
cv2.namedWindow(‘frame’)
尝试不同的视频源参数
cap = cv2.VideoCapture(0)
标志位,用于判断是否正在录制
recording = False
定义拍照函数
def take_photo():
ret, frame = cap.read()
if ret:
cv2.imwrite(‘photo.jpg’, frame)
print(“照片已保存为 photo.jpg”)
定义录制视频函数
def start_stop_recording():
global recording
recording = not recording
if recording:
print(“开始录制视频”)
else:
print(“停止录制视频”)
fourcc = cv2.VideoWriter_fourcc(*‘XVID’)
out = None
if not cap.isOpened():
print(“无法打开摄像头”)
else:
while True:
ret, frame = cap.read()
if not ret:
print(“无法获取帧”)
break
cv2.imshow(‘frame’, frame)
key = cv2.waitKey(1)
# 按下’p’键拍照
if key & 0xFF == ord(‘p’):
take_photo()
# 按下’r’键开始/停止录制视频
if key & 0xFF == ord(‘r’):
start_stop_recording()
# 按下’q’键退出
if key & 0xFF == ord(‘q’):
break
if recording:
if out is None:
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (frame.shape[1], frame.shape[0]))
out.write(frame)
else:
if out is not None:
out.release()
out = None
cap.release()
cv2.destroyAllWindows()