Python学习

opencv(2)视频处理

2020-09-18  本文已影响0人  TZX_0710

采用opencv读取视频并且显示和保存视频

import cv2 as cv


# 读取摄像头的视频
def readVideo():
    # 打开电脑摄像头
    cap = cv.VideoCapture(0)
    # 如果摄像头没有打开
    if not cap.isOpened():
        print("cannot open video")
        exit()
    while True:
        # 逐桢播放 ret返回值true或者false  true表示读取到了  false表示未读取到
        ret, frame = cap.read()
        if not ret:
            # 无法读取到
            print("can't receive frame")
            break
        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        cv.imshow("frame", gray)
        # 输入q的时候进行停止
        if cv.waitKey(1) == ord('q'):
            break
    cap.release()
    cv.destroyAllWindows()


# 读取摄像头的视频
def writeVideo():
    cap = cv.VideoCapture(0)
    # 定义编解码器并创建VideoWriter对象
    fourcc = cv.VideoWriter_fourcc(*'XVID')
    out = cv.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break
        # 图像翻转
        frame = cv.flip(frame, -1)
        # 写翻转的框架
        out.write(frame)
        cv.imshow('frame', frame)
        if cv.waitKey(1) == ord('q'):
            break
    # 完成工作后释放所有内容
    cap.release()
    out.release()
    cv.destroyAllWindows()


if __name__ == '__main__':
    # readVideo()
    writeVideo()

上一篇 下一篇

猜你喜欢

热点阅读