Steve
Steve

Reputation: 505

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

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

Upvotes: 2

Views: 8931

Answers (1)

Anwarvic
Anwarvic

Reputation: 12992

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

Upvotes: 5

Related Questions