From 2387fa21d16ca8d3509d1c5e54b6e2f73f869d3f Mon Sep 17 00:00:00 2001 From: Ahmad Sharif Date: Wed, 26 Jun 2024 12:28:55 -0700 Subject: [PATCH] [torchcodec] Add a simple example showing how to decode the first frame of a video (#51) Summary: Add a basic example of how to decode a frame from a video. Pull Request resolved: https://github.com/pytorch-labs/torchcodec/pull/51 Differential Revision: D59022932 --- examples/basic_example.py | 33 ++++++++++++++++++++++++++++ examples/basic_example_remove_me.py | 34 ----------------------------- 2 files changed, 33 insertions(+), 34 deletions(-) create mode 100644 examples/basic_example.py delete mode 100644 examples/basic_example_remove_me.py diff --git a/examples/basic_example.py b/examples/basic_example.py new file mode 100644 index 00000000..d66acbd2 --- /dev/null +++ b/examples/basic_example.py @@ -0,0 +1,33 @@ +""" +================================================== +Basic Example to use TorchCodec to decode a video. +================================================== +""" + +# A simple example showing how to decode the first few frames of a video. +# using the :class:`~torchcodec.decoders.SimpleVideoDecoder` class. +# %% +import inspect +import os + +from torchcodec.decoders import SimpleVideoDecoder + +my_path = os.path.abspath(inspect.getfile(inspect.currentframe())) +video_file_path = os.path.dirname(my_path) + "/../test/resources/nasa_13013.mp4" +simple_decoder = SimpleVideoDecoder(video_file_path) +# Since `simple_decoder` is an iterable, you can get the total frame count for +# the best video stream by calling len(). +num_frames = len(simple_decoder) +print(f"{video_file_path=} has {num_frames} frames") + +# You can get the decoded frame by using the subscript operator. +first_frame = simple_decoder[0] +print(f"decoded frame has type {type(first_frame)}") +print(f"{first_frame.shape=}") + +last_frame = simple_decoder[num_frames - 1] +print(f"{last_frame.shape=}") + +# TODO: add documentation for slices and metadata. + +# %% diff --git a/examples/basic_example_remove_me.py b/examples/basic_example_remove_me.py deleted file mode 100644 index e01bc496..00000000 --- a/examples/basic_example_remove_me.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -============= -Basic Example -============= - -Remove this! -""" - -# %% -print("This is a cell that gets executerd") -# %% -print("And another cell.") - -# %% -# We can write rst cells too! -# --------------------------- -# -# As if we're writing normal docs/docstrings. Let's reference the -# :class:`~torchcodec.decoders.SimpleVideoDecoder` class. Click on this and it -# should bring you to its docstring!! In the docstring, you should see a -# backreference to this example as well! -# -# And of course we can write normal code - -# %% -from torchcodec.decoders import SimpleVideoDecoder - -try: - SimpleVideoDecoder("bad_path") -except ValueError as e: - print(f"Ooops:\n {e}") - -# %% -print("All good!")