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

大城市里の小女人 提交于 2020-05-31 07:32:18

问题


I am attempting to migrate some OpenCV image analysis (using Python3) from a local Jupyter notebook to Google Colab.

My original Jupyter Notebook code works fine, and the video renders fine (in its own Window) (see a subset of the code below). This code uses cv2.imshow() to render the video. When using the same "cv2.imshow()" code in Colab, the video doesn't render.

Based on this suggestion - I switched to using cv2_imshow()in Colab. However, this change leads to a vertical series of 470 images (1 for each frame), rather than the video being played.

Here is a link to the colab file.

Can anyone outline how to render the video processed by OpenCV within Colab?

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()

回答1:


The method cv2.imshow() shows an image. So, what you are doing is basically reading the whole video frame by frame and showing that frame. To see a whole video, you need to write these frames back to a VideoWriter object.

So, create a VideoWriter object before the while loop:

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

Write the frame after processing using write() method

out.write(frame)

Finally, release the object the same way you did with the VideoCapture

out.release()

Now, a video will be written in your with the name video.mp4



来源:https://stackoverflow.com/questions/58924926/cv2-imshow-doesnt-render-video-file-in-google-colab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!