python + opencv 第三节 视频文件的读取和保存

#本节讲解视频的读取,显示和保存
# 1. cv2.VideoCapture()
# 有两种用法
# cv2.VideoCapture(filename)
# filename : 要打开的视频
# cv2.VideoCapture(device)
# device : 要打开的摄像头,如果要打开默认摄像头,则填 0 ,如笔记本自带的摄像头
import cv2
cap = cv2.VideoCapture('video_1.avi')
# 读取视频
# while(cap.isOpened()):
#     ret, frame  = cap.read()
#     if ret == False:
#         break
#     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#     cv2.imshow('frame', gray)
#     cv2.waitKey(10)
# k = cv2.waitKey(0)
#
# if k == 27:
#     cap.release()
#     cv2.destroyAllWindows()

# 保存视频
# 1.指定 FourCC 编码 FOURCC is short for "four character code"
# FOURCC是four character code“四个字符代码”的缩写
# -媒体文件中使用的视频编解码器,压缩格式,颜色或像素格式的标识符。
# FourCC 就是一个4字节码,用来确定视频的编码格式。
# 可用的编码可以查看 http://www.fourcc.org/codecs.php, 推荐使用 ”XVID"
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
# def VideoWriter_fourcc(c1, c2, c3, c4): # real signature unknown; restored from __doc__
#     """
#     VideoWriter_fourcc(c1, c2, c3, c4) -> retval
#     .   @brief Concatenates 4 chars to a fourcc code
#     .
#     .       @return a fourcc code
#     .
#     .       This static method constructs the fourcc code of the codec to be used in the constructor
#     .       VideoWriter::VideoWriter or VideoWriter::open.
#     """
#     pass

# 2.创建一个 ViDeoWrite 对象
# VideoWriter(filename, fourcc, fps, frameSize[, isColor]) -> <VideoWriter object>
# 第一个参数是要保存的文件的路径
# fourcc 指定编码器
# fps 要保存的视频的帧率
# frameSize 要保存的文件的画面尺寸
# isColor 指示是黑白画面还是彩色的画面
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (960, 528), True)

# flip(src, flipCode[, dst]) -> dst
# filp函数用于图像翻转
# src -- 原始图像矩阵
# dst -- 变换后矩阵
# flipCode -- 翻转模式,有三种
#    0 : 垂直方向翻转
#    1 : 水平方向翻转
#    2 : 水平/垂直方向同时翻转

while(cap.isOpened()):
    ret, frame = cap.read()
    # size = frame.shape
    if ret == True:
        frame = cv2.flip(frame, 0) #垂直方向翻转,返回翻转后的图像
        out.write(frame) #翻转后的图像写入
        cv2.imshow('frame', frame)
        if cv2.waitKey(10) & 0xFF == ord('q'):
            break
    else:
        break
#释放对象
cap.release()
out.release()
#关闭窗口
cv2.destroyAllWindows()
发布了80 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qiukapi/article/details/104440014