In this blog, we will do a small project using OpenCV-Python where we will be creating video from image sequences. This project is entirely based on what we read in Chapter 1 and 2. Let’s start
Steps:
- Fetch all the image file names using glob
- Read all the images using cv2.imread()
- Store all the images into a list
- Create a VideoWriter object using cv2.VideoWriter()
- Save the images to video file using cv2.VideoWriter().write()
- Release the VideoWriter and destroy all windows.
Let’s see the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import cv2 import numpy as np import glob img_array = [] for filename in glob.glob('C:/New folder/Images/*.jpg'): img = cv2.imread(filename) height, width, layers = img.shape size = (width,height) img_array.append(img) out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size) for i in range(len(img_array)): out.write(img_array[i]) out.release() |
glob.glob(Pathname) fetches all the filenames present in that path. ‘*.jpg’ means all the jpg files. So, in code glob.glob() fetches the filename of all the jpg files present in that path.
Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.
If you guys still a have a problem with the files order, if you’re ordering your images in a numerical order here’s a solution for you. Hope it helps
import cv2
import glob
import re
img_array = []
numbers = re.compile(r'(\d+)’)
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
for filename in sorted(glob.glob(‘C:/Users/naitsied/Downloads/DATASOURCES/Scenario1/*.jpg’) , key=numericalSort):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter(‘scenario1.mp4′,cv2.VideoWriter_fourcc(*’DIVX’), 15, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()
Sir, your comment was so helpful. It’s like you knew exactly what I was struggling with. Thank you for taking the time to post your sample code!
How to download back the output video file in folder ?
Found how to do it yet?
path=’path_of_folder’
os.makedir(path)
os.chdir(path)
Good post, thanks for share!