如何使用 opencv-python 提取视频每一帧的图片?

发布时间 2023-08-04 10:04:44作者: 白桦的天空

参考:https://blog.csdn.net/u013066730/article/details/126356627

获取视频(创建 VideoCapture 对象)

使用 cv2.VideoCapture 类

Args:

  • filename – 文件路径;
  • device – 视频设备id ,若只有一个摄像头可以填 0,表示打开默认摄像头;
    vc = cv2.VideoCapture(filename)
    

    检验 VideoCapture 对象是否创境成功

    使用 VideoCapture 对象的 isOpened 方法

    # determine whether to open normally
    if vc.isOpened():
        ret, frame = vc.read()
    else:
        ret = False
    

      

    若成功,返回 True。

    按帧读取视频

    使用 VideoCapture 对象的 read 方法

    使用 VideoCapture 对象的 read 方法按帧读取视频,ret, frame 是 read 方法的两个返回值 ,其中 ret 是布尔值,如果能正确读取帧,则返回 True;如果文件读取到结尾,它的返回值就为 False。frame 就是每一帧的图像,是一个三维矩阵。

    # loop read video frame
    while ret:
        ret, frame = vc.read()
    

      

    保存图片

    使用 cv2.imwrite() 函数

    第一个参数是文件名,第二个参数是图片资源。

  • cv2.imwrite(image_path, image)