Cropping Videos with OpenCV: A Complete Guide

Your complete guide to cropping videos with OpenCV. Follow our step-by-step guide with code examples

Updated March 18, 2023


Hey! If you love Computer Vision and OpenCV as much as I do let's connect on Twitter or LinkedIn. I talk about this stuff all the time and build cool projects.


Video cropping is a common preprocessing step in computer vision applications. It involves extracting a smaller, focused region from a larger video frame. This is useful for reducing the processing time, removing unwanted content, or highlighting specific areas of interest.

Cropping is a simple geometric operation that involves selecting a rectangular region within the image and removing everything outside that region. In this tutorial, we’ll be using the popular OpenCV library, which offers a wide array of tools and functions for computer vision tasks.

Setting Up the Environment

Before we begin, let’s ensure that you have OpenCV installed. If you haven’t installed it yet, follow the instructions on the official OpenCV installation guide. Once OpenCV is installed, we can get started with our video cropping tutorial.

Theory Behind Video Cropping

When cropping a video, we need to understand its frame structure. A video is a sequence of images, or frames, played in quick succession. Each frame has a specific width and height, and every pixel within the frame has a unique coordinate (x, y). To crop a video, we must extract a rectangular region from each frame using the specified coordinates.

In OpenCV, the coordinate system starts from the top-left corner of the image. The x-axis extends horizontally, while the y-axis extends vertically.

When cropping a video, we define a rectangular region using two sets of coordinates:

  1. The top-left corner (x1, y1)
  2. The bottom-right corner (x2, y2)

These coordinates help us extract the region of interest (ROI) from each frame.

Cropping a Video with OpenCV

Let’s walk through a step-by-step example of cropping a video using OpenCV. We’ll use a simple input video and crop it to a smaller region.

Step 1: Import Libraries

First, we’ll import the necessary libraries.

import cv2
import numpy as np

Step 2: Define Crop Coordinates

Next, we’ll define the coordinates for the top-left and bottom-right corners of the cropped region.

# Define the cropping coordinates
x1, y1 = 100, 100
x2, y2 = 400, 400

Step 3: Read the Input Video

Now, we’ll read the input video and obtain its properties, such as width, height, and frames per second (FPS).

# Read the input video
input_video = cv2.VideoCapture('input_video.mp4')

# Get video properties
width = int(input_video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(input_video.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(input_video.get(cv2.CAP_PROP_FPS))

Step 4: Set Up the Output Video

We’ll create an output video file to save the cropped video. We need to specify the output file name, codec, fps, and cropped frame size.

# Set up the output video
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
output_video = cv2.VideoWriter('output_video.mp4',fourcc, fps, (x2 - x1, y2 - y1))

Step 5: Process the Video Frames

Now we’ll process each frame of the input video. For each frame, we’ll extract the region of interest (ROI) using the defined coordinates and write the cropped frame to the output video.

# Process the video frames
while True:
    ret, frame = input_video.read()

    if not ret:
        break

    # Crop the frame
    cropped_frame = frame[y1:y2, x1:x2]

    # Write the cropped frame to the output video
    output_video.write(cropped_frame)

    # Display the cropped frame (optional)
    cv2.imshow('Cropped Video', cropped_frame)

    # Exit if 'q' key is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the input and output videos and close the display window
input_video.release()
output_video.release()
cv2.destroyAllWindows()

That’s it! With these few lines of code, you can now crop any video using OpenCV.

Conclusion

In this tutorial, we explored the theory behind video cropping and provided a step-by-step guide on how to crop a video using OpenCV. We’ve delved into the video frame structure, coordinate system, and how to process each frame to extract the region of interest.

This tutorial aimed to be as engaging and accessible as possible, even for beginners. We hope you found it informative and enjoyable! Keep experimenting with different crop coordinates and videos to further your understanding of video cropping in OpenCV. Happy coding!


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp