cv2读写视频

目录

1、视频读取

2、视频写入


1、视频读取

def video_read():
    video_path = r"03000003810000000.mp4"
    capture = cv2.VideoCapture(video_path)
    if not capture.isOpened():
        print("打开视频失败!")

    fps = capture.get(cv2.CAP_PROP_FPS)
    size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
            int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    fNUMS = capture.get(cv2.CAP_PROP_FRAME_COUNT)
    print("fps:", fps)
    print("size:", size)
    print("fNUMS:", fNUMS)

    cv2.namedWindow("test", 0)
    cv2.moveWindow("test", 100, 100)
    cv2.resizeWindow("test", 960, 640)
    f_cnt = 0
    while True:
        _, frame = capture.read()
        if frame is None:
            break
        f_cnt += 1

        # img proc ...
        cv2.waitKey(30)
        cv2.imshow("test", frame)
    capture.release()

函数解析:

1、打开视频文件,初始化视频类对象

capture = cv2.VideoCapture(file_path)

或:

capture = cv2.VideoCapture() capture .open(self.args.VIDEO_PATH) # 打开视频

2、判断视频是否打开

capture.isOpened() # 成功则返回True

3、获取帧率、宽、高get()

fNUMS = capture.get(cv2.CAP_PROP_FPS) # 帧率

size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) # 宽、高

CV_CAP_PROP_FRAME_COUNT # 总帧数    

4、读取视频流

方法1:

_, frame = capture.read() # 结合grab、retrieve方法

方法2:

capture.grab() # 从视频文件或捕获设备中抓取下一个帧,假如调用成功返回true
capture.retrieve(frame); # 解码并且返回刚刚抓取的视频帧,假如没有视频帧被捕获将返回false

5、释放视频对象

capture.release()

VideoCapture 类基础知识

1、https://blog.csdn.net/u010368556/article/details/79186992

2、视频写入

# coding:utf8
import cv2
"""
    读取视频文件的帧, 采用yuv颜色编码写入到另一个帧
    VideoCapture和VideoWriter用于视频文件的读写
    VideoCapture读的每一帧都是一个bgr格式的图像
"""

videoCapture = cv2.VideoCapture("../data/demo3.mp4")
fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (
     int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
     int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
)
 
videoWriter = cv2.VideoWriter(
     "output.mp4",
     cv2.VideoWriter_fourcc("M", "J", "P", "G"),  # 编码器
     fps,
     size
)

'''
编码器常用的几种:
cv2.VideoWriter_fourcc("M", "J", "P", "G")  
#  视频MP4

cv2.VideoWriter_fourcc("I", "4", "2", "0") 
#    压缩的yuv颜色编码器,4:2:0色彩度子采样 兼容性好,产生很大的视频 avi

cv2.VideoWriter_fourcc("P", "I", "M", "I")
#    采用mpeg-1编码,文件为avi

cv2.VideoWriter_fourcc("X", "V", "T", "D")
#    采用mpeg-4编码,得到视频大小平均 拓展名avi

cv2.VideoWriter_fourcc("T", "H", "E", "O")
#    Ogg Vorbis, 拓展名为ogv

cv2.VideoWriter_fourcc("F", "L", "V", "1")
#    FLASH视频,拓展名为.flv
'''
 
success, frame = videoCapture.read()
while success:  # 循环直到没有帧了
     cv2.imshow("test", frame)
     cv2.waitKey(1)
     videoWriter.write(frame)
     success, frame = videoCapture.read()
videoWriter.release()

 

你可能感兴趣的:(python语言,python,opencv,ffmpeg,videocapture,videwriter)