OpenCV教程-OpenCV VideoCapture
OpenCV提供了VideoCapture()函数,用于处理摄像头。我们可以执行以下任务:
- 读取视频、显示视频和保存视频。
- 从摄像头捕获并显示。
从摄像头捕获视频
OpenCV允许使用摄像头(网络摄像头)捕获实时流的简单界面。它将视频转换为灰度并显示出来。
我们需要创建一个VideoCapture对象来捕获视频。它接受设备索引或视频文件的名称。指定给摄像头的数字称为设备索引。我们可以通过传递0或1来选择摄像头。之后,我们可以逐帧捕获视频。
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(True):
# Capture image frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
cap.read()返回一个布尔值(True/False)。如果正确读取帧,它将返回True。
从文件播放视频
我们可以从文件播放视频。通过更改摄像头索引为文件名,类似于从摄像头捕获。如果时间过长,视频将变慢。如果时间太短,视频将非常快。
import numpy as np
import cv2
cap = cv2.VideoCapture('filename')
while(cap.isOpened()):
ret, frame = cap.read()
#it will open the camera in the grayscale mode
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
保存视频
cv2.imwrite()函数用于将视频保存到文件中。首先,我们需要创建一个VideoWriter对象。然后,应该在函数内指定FourCC代码和每秒帧数(fps)。帧大小应该在函数内传递。
FourCC是用于标识视频编解码器的4字节代码。以下是保存视频的示例。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
它将保存视频到指定位置。运行上述代码并查看输出。