Advertisement
ButAlsoHam

OpenCV Image Combine

May 25th, 2018
872
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.70 KB | None | 0 0
  1. #!/usr/local/bin/python3
  2.  
  3. import cv2
  4. import argparse
  5. import os
  6. import functools
  7. from functools import cmp_to_key
  8.  
  9. def help ():
  10.     with open(__file__, "r", encoding="UTF-8") as open_file:
  11.         for line in open_file:
  12.             if ":" in line and "def" in line and "if " not in line:
  13.                 print(line.split(" ")[1])
  14.  
  15. #Function to check if string can be cast to int
  16. def isnum (num):
  17.     try:
  18.         int(num)
  19.         return True
  20.     except:
  21.         return False
  22.  
  23. #Numerically sorts filenames
  24. def image_sort_name (x,y):
  25.    
  26.     x = int(x.split(".")[0])
  27.     y = int(y.split(".")[0])
  28.     return x-y
  29.  
  30. #Sort filenames by their last edited datetime stamp
  31. #This way, even if you didn't name and number your frames, you can still use their order of creation for sorting
  32. #10/10! :)
  33. def image_sort_datetime (x,y):
  34.     x = os.path.getmtime(x)
  35.     y = os.path.getmtime(y)
  36.     return x - y
  37.  
  38. def render ():
  39.     # Construct the argument parser and parse the arguments
  40.     arg_parser = argparse.ArgumentParser()
  41.     arg_parser.add_argument("-e", "--extension", required=False, default='png', help="Extension name. default is 'png'.")
  42.     arg_parser.add_argument("-o", "--output", required=False, default='output.mp4', help="Output video file.")
  43.     arg_parser.add_argument("-d", "--directory", required=False, default='.', help="Specify image directory.")
  44.     arg_parser.add_argument("-fps", "--framerate", required=False, default='10', help="Set the video framerate.")
  45.     arg_parser.add_argument("-s", "--sort", required=False, default='numeric', help="Determines the type of file-order sort that will be used. Current values: none, numeric, datetime")
  46.     arg_parser.add_argument("-t", "--time", required=False, default='none', help="Sets the framerate so that the video length matches the time in seconds.")
  47.     arg_parser.add_argument("-v", "--visual", required=False, default='false', help="If 'true' then will display preview window.")
  48.     arg_parser.add_argument("-safe", "--safe", required=False, default='true', help="If 'false' then will try to render all images, not just consistenly-sized ones.")
  49.     args = vars(arg_parser.parse_args())
  50.  
  51.     # Arguments
  52.     dir_path = args['directory']
  53.     ext = args['extension']
  54.     output = args['output']
  55.     framerate = args['framerate']
  56.     sort_type = args['sort']
  57.     time = args['time']
  58.     visual = args['visual']
  59.  
  60.     #Flips bools to a bool-type
  61.     visual = visual == "true"
  62.     safe = args['safe'] == "true"
  63.  
  64.     #Sets the framerate to argument, or defaults to 10
  65.     if not isnum(framerate):
  66.         framerate = 10
  67.     else:
  68.         framerate = int(framerate)
  69.  
  70.     #Get the files from directory
  71.     images = []
  72.     for f in os.listdir(dir_path):
  73.         if f.endswith(ext):
  74.             images.append(f)
  75.  
  76.     #Sort the files found in the directory
  77.     if sort_type == "numeric":
  78.         int_name = images[0].split(".")[0]
  79.         if isnum(int_name):
  80.             images = sorted(images, key=cmp_to_key(image_sort_name))
  81.         else:
  82.             print("Failed to sort numerically, switching to alphabetic sort")
  83.             images.sort()
  84.     elif sort_type == "datetime":
  85.         images = [dir_path + "/" + im for im in images]
  86.         images = sorted(images, key=cmp_to_key(image_sort_datetime))
  87.         images = ["".join(im.split(dir_path + "/")[1:]) for im in images]
  88.     elif sort_type == "alphabetic":
  89.         images.sort()
  90.  
  91.     #Change framerate to fit the time in seconds if a time has been specified.
  92.     #Overrides the -fps arg
  93.     if isnum(time):
  94.         framerate = int(len(images) / int(time))
  95.         print("Adjusting framerate to " + str(framerate))
  96.  
  97.     # Determine the width and height from the first image
  98.     image_path = os.path.join(dir_path, images[0])
  99.     frame = cv2.imread(image_path)
  100.  
  101.     if visual:
  102.         cv2.imshow('video',frame)
  103.     regular_size = os.path.getsize(image_path)
  104.     height, width, channels = frame.shape
  105.  
  106.     # Define the codec and create VideoWriter object
  107.     fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
  108.     out = cv2.VideoWriter(output, fourcc, framerate, (width, height))
  109.  
  110.     for n, image in enumerate(images):
  111.         image_path = os.path.join(dir_path, image)
  112.         image_size = os.path.getsize(image_path)
  113.         if image_size < regular_size / 1.5 and safe:
  114.             print("Cancelled: " + image)
  115.             print("Abnormal image size. Use the '-safe false' to disable this check")
  116.             continue
  117.  
  118.         frame = cv2.imread(image_path)
  119.         out.write(frame) # Write out frame to video
  120.         if visual:
  121.             cv2.imshow('video', frame)
  122.  
  123.         if (cv2.waitKey(1) & 0xFF) == ord('q'): # Hit `q` to exit
  124.             break
  125.         if n%100 == 0:
  126.             print("Frame " + str(n))
  127.  
  128.     # Release everything if job is finished
  129.     out.release()
  130.     cv2.destroyAllWindows()
  131.  
  132.     print("The output video is {}".format(output))
  133.  
  134. if __name__ == "__main__":
  135.     do = "[]"
  136.     while do not in "[q][quit][end][exit][-q]":
  137.         do = "[" + input("do: ").lower() + "]"
  138.         if do in "[render]":
  139.             render()
  140.         elif do in "[-h][h][help][--help][--h]":
  141.             help()
  142.     print("Bye!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement