美文网首页程序员
opencv读写视频流

opencv读写视频流

作者: 远叔 | 来源:发表于2018-03-31 10:44 被阅读0次

    #环境:opencv 3.4.0    python 3.5.2

    #读取视频

    import cv2

    cap = cv2.VideoCapture('video.avi')

    #读取摄像头,0为摄像头索引,当有多个摄像头时,从0开始编号

    cap = cv2.VideoCapture(0)

    #从视频或摄像头中读取一帧(即一张图像),返回是否成功标识ret(True代表成功,False代表失败),img为读取的视频帧

    ret,frame = cap.read()


    #完整的读取视频流并播放视频流代码

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

    import cv2

    cap = cv2.VideoCapture("video.avi")

    while(1):

    # 读取视频帧

        ret, frame = cap.read()

    # 显示视频帧

        cv2.imshow("capture", frame)

    #等候50ms,播放下一帧,或者按q键退出

    if cv2.waitKey(50) &0xFF ==ord('q'):

        break

    #释放视频流

    cap.release()

    #关闭所有窗口

    cv2.destroyAllWindows()


    #创建视频流写入对象,VideoWriter_fourcc为视频编解码器,20为帧播放速率,(640,480)为视频帧大小

    videoWriter = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc('I', '4', '2', '0'), 20, (640,480))

    #向视频文件写入一帧

    videoWriter.write(frame)

    #详解cv2.VideoWriter_fourcc对象(摘自Learning OpenCV3 Computer Vision with Python,坦白讲不太懂)

    #fourcc意为四字符代码(Four-Character Codes),顾名思义,该编码由四个字符组成,下面是VideoWriter_fourcc对象一些常用的参数,注意:字符顺序不能弄混

    #cv2.VideoWriter_fourcc('I', '4', '2', '0'),该参数是YUV编码类型,文件名后缀为.avi

    #cv2.VideoWriter_fourcc('P', 'I', 'M', 'I'),该参数是MPEG-1编码类型,文件名后缀为.avi

    #cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),该参数是MPEG-4编码类型,文件名后缀为.avi

    #cv2.VideoWriter_fourcc('T', 'H', 'E', 'O'),该参数是Ogg Vorbis,文件名后缀为.ogv

    #cv2.VideoWriter_fourcc('F', 'L', 'V', '1'),该参数是Flash视频,文件名后缀为.flv

    #以下为写视频的完整代码

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

    import cv2

    cap = cv2.VideoCapture('./dataset/video/cap_zhihao.avi')

    fps =int(cap.get(cv2.CAP_PROP_FPS))

    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),

    int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

    videoWriter = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc('I','4','2','0'), fps, size)

    ret, frame = cap.read()

    while(ret):

        # 展示一帧

        cv2.imshow("capture", frame)

        videoWriter.write(frame)

        cv2.waitKey(fps)

        ret,frame = cap.read()

    cap.release()

    cv2.destroyAllWindows()

    相关文章

      网友评论

        本文标题:opencv读写视频流

        本文链接:https://www.haomeiwen.com/subject/tkuwcftx.html