opencv VideoCapture
时间: 2023-11-09 17:05:53 浏览: 39
OpenCV VideoCapture is a class that provides an interface for capturing video from cameras or files. It is a part of the OpenCV library that is used for computer vision applications. VideoCapture can be used to capture live video from a webcam or to read video files.
To use VideoCapture, you need to create an instance of the class and specify the device or file you want to capture video from. The device is identified by its index number, which starts from 0. For example, to capture video from the default camera, you can use the following code:
```python
import cv2
cap = cv2.VideoCapture(0)
```
This creates a VideoCapture object and sets it to capture video from the first camera device available on the system.
You can also specify a video file to read using the constructor. For example, to read a video file named "test.mp4", you can use the following code:
```python
import cv2
cap = cv2.VideoCapture("test.mp4")
```
Once you have created a VideoCapture object, you can use the read() method to read frames from the video stream. The read() method returns a tuple containing a boolean value and a frame. The boolean value indicates whether the frame was successfully read or not, and the frame is a NumPy array containing the image data.
```python
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
cv2.imshow("Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
This code captures video from the default camera and displays each frame in a window. The loop continues until the user presses the 'q' key to quit. Finally, the VideoCapture object is released and the display window is destroyed.