实时显示摄像头图像
按下空格键,截取图片
按下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()
截图:
可以添加函数来使图像的显示效果改变(边缘检测效果):
def strokeEdges(src,dst,blurKsize = 7,edgeKsize = 5):
# 模糊函数,对去除数字化的视频噪声很有效,尤其是彩色图像的噪声
blurredSrc = cv2.medianBlur(src, blurKsize)
# 彩色图转灰度图
graySrc = cv2.cvtColor(blurredSrc, cv2.COLOR_BGR2GRAY)
# 边缘检测函数,会产生明显的边缘线条
cv2.Laplacian(graySrc, cv2.CV_8U, graySrc, edgeKsize)
# 黑转白,白转黑
normalizedInverseAlpha = (1.0 / 255) * (255 - graySrc)
# 重新恢复彩色,实现更清晰的轮廓图
channels = cv2.split(src)
for channel in channels:
channel[:] = channel * normalizedInverseAlpha
cv2.merge(channels, dst)
自行在对应的帧显示处调用: