Use OpenCV to realize camera video capture, and read the default camera and display the screen in real time by creating VideoCapture objects; 2. You can set resolution, frame rate and other parameters to optimize video quality; 3. You can save the frames captured by the camera as a video file, and you need to ensure that the encoding format, resolution and frame size of VideoWriter matches the frame size; 4. Support reading local video files such as mp4 and avi formats and playback; 5. Notes include correctly setting waitKey to control playback speed, device number selection, system permissions and driver support issues. This example fully covers the core functions of video capture, display, save and playback in OpenCV, providing a foundation for subsequent expansion of face recognition, motion detection and other applications.
Here is a simple and practical example of video capture using Python and OpenCV for reading video streams from the camera and displaying them in real time.

? Basic video capture example (from the camera)
import cv2 # Create a VideoCapture object, 0 means the default camera cap = cv2.VideoCapture(0) # Check whether the camera is successfully opened if not cap.isOpened(): print("Camera cannot be turned on") exit() While True: # Capture ret frame by frame, frame = cap.read() # If the frame is read correctly, ret is True if not ret: print("Cannot receive frames (maybe stream ended?), exit...") break # Show frame cv2.imshow('camera screen', frame) # Press the 'q' key to exit if cv2.waitKey(1) == ord('q'): break # Release resource cap.release() cv2.destroyAllWindows()
? Common settings (resolution, frame rate, etc.)
You can set camera parameters before capturing:
cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # Set width cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # Set height cap.set(cv2.CAP_PROP_FPS, 30) # Set frame rate# Optional: Print the current set print(f"Resolution: {cap.get(cv2.CAP_PROP_FRAME_WIDTH)}x{cap.get(cv2.CAP_PROP_FRAME_HEIGHT)}") print(f"FPS: {cap.get(cv2.CAP_PROP_FPS)}")
? Save video to file
If you want to save the content captured by the camera into a video file:

import cv2 cap = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc(*'XVID') # Encoding format out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) While True: ret, frame = cap.read() if not ret: break out.write(frame) # Write frame cv2.imshow('Recording...', frame) if cv2.waitKey(1) == ord('q'): break cap.release() out.release() cv2.destroyAllWindows()
?? Note: When saving video, the resolution of
VideoWriter
must be consistent with the size of the written frame.
? Read local video files
Not only the camera, OpenCV can also read video files such as .mp4
and .avi
:

cap = cv2.VideoCapture('input.mp4') # Replace with your video path while cap.isOpened(): ret, frame = cap.read() if not ret: print("Video playback ends") break cv2.imshow('Video Play', frame) if cv2.waitKey(25) == ord('q'): # waitKey controls playback speed break cap.release() cv2.destroyAllWindows()
? Tips
-
cv2.waitKey(1)
: The parameter is milliseconds, indicating the display time per frame. The smaller the value, the faster the video. - Camera device number: If there are multiple cameras, you can try
1
,2
, etc. - Virtual Environment Issues: Some systems (such as macOS or Linux) may require additional drivers to support the camera.
- Permissions issue: Make sure the program has permission to access the camera (especially on Mac or browser sandbox environments).
Basically that's it. This example covers the most common usage scenarios for OpenCV video capture: real-time capture, display, save and play. You can expand the functions of facial recognition, motion detection and other functions based on this.
The above is the detailed content of python opencv video capture example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Use the pip command to easily install OpenCV tutorial, which requires specific code examples. OpenCV (OpenSource Computer Vision Library) is an open source computer vision library. It contains a large number of computer vision algorithms and functions, which can help developers quickly build image and video processing related applications. Before using OpenCV, we need to install it first. Fortunately, Python provides a powerful tool pip to manage third-party libraries

1. Theoretical basis of image pyramid Image pyramid is a kind of multi-scale expression of images. It is an effective but conceptually simple structure to explain images at multiple resolutions. An image pyramid is a collection of images with progressively lower resolutions arranged in a pyramid shape and derived from the same original image. It is obtained through ladder down sampling, and the sampling is not stopped until a certain termination condition is reached. We compare images layer by layer to a pyramid. The higher the level, the smaller the image and the lower the resolution. So why do we make an image pyramid? This is because changing the size of a pixel sometimes does not change its characteristics. For example, if you show you a picture of 10 million pixels, you can know that there is a person in it. If you show you a picture of 100,000 pixels, you can also know that there is a person in it. But against the plan

OpenCV is an open source library for computer vision and image processing, which is widely used in machine learning, image recognition, video processing and other fields. When developing using OpenCV, in order to better debug and run programs, many developers choose to use PyCharm, a powerful Python integrated development environment. This article will provide PyCharm users with an installation tutorial for OpenCV, with specific code examples. Step One: Install Python First, make sure you have Python installed

The org.opencv.imgproc package of the JavaOpenCV library contains a class called Imgproc that provides various methods to process input images. It provides a set of methods for drawing geometric shapes on images. To draw an arrowed line, you need to call the arrowedLine() method of this class. The method accepts the following parameters: a Mat object representing the image on which the line is to be drawn. A Point object representing two points between lines. drawn. A Scalar object representing the line color. (BGR) An integer representing the thickness of the line (default: 1). Example importorg.opencv.core.Core;importo

Image segmentation and extraction: Foreground objects are segmented or extracted as target images in images. The background itself is not interested. The watershed algorithm and the GrabCut algorithm segment and extract the image. Use watershed algorithm to achieve image segmentation and extraction. The watershed algorithm vividly compares images to geographical terrain surfaces to achieve image segmentation. This algorithm is very effective. Algorithm Principle Any grayscale image can be regarded as a geographical terrain surface. Areas with high grayscale values ??can be seen as mountain peaks, and areas with low grayscale values ??can be seen as valleys. The image on the left is the original image, and the image on the right is its corresponding "topographic surface". This process separates the image into two distinct sets: catchment basins and watershed lines. The dam we constructed is the watershed line, that is, the original image

1. Project effect 2. Core process 1. openCV reads the video stream and draws a rectangle on each frame of the picture. 2. Use mediapipe to obtain the coordinates of finger key points. 3. Based on the coordinate position of the finger and the coordinate position of the rectangle, determine whether the finger point is on the rectangle. If it is, the rectangle will follow the finger movement. 3. Code process environment preparation: python:3.8.8opencv:4.2.0.32mediapipe:0.8.10.1 Note: 1. If the opencv version is too high or too low, there may be some problems such as the camera not being able to open, crashing, etc. The python version affects opencv Optional versions. 2. pipinstallmediapipe may cause op

Computer Vision (Computer Vision) is one of the important branches in the field of artificial intelligence. It enables computers to automatically perceive and understand visual signals such as images and videos, and realize application scenarios such as human-computer interaction and automated control. OpenCV (OpenSourceComputerVisionLibrary) is a popular open source computer vision library that is widely used in computer vision, machine learning, deep learning and other fields. This article will introduce how to use

How to implement video processing using PHP and OpenCV library? Abstract: Video processing has become an important technology in modern scientific and technological applications. This article will introduce how to use the PHP programming language combined with the OpenCV library to implement some basic video processing functions, and attach corresponding code examples. Keywords: PHP, OpenCV, video processing, code examples Introduction: With the development of the Internet and the popularity of smartphones, video content has become an indispensable part of people's lives. However, to achieve video editing and
