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

Stephen Morris, September 2019

"""
from skimage.io import imread
from skimage.io import imsave

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

path = 'some path string' 		 # path to the data folder
root_folder_name = 'some data 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   # set the number of frames per second in the movie

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

left = 	  	#  pixels off the top, etc
right = 
top = 	
bot = 	

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)
