欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenCV读写视频文件

程序员文章站 2022-05-16 14:06:44
...

OpenCV提供了VideoCapture类来支持视频读/写。VideoCapture类通过read()函数来获取每一帧,即一个RGB图像。

本文用到的视频traffic.flv,来源于原作者Github,地址为: 
https://github.com/techfort/pycv/tree/master/chapter8/surveillance_demo

 

OpenCV读取视频并显示

# -*- coding:utf-8 -*-

import cv2

cap = cv2.VideoCapture('video/traffic.flv')

while True:
    ret, frame = cap.read() # 读
    cv2.imshow("capture", frame) # 显示
    if cv2.waitKey(100) & 0xFF == ord('q'): #键盘按键q,退出
        break

 

OpenCV写入视频

# -*- coding:utf-8 -*-

import cv2

# Step1. 调用VideoCapture构造器
cap = cv2.VideoCapture('video/traffic.flv')
fps = cap.get(cv2.CAP_PROP_FPS)
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

# Step2. 改用YUV颜色编码 写入到另一个视频文件中
# 注意,视频文件的后缀改为.avi,由于I420采用YUV颜色编码,只支持.avi格式
writer = cv2.VideoWriter('video/trafficOutput.avi', cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps, size)
ret, frame = cap.read()
while ret:
    writer.write(frame)
    ret, frame = cap.read()


# Step3.读取新的文件
cap = cv2.VideoCapture('video/trafficOutput.avi')
while True:
    ret, frame = cap.read() # 读
    cv2.imshow("capture", frame) # 显示
    if cv2.waitKey(100) & 0xFF == ord('q'): #键盘按键q,退出
        break

 

 

 

 

相关标签: python-opencv