Create video using multiple images using OpenCV
Steps to create a video from multiple images using OpenCV:
import cv2
: This imports the OpenCV library, which provides functions for reading, writing, and manipulating images and videos.import glob
: This imports theglob
module, which provides functions for finding files and directories matching a specified pattern.images = glob.glob('*.jpg')
: This line uses theglob
function to find all the files in the current directory with the extension.jpg
. It returns a list of filenames that match the pattern.frame_width = 640
andframe_height = 480
: These lines set the frame width and height for the video. You can adjust these values to suit your needs.fourcc = cv2.VideoWriter_fourcc(*'MJPG')
: This line sets the codec for the video. The codec is a software or hardware-based mechanism for encoding and decoding video data.MJPG
is a common codec for video files.out = cv2.VideoWriter('video.avi', fourcc, 30.0, (frame_width, frame_height))
: This line creates a VideoWriter object with the specified filename, codec, frame rate, and frame size. The video will be saved as an AVI file with the namevideo.avi
. You can adjust the filename and frame rate to suit your needs.for image in images:
: This line begins a loop that iterates through the images in theimages
list.img = cv2.imread(image)
: This line reads an image from the file specified byimage
.img = cv2.resize(img, (frame_width, frame_height))
: This line resizes the image to the specified frame size.out.write(img)
: This line writes the image to the video file.out.release()
: This line releases the VideoWriter object, which closes the video file and releases any resources used by the object.
Sample Python code using OpenCV to create a video from multiple images:
import cv2
import glob
# Read all the images
images = glob.glob('*.jpg')
# Set the frame width and height
frame_width = 640
frame_height = 480
# Set the video codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('video.avi', fourcc, 30.0, (frame_width, frame_height))
for image in images:
# Read the image
img = cv2.imread(image)
# Resize the image
img = cv2.resize(img, (frame_width, frame_height))
# Write the image to the video file
out.write(img)
# Release the VideoWriter object
out.release()
This code reads all the images in the current directory with the extension .jpg
, sets the frame width and height, and creates a VideoWriter object with the specified codec (in this case, MJPG
) and frame rate (in this case, 30 frames per second). Then it iterates through the images, resizes them to the specified frame size, and writes them to the video file. Finally, it releases the VideoWriter object.
You can adjust the frame size, codec, and frame rate to suit your needs. You can also use a different extension for the images, or specify a specific list of images rather than reading all the images in the current directory.
Leave a Comment