cv2_imshow() 不在 Google Colab 中呈现视频文件

cv2_imshow() doesn't render video file in Google Colab

我正在尝试将一些 OpenCV 图像分析(使用 Python3)从本地 Jupyter 笔记本迁移到 Google Colab。

我原来的 Jupyter Notebook 代码运行良好,视频呈现也很好(在它自己的 Window 中)(请参阅下面的代码子集)。此代码使用 cv2.imshow() 来呈现视频。在 Colab 中使用相同的 "cv2.imshow()" 代码时,视频不会呈现。

基于 - 我在 Colab 中改用 cv2_imshow()。但是,此更改会导致垂直系列的 470 张图像(每帧一张),而不是正在播放的视频。

这里是link to the colab file.

谁能概述一下如何在 Colab 中渲染由 OpenCV 处理的视频?

import numpy as np
import cv2

cap = cv2.VideoCapture(r"C:\.....Blocks.mp4")
counter = 0
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    cv2.imshow(frame)

    print("Frame number: " + str(counter))
    counter = counter+1
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

方法cv2.imshow()显示图像。所以,你所做的基本上是逐帧读取整个视频并显示该帧。要观看整个视频,您需要将这些帧写回 VideoWriter 对象。

因此,在 while 循环之前创建一个 VideoWriter 对象:

res=(360,240) #resulotion
fourcc = cv2.VideoWriter_fourcc(*'MP4V') #codec
out = cv2.VideoWriter('video.mp4', fourcc, 20.0, res)

使用write()方法处理后写入帧

out.write(frame)

最后,按照与 VideoCapture

相同的方式释放对象
out.release()

现在,将在您的视频中写入一个名为 video.mp4

的视频