Python - Process images of a video using OpenCV

Python - Process images of a video using OpenCV

Processing images of a video using OpenCV involves reading the video frame by frame, processing each frame (image) as required, and then optionally saving the processed frames back to a new video file.

Here's a step-by-step guide on how to process images of a video using OpenCV:

1. Install OpenCV:

First, you need to install OpenCV if you haven't already:

pip install opencv-python 

2. Read and Process Video:

Here's a basic script to read a video, convert each frame to grayscale, and then save the processed video:

import cv2 # Open the video file cap = cv2.VideoCapture('input_video.mp4') # Check if video opened successfully if not cap.isOpened(): print("Error: Could not open video.") exit() # Get video properties width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) # Define the codec and create a VideoWriter object to save the processed video fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output_video.avi', fourcc, fps, (width, height), isColor=False) while True: ret, frame = cap.read() # Break the loop if video has ended if not ret: break # Convert frame to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Save the processed frame out.write(gray) # Optionally display the frame (press 'q' to close the window) cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the video objects and close display window cap.release() out.release() cv2.destroyAllWindows() 

In the example above:

  • We read the video input_video.mp4.
  • For each frame, we convert it to grayscale using cv2.cvtColor().
  • We save the processed frames to output_video.avi.
  • We also display the processed frames in a window (you can close the window by pressing 'q').

You can replace the grayscale conversion with any other image processing task you need.


More Tags

microservices textinputlayout count-unique arrays cp1252 animated-gif fork html-encode python-unicode lodash

More Programming Guides

Other Guides

More Programming Examples