OpenCV Tutorial
Image Processing
Feature Detection and Description
Drawing Functions
Video Processing
Applications and Projects
Creating a video from multiple images using OpenCV is relatively straightforward. This can be useful in many scenarios, such as generating time-lapse videos or slideshows. Here's a tutorial on how to achieve this:
pip install opencv-python
import cv2 import os
Make sure all the images are of the same size. If not, you'll need to resize them to a uniform size.
path = 'path_to_directory_with_images/' image_files = [f for f in os.listdir(path) if f.endswith('.jpg')] # Assuming all images are jpg. Modify if needed. image_files.sort() # To ensure images are in order
Define the video codec using cv2.VideoWriter_fourcc
and create a VideoWriter
object.
# Read the first image to get the width and height img = cv2.imread(os.path.join(path, image_files[0])) height, width, layers = img.shape fourcc = cv2.VideoWriter_fourcc(*'XVID') # or use 'MJPG' fps = 1 # Frames per second. Adjust as needed. video = cv2.VideoWriter('output_video.avi', fourcc, fps, (width, height))
Loop over each image and write it to the video.
for image_file in image_files: img = cv2.imread(os.path.join(path, image_file)) video.write(img)
video.release() cv2.destroyAllWindows()
Ensure that all images are of the same size, or you might run into issues. If your images are of different sizes, you can resize each image using cv2.resize()
before writing it to the video.
The output video format is .avi
as defined in the VideoWriter
object. You can change the format by replacing 'output_video.avi'
with your desired format (e.g., 'output_video.mp4'
) and adjusting the codec accordingly.
You can adjust the fps
(frames per second) as per your requirement. For instance, for a slideshow, you might want to use a lower value like 1
or 0.5
, while for a time-lapse, a value like 24
or 30
might be more suitable.
OpenCV provides an efficient way to create videos from a sequence of images. This is particularly useful for creating time-lapses, slideshows, or any other video that can be constructed from individual frames. Adjusting parameters like FPS and video codec can help tailor the output to specific needs.
Python Code for Making a Video from Images in OpenCV:
import cv2 import os # Path to the directory containing images img_folder = 'path/to/images/' # Video properties video_name = 'output_video.mp4' fps = 24 # Frames per second images = [img for img in os.listdir(img_folder) if img.endswith(".png")] frame = cv2.imread(os.path.join(img_folder, images[0])) height, width, layers = frame.shape video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height)) for image in images: video.write(cv2.imread(os.path.join(img_folder, image))) cv2.destroyAllWindows() video.release()