opencv (python) video slicing by frame/cv2.VideoCapture() usage

1. Introduction

cv2.VideoCapture is a class in OpenCV used to capture videos. It can access your computer's camera, or read images from video files. With cv2.VideoCapture, users can easily capture, save, edit and transfer video streaming data.

Using cv2.VideoCapture you can achieve the following functions:

1. Turn on the computer's camera and capture the camera's video stream data in real time.
2. Read the video file, decode it frame by frame and output the video stream data.
3. Control the frame rate and adjust the video playback speed.
4. Control the length, width and resolution of the video.
5. Edit video stream data, such as adding watermarks, merging videos, etc.
6. Transmit video data, video streaming data can be transmitted through the network.

The most commonly used methods in cv2.VideoCapture are:

1. read(): Read a frame in the video stream data.
2. isOpened(): Check whether the current cv2.VideoCapture has been opened.
3. release(): Release the resources occupied by the cv2.VideoCapture object.

For example, the following code shows how to use the cv2.VideoCapture object to open the computer's camera and capture live video:


import cv2

cap = cv2.VideoCapture(0)  # 打开计算机的摄像头

while True:
    ret, frame = cap.read()  # 读取视频流数据中的一帧

    cv2.imshow('frame', frame)  # 显示捕获的视频流数据

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()  # 释放占用的资源
cv2.destroyAllWindows()

2. cv2.VideoCapture() video acquisition operation

1. Read video from file

The parameter is the video file path, and the opening method is as follows:

videoCapture = cv2.VideoCapture(“../test1.mp4”) #.avi等视频文件

2. Read video from camera

 The parameter in VideoCapture (0) is 0, which means turning on the notebook's built-in camera. If there are multiple cameras, just add more.

videoCapture = cv2.VideoCapture(0)
If you want to read the video stream of a surveillance camera, you need to know the IP address of the specified camera and other information.
# 使用rtsp流打开相机
videoCapture = cv2.VideoCapture(f'rtsp://{username}:{password}@{ip}:{port}/h264/ch1/main/av_stream')

3. videoCapture.read() reads content by frame

# 读帧
success, frame = videoCapture.read()
print(success)
print(frame)
Success and frame are the two return values ​​of the .read() method. Success is a Boolean value. If the read frame is correct, it returns True. If the file is read to the end, its return value is False. Frame is the image of each frame, which is a three-dimensional matrix.

In the following example, we use the default camera (device number 0) as input, and then use a while loop to read the video frame by frame and display it in the window. If the 'q' key is pressed or the video cannot be read, exit the loop and release the resource.

import cv2

# 创建 VideoCapture 对象
cap = cv2.VideoCapture(0)

# 循环读取视频流
while True:
    # 逐帧读取视频
    ret, frame = cap.read()

    # 如果不能读取视频,退出循环
    if not ret:
        break

    # 在窗口中显示视频帧
    cv2.imshow("frame", frame)

    # 检测键盘输入,按 'q' 键退出循环
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

# 释放资源并关闭窗口
cap.release()
cv2.destroyAllWindows()

What is a frame, what is the speed of a frame, and what is its impact? The
        basic component of video is a frame, that is, a series of static images that are played in a continuous manner at a certain rate to form a dynamic image, such as 30 frames/second. . The number of frames per second of a video is called the frame rate (Frame Rate), usually expressed as "fps" (Frames Per Second). For example, 30fps means that the video contains 30 frames per second. The frame rate determines the smoothness and realism of the video. Higher frame rates can make videos look smoother because they refresh the image faster. For example, a 60fps video looks smoother than a 30fps video. Additionally, higher frame rates can also reduce blur and judder in videos because they capture motion better. But higher frame rates result in larger files and more complex codecs because more frames need to be processed.
————————————————
https://blog.csdn.net/cvxiayixiao/article/details/130519349

4. Examples

import os
import cv2


# 定义保存图片函数
# image:要保存的图片
# pic_address:图片保存地址
# num: 图片后缀名,用于区分图片,int 类型
def save_image(image, address, num):
    pic_address = address + str(num) + '.jpg'
    cv2.imwrite(pic_address, image)


def video_to_pic(video_path, save_path, frame_rate):
    # 读取视频文件
    # video_path为视频路径,save_path为保存图片路径,frame_rate可以设置多少帧切一张图

    global videoCap
    #这里将videoCapture加global意思是设置成了全局变量,后面释放摄像头要用到这个变量

    videoCap = cv2.VideoCapture(video_path)

    if videoCap.isOpened():
        print("摄像头or视频打开成功")
    if not videoCap.isOpened():
        print("找不到摄像头or视频")
        exit()

 
    # 读帧
    success, frame = videoCap.read()
    """success,frame是获.read()方法的两个返回值。 
    其中success是布尔值,如果读取帧是正确的则返回True,如果文件读取到结尾,它的返回值就为False。
    frame就是每一帧的图像,是个三维矩阵。"""
    # print(success)
    # print(frame)
    if videoCap.open(video_path):
        print("视频提取成功")
    if not videoCap.open(video_path):
        print("can not open the video")

    j = 0
    i = 0
    while success:
        i = i + 1
        # 每隔固定帧保存一张图片
        if i % frame_rate == 0:
            j = j + 1
            save_image(frame, save_path, j)
            print('图片保存地址:', save_path + str(j) + '.jpg')
        success, frame = videoCap.read()
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break


if __name__ == '__main__':


    # 视频文件和图片保存地址
    SAMPLE_VIDEO = 'F:/Capture/dist/video/sc0914.mp4'
  
    SAVE_PATH = 'F:/Capture/dist/VideotoImages/sc0914/'
    #注意保存本地路径不能有中文,save_image()以及imwrite、cv2.imread()均不支持有中文的路径

    if not os.path.exists(SAVE_PATH):
        os.makedirs(SAVE_PATH)

    # 设置固定帧率
    FRAME_RATE = 10
    video_to_pic(SAMPLE_VIDEO, SAVE_PATH, FRAME_RATE)


# 调用release()释放摄像头
# 调用destroyAllWindows()关闭所有图像窗口。
videoCap.release()
cv2.destroyAllWindows()

Guess you like

Origin blog.csdn.net/m0_63172128/article/details/132733548