Reversing a video using python

·

5 min read

HOW TO REVERSE A VIDEO USING PYTHON (OPENCV)

1. What is reversing a Video?

Reversing a video refers to playing a clip backward. It creates interesting visual effects, We are used to seeing events unfold chronologically. Seeing a reversed video can seem odd or humorous since it goes against our expectations.

There are a few different technical ways to achieve this. A common approach is video editing software, but it does not work for everyone. We can do the same using a Python program.

2. Reverse effects through Python automation

I use OpenCV computer vision libraries to automate reverse videos. The process involves extracting frames, iterating backward then exporting the reversed frames into a new video. This gives me more

flexibility to customize the effect compared to using editing software presets.

3. Prerequisites

1. Basic proficiency in Python programming, knowledge of syntax, functions, etc...

2. Understanding general programming concepts like variables, loops, and conditionals.

3. Familiar with pip/conda for installing packages in Python.

4. OS-level file system navigation for loading and saving files.

5. Code editor or IDE installed jupyter notebook, VS code, etc...

4. Overview of using Python and OpenCV for video reversal

If you are familiar with Python programming language and the OpenCV library means you can skip this part, Code samples are available in part 5.

4.1 Python

    1. Python is a high-level interpreted programming language great for automation and workflows.

      1. It has a simple and readable syntax that makes it easy to write complex code for tasks like video manipulation.

      2. Python has many libraries and packages for scientific computing, matrix operations, image processing, etc...

      3. Python provides complete control over the algorithm and customization of parameters at each step.

      4. For video reversing Python can implement logic to iterate through extracted video frames in reverse order.

      5. Download Python here.

4.2 OpenCV

    1. OpenCV is an open-source computer vision and machine learning library with 2500+ algorithms.

      1. CV2 name of the main module that provides access to OpenCV functionality in Python.

      2. With this we can replicate the functions of core OpenCV C++ functions, but in a Pythonic way.

      3. I use OpenCV with Python 3 for best compatibility with the cv2 module.

      4. OpenCV installation on Windows is here. The provided link is the official documentation by OpenCV.

5. Extraction and processing frames with code samples

  1. First import the cv2 module in your code editor.

  2. Initialize a variable called frame counter to 0. to keep track of how many frames have been extracted.

  3. Load the video using cv2.VideoCapture() method which is available in the cv2 library.

  4. read() method is available in cv2 to read the frames in the video.

  5. Specify the path where the frames need to be extracted.

  6. Loop through frames with a while loop, reading a frame with each iteration.

  7. Save the frames "frameXX.jpg" with a customized name. Don't forget to add the extension.

  8. Increment the frame counter at the end.

Sample code:

```import cv2

video="path_of_your_video"

vid=cv2.VideoCapture(video)

count=0

success=1

extracted_frame_path="path_to_store_the_extracted_frames"

while success:

success, img = vid.read()

if not success:

print("All frames are extracted")

break

filename = extracted_frame_path + "\\frame%d.jpg" % count

cv2.imwrite(filename, img)

count += 1```

Output

Once all frames are extracted means you will get an output like "All frames are extracted". Also, check whether frames are saved in specified locations in your system.

6. Reversing the video

  1. Assign a variable to the path where your extracted frames are saved.

  2. Specify the output path where your reversed video will be saved.

  3. Create a list of frame file names and iterate the list in reversed order

  4. Generate FOURCC to code that specifies the video codec. fourcc refers to "four character code" which specifies the video codec used to encode the output video. VideoWriter_fourcc() is an OpenCV function that takes fourcc code and returns a 32-bit integer that OpenCV can use internally. If you feel confused about the terms means check out VideoWriter (official documentation from OpenCV for better understanding).

  5. We pass the string 'MPEG' to VideoWriter_fourcc(), MPEG stands for Moving Pictures Experts Groups and refers to a family of video compression.

  6. We pass in the output file path, FourCC, frames per second, and frame resolution. This configures the video encoding settings.

  7. In the loop, we load each frame JPEG image, make sure it is loaded properly, and pass it to the VideoWriter's .write() method to append it to the video.

  8. Finally, we call output_vid.release() to finish writing the file once all frames are processed.

    This combines the individual frame images into a complete video encoded with the given settings. The reverse ordering results in the backward video.

  9. If there are any errors reading the frames means you will be indicated in the editor with the specific error.

  10. output_vid.release() used to finish writing a video once all frames have been written.

Code:

```

frame_path = "Frames_path"

output_video_path = "reversed_vid.mp4"

frame_count = "total frames of your video"

frame_names = [f"{frame_path}\\frame{i}.jpg" for i in range(frame_count - 1,-1, -1)]

fourcc = cv2.VideoWriter_fourcc(*'MPEG')

output_vid = cv2.VideoWriter(output_video_path, fourcc, 48, (1920, 1080))

for filename in frame_names:

img = cv2.imread(filename)

if img is None:

print(f" Error reading file {filename}")

else:

output_vid.write(img)

output_vid.release()```

Conclusion

This is a simple process to reverse a video using a Python programming language. We just extracted frames from a video and read those in reverse order to make a reversed video.

contact: ragnorlothbrok2004@gmail.com

SHARE

SHARE