Opencv Python 简明教程

OpenCV Python - Capture Video from Camera

通过在 OpenCV 库中使用 VideoCapture() 函数,可以非常轻松地从相机在 OpenCV 窗口上实时捕捉视频流。

By using the VideoCapture() function in OpenCV library, it is very easy to capture a live stream from a camera on the OpenCV window.

此函数需要设备索引作为参数。你的电脑可能连接了多个相机。它们从内置网络摄像头开始按索引编号排列。此函数返回一个 VideoCapture 对象。

This function needs a device index as the parameter. Your computer may have multiple cameras attached. They are enumerated by an index starting from 0 for built-in webcam. The function returns a VideoCapture object

cam = cv.VideoCapture(0)

打开摄像头后,我们可以借助 read() 函数从摄像头连续读取帧。

After the camera is opened, we can read successive frames from it with the help of read() function

ret,frame = cam.read()

read() 函数读取下一个可用的帧,并返回一个值(True/False)。此帧现在呈现为 cvtColor() 函数所需的色彩空间,并在 OpenCV 窗口中显示。

The read() function reads the next available frame and a return value (True/False). This frame is now rendered in desired color space with the cvtColor() function and displayed on the OpenCV window.

img = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
# Display the resulting frame
cv.imshow('frame', img)

你可以使用 imwrite() 函数将当前帧捕捉到图像文件中。

To capture the current frame to an image file, you can use imwrite() function.

cv2.imwrite(“capture.png”, img)

OpenCV 提供了 VideoWriter() 函数来将摄像头实时流保存到视频文件中。

To save the live stream from camera to a video file, OpenCV provides a VideoWriter() function.

cv.VideoWriter( filename, fourcc, fps, frameSize)

fourcc 参数是视频编解码器的标准化代码。OpenCV 支持各种编解码器,如 DIVX、XVID、MJPG、X264 等。fps 和 framesize 参数取决于视频采集设备。

The fourcc parameter is a standardized code for video codecs. OpenCV supports various codecs such as DIVX, XVID, MJPG, X264 etc. The fps anf framesize parameters depend on the video capture device.

VideoWriter() 函数返回一个 VideoWrite 流对象,捕获的帧会连续写入其中,形成一个循环。最后,释放帧和 VideoWriter 对象,以便最终完成视频的创建。

The VideoWriter() function returns a VideoWrite stream object, to which the grabbed frames are successively written in a loop. Finally, release the frame and VideoWriter objects to finalize the creation of video.

Example

以下示例会从内置网络摄像头读取实时视频,并将其保存到 ouput.avi 文件中。

Following example reads live feed from built-in webcam and saves it to ouput.avi file.

import cv2 as cv
cam = cv.VideoCapture(0)
cc = cv.VideoWriter_fourcc(*'XVID')
file = cv.VideoWriter('output.avi', cc, 15.0, (640, 480))
if not cam.isOpened():
   print("error opening camera")
   exit()
while True:
   # Capture frame-by-frame
   ret, frame = cam.read()
   # if frame is read correctly ret is True
   if not ret:
      print("error in retrieving frame")
      break
   img = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
   cv.imshow('frame', img)
   file.write(img)


   if cv.waitKey(1) == ord('q'):
      break

cam.release()
file.release()
cv.destroyAllWindows()