To use the camera, you need to create a VideoCapture object using (0), the parameter 0 refers to the number of the camera, if you have two cameras on your computer, you can pass in 1 for accessing the 2nd camera, and so on.
# Turn on the camera and gray out the display import cv2 as cv # 0 indicates the camera number capture = (0) while(True): # Get a frame # The first parameter ret (abbreviation for return value) is a boolean value indicating whether the current frame was acquired correctly or not. ret, frame = () # Convert this frame to grayscale gray = (frame, cv.COLOR_BGR2GRAY) ('frame', gray) if (1) == ord('q'): break
The camera captures the image:
Getting and modifying camera property values
With (propId) you can get some properties of the camera, such as captured resolution, brightness and contrast, etc. propId is a number from 0 to 18, representing different properties. To modify the value of the camera's properties, you can use (propId,value). For example, if we add the following code before while, we can capture the video with 2x resolution relative to the above.
# Get the resolution of the capture # propId can be written directly as a number, or in OpenCV notation width, height = (3), (4) print(width, height) # Captured at double the original resolution (cv.CAP_PROP_FRAME_WIDTH, width * 2) (cv.CAP_PROP_FRAME_HEIGHT, height * 2)
Captured at 2x the resolution of the original image:
Play local video
Same as turning on the camera, if you replace the camera number with the path to the video you can play the local video. Recall that (), its parameter indicates the pause time, so the larger this value is, the slower the video will play, and vice versa, the faster it will play, usually set to 25 or 30.
# opencv playback of local video import cv2 as cv capture = ('E:/1.mp4') while(()): ret, frame = () gray = (frame, cv.COLOR_BGR2GRAY) ('frame', gray) if (30) == ord('q'): break
E:/1.mp4 in playback:
Record video and save it
Previously we used () to save images, to save videos we need to create a VideoWriter object and we need to pass it four parameters:
1. The name of the output file, such as ''
2. Coding mode FourCC code
3. Frame rate FPS
4. Resolution size to be saved
FourCC is a four-byte code used to specify how the video is encoded. For example, MJPG encoding can be written like this: cv.VideoWriter_fourcc(*'MJPG') or cv.VideoWriter_fourcc('M','J','P','G')
import cv2 as cv capture = (0) # Define the encoding method and create the VideoWriter object fourcc = cv.VideoWriter_fourcc(*'MJPG') outfile = ('', fourcc, 25., (640, 480)) while(()): ret, frame = () if ret: (frame) # Write the file ('frame', frame) if (1) == ord('q'): break else: break
As expected it was generated under the current path :
The above is python based opencv operation camera details, more information about python opencv operation camera please pay attention to my other related articles!