from glob import glob
import os
import subprocess
#PIL: from PIL import Image
import tifffile
import numpy as np
import time
import sys

x = "01/mask001.tif"

#PIL: im = Image.open(x)
im = tifffile.imread(x)

print("Opened succesfully");
try:
	print("Trying to save ...")
	#PIL: im.save(x, dpi=(25, 25))   # Fix dpi value for all available results. STAPLE executable requires inputs with same dpi
	# is the dpi param just fixing res metadata in TIFFs, or is it rescaling?
	#tifffile.imsave(x,im)
	tifffile.imwrite(x,im,
		imagej=True, #optional
		resolution=(1./2.6755, 1./2.6755),
		metadata={'spacing': 3.947368, 'unit': 'um'})


	print("Saved succesfully")
	#subprocess.call(executable_path_crlConvertBetweenFileFormats + " -in " + os.getcwd() + "/" + x + " -out " + os.getcwd() + "/" + x.split(".")[0] + ".nrrd", shell=True)
	#print(executable_path_crlConvertBetweenFileFormats + " -in " + os.getcwd() + "/" + x + " -out " + os.getcwd() + "/" + x.split(".")[0] + ".nrrd")
except:
	print("Unexpected error in saving file, skipping " + x)

