实时显示摄像头图像
按下空格键,截取图片
按下tab键,开始录制摄像内容,再次按下,结束录制按下Esc键,关闭窗口
import cv2
import numpy
#第几章图片
img_count=0
InitVideo=False
#第几个视频
video_count=0
video_flag=False
#参数为0,表示打开笔记本的内置摄像头
cameraCapture = cv2.VideoCapture(0)
w = cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)
# 获取视频帧的高
h = cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)
# 获取视频帧的帧率
fps = cameraCapture.get(cv2.CAP_PROP_FPS)
# 获取视频流的总帧数
fcount = cameraCapture.get(cv2.CAP_PROP_FRAME_COUNT)
# 给窗口命名
cv2.namedWindow('MyWindow')
# 按帧读取数据
success, frame = cameraCapture.read()
while success :
#镜像显示摄像头图像
mirroredFrame=numpy.fliplr(frame).copy()
cv2.imshow('MyWindow', mirroredFrame)
keycode=cv2.waitKey(1)
if keycode == 32:
cv2.imwrite('img'+str(img_count)+'.jpg', frame)
img_count=img_count+1
elif keycode == 27:
break
elif keycode == 9:
video_flag =not video_flag #这个参数控制是否开始录屏
InitVideo = True #这个参数来影响初始化视频的次数
#关于录屏
if video_flag == True:
if InitVideo == True:
# 初始化
writer = cv2.VideoWriter('out' + str(video_count) + '.avi', cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),
int(fps), (int(w), int(h)))
video_count = video_count + 1
InitVideo =False
writer.write(frame)
success, frame = cameraCapture.read()
cv2.destroyWindow('MyWindow')
cameraCapture.release()
writer.release()
cv2.destroyAllWindows()
截图: