簡體   English   中英

如何使用python的opencv從mp4創建幀數組

[英]How to create array of frames from an mp4 with opencv for python

我正在嘗試使用opencv_python將mp4文件分解為框架,以便以后可以用枕頭打開它們,或者至少能夠使用圖像在它們上運行我自己的方法。

我了解以下代碼段是從實況視頻或錄制的視頻中獲取幀。

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

讀取函數返回的確切信息是什么,以及如何創建可以修改的圖像數組。

改編自《 如何使用Opencv 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:
    boolen, frame = cap.read() # get the frame
    if flag:
        # 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM