Created
January 5, 2020 04:44
-
-
Save tatsy/9416fd44f2b1b540616df6394bbfb6d7 to your computer and use it in GitHub Desktop.
Compress image sequence into MP4 video
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import os | |
import argparse | |
import cv2 | |
def is_image_file(filename): | |
""" Check whether the file name sounds like an image """ | |
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif'] | |
_, ext = os.path.splitext(filename) | |
return ext in image_extensions | |
def compress(input_folder, output_file, frame_rate): | |
""" Compress image sequence into an video with specified frame rate """ | |
# Retrieve image files | |
image_files = filter(is_image_file, os.listdir(input_folder)) | |
image_files = [os.path.join(input_folder, f) for f in image_files] | |
image_files = sorted(image_files) | |
num_images = len(image_files) | |
print('#image: {}'.format(num_images)) | |
# Video format | |
dummy = cv2.imread(image_files[0], cv2.IMREAD_GRAYSCALE) | |
size = dummy.shape | |
size = (size[1], size[0]) | |
fmt = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') | |
# Write frames to video | |
writer = cv2.VideoWriter(output_file, fmt, frame_rate, size) | |
for i, f in enumerate(image_files): | |
print('[{0} / {1}] {2}'.format(i + 1, num_images, f)) | |
frame = cv2.imread(f, cv2.IMREAD_COLOR) | |
writer.write(frame) | |
writer.release() | |
if __name__ == '__main__': | |
# Parse input arguments | |
parser = argparse.ArgumentParser(description='Compress image sequence into MP4 video') | |
parser.add_argument('-i', '--input', type=str, default='.', | |
help='Input folder which stores image sequence') | |
parser.add_argument('-o', '--output', type=str, default=None, | |
help='Output file name') | |
parser.add_argument('--fps', type=float, default=29.97, | |
help='Output video frame rate [default: 29.97]') | |
args = parser.parse_args() | |
# Setup output file name | |
input_folder = os.path.abspath(args.input) | |
output_file = args.output | |
fps = args.fps | |
if output_file is None: | |
output_file = os.path.basename(input_folder) + '.mp4' | |
print('Input: {}'.format(input_folder)) | |
print('Output: {}'.format(output_file)) | |
# Run | |
compress(input_folder, output_file, fps) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment