pythongoogle-colaboratorytorchvision

`AttributeError` constructing `torchvision.io.VideoReader` in Google Colab


I'm trying to write a program that will use torchvision.io.VideoReader to extract a number of still images from a set of video files. This program is expected to run on Google Colab. Unfortunately, even though torchvision 0.18.0 is available on Colab's runtime, when I try to create a VideoReader object I get an AttributeError raised with the message 'ImportError' object has no attribute 'open'.

Full code of my Colab notebook:

import torch
import torchvision
import os
from google.colab import drive

driveLoc = '/content/drive'

if os.path.exists(driveLoc):
  print ("Drive already mounted")
else:
  print ("Mounting drive")
  drive.mount(driveLoc)

vpath = driveLoc + "/MyDrive/videos"
datafiles = os.listdir(vpath)
for f in datafiles:
  if not os.path.isfile(vpath+"/"+f):
    continue
  print (f)

  video = torchvision.io.VideoReader(vpath+"/"+f, "video")
  print (video.get_metadata())

Full traceback:

AttributeError                            Traceback (most recent call last)

<ipython-input-7-1051bd84b049> in <cell line: 16>()
     19   print (f)
     20 
---> 21   video = torchvision.io.VideoReader(vpath+"/"+f, "video")
     22   print (video.get_metadata())
     23 

/usr/local/lib/python3.10/dist-packages/torchvision/io/video_reader.py in __init__(self, src, stream, num_threads)
    157 
    158         elif self.backend == "pyav":
--> 159             self.container = av.open(src, metadata_errors="ignore")
    160             # TODO: load metadata
    161             stream_type = stream.split(":")[0]

AttributeError: 'ImportError' object has no attribute 'open'

Just running this on the default Colab runtime, with no extra packages installed. I presume I need to install something else, but the error gives me no clue as to what...


Solution

  • This error is caused by not having a sufficiently recent version of PyAV installed on the system when you import torchvision. Adding !pip install av==11.0.0 at the top of the file solved the issue for me; fixing the version at 11.0.0 was necessary to avoid this problem.