2

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()
GPPK
  • 6,546
  • 4
  • 32
  • 57
Steve
  • 475
  • 4
  • 12
  • 25
  • `imshow` creates the window on whatever machine the code runs on. In case of Jupyter notebook it runs on the Jupyter server. When you're running the server locally, you see the window on your machine. However, when you run it on Colab, it's executed on some machine in a datacenter, who knows where... – Dan Mašek Nov 19 '19 at 19:35

1 Answers1

5

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

Anwarvic
  • 12,156
  • 4
  • 49
  • 69