"""
Crop images and then use ffmpeg to make a movie out of them.
The cropped images are not saved, only the movie.

This is just for making nice looking movies, not serious data analysis.

Stephen Morris, June 2018

"""
from skimage.io import imread, imsave

from os import listdir, mkdir, system, chdir, remove, rmdir

path =   # path to the data folder
root_folder_name =   # name of the data folder

root_folder = path + '/' + root_folder_name   # name of the data folder

frames_dir = path + '/' + root_folder_name + '_frames'
mkdir(frames_dir)

frame_rate = 20   # frames per second

# crop to these dimensions: you can choose these by inspecting a test image using Image J

left =  80      #  pixels off the top, etc
right = 64
top =   450
bot =   660

file_list = listdir(root_folder)  
file_list = sorted([name for name in file_list if (name.endswith('.tif') and not name.startswith('.'))])  

i = 0   # new index for frame numbers

for name in file_list: 
    image = imread(root_folder+'/'+name) 
    image_cropped = image[ top:image.shape[0]-bot, left:image.shape[1]-right ] 
    imsave(frames_dir+'/'+root_folder_name+'.'+str(i)+'.jpg', image_cropped)      # jpg versions of frames (erased later)
    i = i+1

# this system call runs ffmeg --- you must have ffmpeg installed:
# see https://ffmpeg.org to download it

# At the moment, this does not work on Windows without some special tweak

system('ffmpeg -r '+str(frame_rate) +' -i ' + frames_dir+'/'+root_folder_name+'.%d.jpg'+ ' -vcodec h264 -b 64000 ' + root_folder_name + '.mp4' )

chdir(frames_dir)

for frame in listdir('.'):   # delete the temporary frame files

    remove(frame)
    
chdir('..')
rmdir(frames_dir)
