【问题标题】:How to create array of frames from an mp4 with opencv for python如何使用opencv for python从mp4创建帧数组
【发布时间】:2017-05-06 08:31:37
【问题描述】:

我正在尝试使用 opencv_python 将 mp4 文件分解为帧,以便以后可以用枕头打开它们,或者至少能够使用图像在它们上运行我自己的方法。

我了解以下 sn-p 代码从实时视频或录制的视频中获取帧。

    import cv2
    cap = cv2.VideoCapture("myfile.mp4")
    boolean, frame = cap.read()

read 函数究竟返回什么以及如何创建可以修改的图像数组。

【问题讨论】:

标签: python opencv video


【解决方案1】:

改编自How to process images of a video, frame by frame, in video streaming using OpenCV and Python。未经测试。但是,这些帧被读入一个 numpy 数组并附加到一个列表,当所有帧都被读入时,该列表将转换为一个 numpy 数组。

import cv2
import numpy as np


images = []

cap = cv2.VideoCapture("./out.mp4")
while not cap.isOpened():
    cap = cv2.VideoCapture("./out.mp4")
    cv2.waitKey(1000)
    print "Wait for the header"

pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
    frame_ready, frame = cap.read() # get the frame
    if frame_ready:
        # The frame is ready and already captured
        # cv2.imshow('video', frame)

        # store the current frame in as a numpy array
        np_frame = cv2.imread('video', frame)
        images.append(np_frame)
        
        pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
    else:
        # The next frame is not ready, so we try to read it again
        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
        print "frame is not ready"
        # It is better to wait for a while for the next frame to be ready
        cv2.waitKey(1000)

    if cv2.waitKey(10) == 27:
        break
    if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
        # If the number of captured frames is equal to the total number of frames,
        # we stop
        break

all_frames = np.array(images)

【讨论】:

  • 非常感谢。感谢您注释掉代码。我喜欢对它有很好的理解
  • 没问题,很高兴能帮上忙。如果有效,请考虑将其标记为答案。
  • 嘿,我有个小问题。
  • np_frame = cv2.imread('video', frame) 返回此错误,我不知道该怎么办:
  • cv2.imread('video', frame) throws TypeError: 'flags' is required to be an integer
猜你喜欢
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多