OpenCV realizes video reading, display and saving

Table of contents

1. Read the video from the file and play it

1.2 Code implementation

1.3 Effect display

2. Save the video

2.1 Code implementation

2.2 Result display


1. Read the video from the file and play it

In OpenCV we need to get a video, we need to create a VideoCapture object and specify the video file you want to read:

(1) Create an object to read the video

cap = cv.VideoCapture(filepath) parameter: video file path

(2) Certain attributes of the video

(3) Determine whether the image is read successfully

(4) Get a frame of video

(5) Call cv.imshow to display the image. Use cv.waitkey() to set the appropriate duration when displaying the image. If it is too low, the video will play very fast. If it is too high, it will play very slowly. Normally, set is  25  ms

(6) Call cap.release() to release the video

1.2 Code implementation

import numpy as np
import cv2 as cv

#获取视频对象
cap = cv.VideoCapture(r'E:\All_in\opencv\video.mp4')
#判断是否读取成功

while(cap.isOpened()):
    #获取某一帧图像
    ret , frame = cap.read()
    #获取成功显示图像
    if ret == True:
        cv.imshow('frame',frame)
    #每一帧间隔25ms
    if cv.waitKey(25)& 0xFF == ord('q'):
        break

#释放视频对象
cap.release()
cv.destroyWindow()

1.3 Effect display

2. Save the video

2.1 Code implementation

import cv2 as cv
import numpy as np

#读取视频
cap = cv.VideoCapture(r'E:\All_in\opencv\video.mp4')

#获取图像的属性(宽和高),并将其转化为整数
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

#创建保存图像的对象 , 设置编码格式,帧率,图像的宽 高等
'''函数第一个参数为输出文件路径,因为我们想保存为AVI格式,所以要指定编码格式为'M','J','P','G'(MJPEG压缩)
,帧率设置为10,视频帧的宽高设置为前面获取到的frame_width和frame_height。'''
out = cv.VideoWriter('outpy.avi',cv.VideoWriter_fourcc('M','J','P','G'),10,(frame_width,frame_height))
while(True):
    #获取视频中每一帧图像
    ret ,frame= cap.read()
    if ret==True:
        #将每一帧图像写入输出文件中
        out.write(frame)
    else:
        break

#释放资源
cap.release()
out.release()
cv.destroyAllWindows()

2.2 Result display

Guess you like

Origin blog.csdn.net/qq_53545309/article/details/133465326