使用摄像头,需要使用cv2.VideoCapture(0)创建VideoCapture对象,参数0指的是摄像头的编号,如果你电脑上有两个摄像头的话,访问第2个摄像头就可以传入1,依此类推。
import cv2
#
capture = cv2.VideoCapture(0)
if None == capture:
print("摄像头打开失败")
while(True):
# 获取一帧
ret, frame = capture.read()
if ret == False:
continue
# 将这帧转换为灰度图
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if cv2.waitKey(1) == ord('q'):
break
VideoCaptureProperties
import cv2
#打开 0号摄像头
capture = cv2.VideoCapture(0)
# 获取捕获的分辨率
# propId可以直接写数字,也可以用OpenCV的符号表示
width, height = capture.get(3), capture.get(4)
print(width, height)
# 以原分辨率的一倍来捕获
capture.set(cv2.CAP_PROP_FRAME_WIDTH, width * 2)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height * 2)
# 某些摄像头设定分辨率等参数时会无效,因为它有固定的分辨率大小支持,一般可在摄像头的资料页# 中找到
播放视频其实跟打开摄像头的操作一样
我们也可以获取视频分辨率、帧率、当前播放帧等等信息,可以查看
VideoCapture Object
结构就可以看到信息了~~~~~~~~~~
eg:
import cv2
# 播放本地视频
capture = cv2.VideoCapture('wzry.mp4')
#打印一些视频的信息
print(capture.get(cv2.CAP_PROP_POS_MSEC))
width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
print("分辨率:%f,%f"%(width,height))
print("休息一会")
while(capture.isOpened()):
ret, frame = capture.read()
if False == ret:
print("视频播放完毕~~~")
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if cv2.waitKey(30) == ord('q'):
print("手动退出了~~~~")
break
关于视频四字节码,可以去这个网站查看
http://www.fourcc.org/codecs.php
如下功能是读取一个视频,转存成另一个视频
import cv2
# 定义编码方式并创建VideoWriter对象
# 指定视频编码方式的四字节码
'''
cv2.VideoWriter_fourcc('P','I','M','1') = MPEG-1 codec
cv2.VideoWriter_fourcc('M','J','P','G') = motion-jpeg codec --> mp4v
cv2.VideoWriter_fourcc('M', 'P', '4', '2') = MPEG-4.2 codec
cv2.VideoWriter_fourcc('D', 'I', 'V', '3') = MPEG-4.3 codec
cv2.VideoWriter_fourcc('D', 'I', 'V', 'X') = MPEG-4 codec --> avi
cv2.VideoWriter_fourcc('U', '2', '6', '3') = H263 codec
cv2.VideoWriter_fourcc('I', '2', '6', '3') = H263I codec
cv2.VideoWriter_fourcc('F', 'L', 'V', '1') = FLV1 codec
'''
#视频读取
capture = cv2.VideoCapture('wzry.mp4')
#获取FPS
video_fps = capture.get(cv2.CAP_PROP_FPS)
#获取宽度、高度
video_width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
video_height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
video_size =(int(video_width),int(video_height))
#获取视频编码方式的四字节码
codec = capture.get(cv2.CAP_PROP_FOURCC)
#strcodec = chr(codec&0xFF) + chr((codec>>8)&0xFF) + chr((codec>>16)&0xFF) + chr((codec>>24)&0xFF)
#print ('codec is ' + strcodec)
outfile = cv2.VideoWriter('output.mp4', int(codec), video_fps, video_size)
while(capture.isOpened()):
ret, frame = capture.read()
if ret:
outfile.write(frame) # 写入文件
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
else:
break