This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.
- OpenCV 3.4
- Python 3.6+
- Image, Webcam or Video input
- Documentation Source: OpenCV Official Documentation
First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3
In this tutorial, I will show you how to merge or convert several frames to a video by combing the image frames using OpenCV library and Python coding.
Python: cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) → <VideoWriter object>
Python: cv2.VideoWriter.write(image) → None
Write image frames to a video file
- filename – Name of the output video file.
- fourcc – 4-character code of codec used to compress the frames. List of codes can be obtained at Video Codecs by FOURCC page.
- VideoWriter_fourcc(c1, c2, c3, c4) → retval
- fps – Framerate of the created video stream.
- frameSize – Size of the video frames.
- isColor – If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only).
- Read each image using cv2.imread()
- Initialize the video writer using cv2.VideoWriter()
- Save the frames to a video file using cv2.VideoWriter.write()
- Wait for keyboard button press using cv2.waitKey()
- Release the VideoWriter using cv2.VideoWriter.release()
- Exit window and destroy all windows using cv2.destroyAllWindows()
import numpy as np
from os.path import isfile, join
frame_array = 
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#for sorting the file names properly
files.sort(key = lambda x: int(x[5:-4]))
for i in range(len(files)):
filename=pathIn + files[i]
#reading each files
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
#inserting the frames into an image array
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
for i in range(len(frame_array)):
# writing to a image array
pathOut = 'video.avi'
fps = 25.0
convert_frames_to_video(pathIn, pathOut, fps)
Latest posts by Life2Coding (see all)
- How to Install OpenCV 3.4.0 with Python 3 on Raspberry Pi 3 - 3 March, 2018
- Split Video Channels into RGB components using OpenCV in Python - 6 February, 2018
- Convert Image Frames to Video File using OpenCV in Python - 6 February, 2018