#pip3 install -U imageio-ffmpeg                             # It contains VideoFileClip module and must be installed from shell
#from moviepy.editor import VideoFileClip,ImageSequenceClip # Must be added in the beginning with the rest of imported modules


# Define Input and Output folder (USER must Edit)
video_name         = "sample.mp4"
video_name_part    = video_name.split(".")    # sample & mp4 has been split
input_video_path   = os.path.join("Input_Video", video_name) 
output_images_path = os.path.join("Output_Video", "Processed_Images") # This is a temporary folder to hold processed images
output_video_path  = os.path.join("Output_Video", video_name_part[0] + "_output." + video_name_part[1])


# Load video
cap = cv2.VideoCapture(input_video_path)


# Get General Info
fps         = cap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration    = int(frame_count/fps)
width       = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))  # float
height      = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # float

    
# Apply some processing to each image and then save them
for frame_num in range(frame_count):
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
    _,frame=cap.read()
    #Apply some processing here and then ...
    image_path =  os.path.join(output_images_path, "Frame_" + str(frame_num)+".jpg")
    cv2.imwrite(image_path, frame)   
    

# Order images according to frame number and file type in a list
IMAGE_EXT = ['jpeg', 'gif', 'png', 'jpg']
image_list = sorted(os.listdir(output_images_path), key=lambda a: int((a.split(".")[0]).split("_")[1]))    # Order accord. to frame num
image_list = [os.path.join(output_images_path, image_file) for image_file in image_list]                   # Add directory path
image_list = [image_file for image_file in image_list if os.path.splitext(image_file)[1][1:].lower() in IMAGE_EXT] # Order accord. to file type


# Make video
clip = ImageSequenceClip(image_list, fps=fps)
clip.write_videofile(output_video_path)


# (OPTIONAL) Delete folder of Procesed Images
try: 
    shutil.rmtree(ouput_images_path)
except FileNotFoundError:
    print ("Folder has been deleted already and Video is ready")