要点
- opencv常用读视频函数 cv2.VideoCapture 、cv2.VideoCapture.get 等,可以参考这里
- opencv常用写视频函数 cv2.VideoWriter 等可以参考这里 ,其中视频格式可以参考这里
- videoCapture.read() 是按帧读取视频,ret,frame 是获 .read() 方法的两个返回值。其中 ret 是布尔值,如果读取帧是正确的则返回True,如果文件读取到结尾,它的返回值就为False。frame 就是每一帧的图像,是个三维矩阵。
- 可以使用 cv2.putText 来添加文字,具体参数可以参考这里
代码
例程一
- 本例程将读取一个视频,并个视频加上流动水印后保存为一个新视频。
import cv2
VideoCapture = cv2.VideoCapture("VideoExample.mp4")
fps = VideoCapture.get(cv2.CAP_PROP_FPS)
size = (int(VideoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(VideoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
totalFrames = int(VideoCapture.get(7))
ViideoWrite = cv2.VideoWriter("VideoWriterExample.avi",cv2.VideoWriter_fourcc('I','4','2','0'),
fps,size)
x=10
y=10
i=1
step_x=5
step_y=5
success,frame = VideoCapture.read()
print("第"+str(i)+"帧, 共"+str(totalFrames)+"帧")
while success:
cv2.waitKey(1)
cv2.putText(frame,'hello,opencv',(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),3)
cv2.imshow("frame",frame)
ViideoWrite.write(frame)
if(x>size[0]):step_x=-5
if(x<0):step_x=5
if(y>size[1]):step_y=-5
if(y<0):step_y=5
x += step_x
y += step_y
success,frame = VideoCapture.read()
i += 1
print("第"+str(i)+"帧, 共"+str(totalFrames)+"帧")
print ('Quitted!')
cv2.destroyAllWindows()
例程二
- 本例程将读取并显示摄像头图像,在图像窗口按下按键“S”将开始录制摄像头视频,按下按键“X”将停止录制摄像头视频,按下按键“Q”将停止程序。
import cv2
cameraCapture = cv2.VideoCapture(0)
fps = cameraCapture .get(5)
size = (int(cameraCapture .get(cv2.CAP_PROP_FRAME_WIDTH)),int(cameraCapture .get(cv2.CAP_PROP_FRAME_HEIGHT)),)
cameraWriter = cv2.VideoWriter("CameraExample.avi",cv2.VideoWriter_fourcc('I','4','2','0'),fps,size)
x=10
y=10
i=1
step_x=5
step_y=5
success,frame = cameraCapture.read()
print ('Showing camera. Press key "Q" to quit.')
print ('Press key "S" to start recording.')
Quit=1
Record=0
while success and Quit:
keycode=cv2.waitKey(1)
if keycode & 0xFF == ord('q'):
Quit = 0
if keycode & 0xFF == ord('s'):
Record = 1
if keycode & 0xFF == ord('x'):
Record = 0
if Record:
cv2.putText(frame,'hello,opencv',(x,y),cv2.FONT_HERSHEY_SIMPLEX,3,(0,255,255),3)
cameraWriter.write(frame)
if x > size[0]:
step_x = -5
if x < 0:
step_x = 5
if y > size[1]:
step_y = -5
if y < 0:
step_y = 5
x += step_x
y += step_y
print("第" + str(i) + "帧,")
i = i + 1
print('Press key "X" to end recording.')
print("\n\t")
cv2.imshow('frame',frame)
success,frame = cameraCapture.read()
if success == 0:
print ('Camera disconnect !')
print('Quitted!')
cameraCapture.release()
cv2.destroyAllWindows()