forked from abhishekkr/lyrical-video-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-video.py
96 lines (71 loc) · 2.69 KB
/
create-video.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python
import os
import cv2
import re
import sys
from PIL import Image
def frame_dir():
try:
return sys.argv[1]
except:
return os.getcwd()
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
source: https://stackoverflow.com/a/5967539
'''
return [ atoi(c) for c in re.split(r'(\d+)', text) ]
def listframes(path_with_frames):
_listframes = [img for img in os.listdir(path_with_frames)
if img.endswith(".jpg") or
img.endswith(".jpeg") or
img.endswith(".png")]
_listframes.sort(key=natural_keys)
return _listframes
def get_video_size(path_with_frames, list_of_frames):
mean_height = 0
mean_width = 0
num_of_images = len(list_of_frames)
for frame in list_of_frames:
width, height = Image.open(os.path.join(path_with_frames, frame)).size
mean_height += height
mean_width += width
mean_height /= num_of_images
mean_width /= num_of_images
return (int(mean_width), int(mean_height))
def resize_frames(path_with_frames, list_of_frames, size):
for frame in list_of_frames:
framepath = os.path.join(path_with_frames, frame)
im = Image.open(framepath)
imResize = im.resize(size, Image.ANTIALIAS)
imResize.save(framepath, 'PNG', quality = 100) # setting quality
# printing each resized image name
print("resized:", frame)
def generate_video(path_with_frames, list_of_frames, video_file, size):
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
video = cv2.VideoWriter(video_file, fourcc, FRAMES_PER_SECOND, size, True)
last_framepath = None
for frame in list_of_frames:
print("adding frame:", frame)
framepath = os.path.join(path_with_frames, frame)
video.write(cv2.imread(framepath))
last_framepath = framepath
for _ in range(REPEAT_LAST_FRAME_FOR_COUNT):
video.write(cv2.imread(last_framepath))
cv2.destroyAllWindows() # Deallocating memories taken for window creation
video.release() # releasing the video generated
def main():
path_with_frames = frame_dir()
all_frames = listframes(path_with_frames)
if all_frames == None or len(all_frames) == 0:
print("found no frames at %s" % (path_with_frames))
sys.exit(1)
video_size = get_video_size(path_with_frames, all_frames)
resize_frames(path_with_frames, all_frames, video_size)
generate_video(path_with_frames, all_frames, VIDEO_NAME, video_size)
FRAMES_PER_SECOND = 24 ## common across scripts
VIDEO_NAME = '/tmp/mygeneratedvideo.avi'
REPEAT_LAST_FRAME_FOR_COUNT = 48
if __name__ == "__main__":
main()