【问题标题】:How to turn a video into numpy array?如何将视频转换为 numpy 数组?
【发布时间】:2017-06-29 00:26:44
【问题描述】:

我在要转换为 numpy 数组的视频所在的文件夹中有一个 python 脚本。我的视频名为“test.mp4”。

在我的脚本中,我想调用 someFunction('test.mp4') 并取回一个 numpy 数组。生成的 numpy 数组应该是一个 numpy 图像数组,其中每个图像都是一个 3-d numpy 数组。

这有意义吗?

谢谢!

【问题讨论】:

标签: python arrays numpy video


【解决方案1】:

下面的脚本可以满足您的需求。您可以将它的一部分分离到函数中。

下面的代码不会检查错误,特别是生产代码会检查每个frame* 变量是否大于零。

import cv2
import numpy as np

cap = cv2.VideoCapture('test.mp4')
frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

buf = np.empty((frameCount, frameHeight, frameWidth, 3), np.dtype('uint8'))

fc = 0
ret = True

while (fc < frameCount  and ret):
    ret, buf[fc] = cap.read()
    fc += 1

cap.release()

cv2.namedWindow('frame 10')
cv2.imshow('frame 10', buf[9])

cv2.waitKey(0)

【讨论】:

  • 请注意,您也可以考虑处理流,因为将整个未压缩视频保存在内存中会很快耗尽物理内存。
  • 将视频转换为 numpy 数组有什么好处?
  • 这段代码需要执行多长时间?是否需要与视频一样长的时间?
【解决方案2】:

skvideo是一个python包,可用于读取视频并存储到多维数组中。

import skvideo.io  
videodata = skvideo.io.vread("video_file_name")  
print(videodata.shape)

更多详情: http://www.scikit-video.org/stable/index.htmlhttp://mllearners.blogspot.in/2018/01/scikit-video-skvideo-tutorial-for.html

【讨论】:

  • 如何转成numpy数组?
  • videodata 仅是 numpy 格式。否则,将 numpy 导入为 np --> temp = np.array(videodata)
  • 这比使用 cv2 更干净更简单
【解决方案3】:

当我们从图像处理的角度来看视频时,我们可以假设它是一系列图像。 从这一点开始,您可以循环播放视频的帧并将它们转换为 numpy 数组。

下面是 PillowOpenCV 库的示例,我将网络摄像头的屏幕截图转换为 numpy 数组:

import cv2
import numpy as np
from PIL import Image, ImageOps    


def screenshot():
    global cam
    cv2.imwrite('screenshot.png', cam.read()[1])


if __name__ == '__main__':
    np.set_printoptions(suppress=True)

    cam = cv2.VideoCapture(0) # You can replace it with your video path
    
    while True:
        ret, img = cam.read()

        cv2.imshow('My Camera', img)

        ch = cv2.waitKey(5)
        if ch == 27:
            break

        screenshot()

        data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

        image = Image.open('screenshot.png')

        size = (224, 224) # Put your suitable size
        image = ImageOps.fit(image, size, Image.ANTIALIAS)

        image_array = np.asarray(image) # Here, an image -> numpy array
        print(image_array)

    cv2.destroyAllWindows()

【讨论】:

    猜你喜欢
    • 2021-07-19
    • 2021-08-11
    • 2021-04-03
    • 2021-12-18
    • 2017-07-21
    • 2011-09-23
    • 2022-10-25
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多