video = cv2.VideoCapture(index)用于调用摄像头,其中index从0开始命名。在台式机中,0表示外接摄像头;笔记本电脑中,0为内置摄像头,1为外接摄像头。
opencv支持对某一帧图片或摄像头拍摄的全部视频进行保存,图片保存利用cv2.imwrite()函数即可实现。视频保存需创建视频流,将摄像头拍摄的视频分解为图片写入视频流中,生成视频。
import cv2
video = cv2.VideoCapture(0) # 调用摄像头,PC电脑中0为内置摄像头,1为外接摄像头
judge = video.isOpened() # 判断video是否打开
while judge:
ret, frame = video.read()
cv2.imshow("frame", frame)
keyword = cv2.waitKey(1)
if keyword == ord('s'): # 按s保存当前图片
cv2.imwrite('F:/PycharmProjects/a.jpg', frame)
elif keyword == ord('q'): # 按q退出
break
# 释放窗口
video.release()
cv2.destroyAllWindows()
import cv2
video = cv2.VideoCapture(0) # 调用摄像头,PC电脑中0为内置摄像头,1为外接摄像头
judge = video.isOpened() # 判断video是否打开
frame_size = (int(video.get(3)),int(video.get(4))) # 获取摄像头分辨率
FPS = video.get(5) # 获取摄像头帧率
print("FPS: ", FPS)
# 保存视频
code = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') # 编码格式
fps = 25 # 保存视频的帧率
filename = "video.avi" # 保存视频的路径和名字
out = cv2.VideoWriter(filename, code, fps, frame_size, isColor=True) # 保存视频的视频流
if not(out.isOpened()): # 判断视频流是否创建成功
print('out is not opened')
while judge:
ret, frame = video.read()
out.write(frame) # 将图像写入视频流,生成视频
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
# 释放窗口和视频流
video.release()
out.release()
cv2.destroyAllWindows()
注意保存图片和视频功能尽量分别实现,否则可能会相互干扰。