# need connect them again

# /usr/local/bin/python3.7 /home/aigouy/mon_prog/Python/epyseg_pkg/personal/refine_really_using_seeds_final_version.py
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/5.tif
# INFO - 2020-09-08 10:22:51,251 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 13.412909021833912
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/11.tif
# INFO - 2020-09-08 10:22:55,879 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.426248760195449
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/12.tif
# INFO - 2020-09-08 10:22:59,347 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.4726882169488817
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/122.tif
# INFO - 2020-09-08 10:26:10,318 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 218.84090158320032
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/100708_png06.tif
# INFO - 2020-09-08 10:26:39,909 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.28710938
#
# loop duration 1.4557520730886608
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/100708_png07.tif
# INFO - 2020-09-08 10:26:41,408 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.28710938
#
# loop duration 1.4955594521015882
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/AVG_070219.lif - Series0020000.tif
# INFO - 2020-09-08 10:26:52,773 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.14257812
#
# loop duration 12.987532612867653
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Bro43_avproj0000.tif
# INFO - 2020-09-08 10:26:57,508 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.3414891839493066
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Bro43_avproj0001.tif
# INFO - 2020-09-08 10:27:00,989 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.4897151968907565
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/FocStich_RGB005.tif
# INFO - 2020-09-08 10:30:10,850 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 213.77805873099715
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/FocStich_RGB008.tif
# INFO - 2020-09-08 10:33:32,117 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 201.50568953878246
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/FocStich_RGB010.tif
# INFO - 2020-09-08 10:36:53,030 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 201.437952702865
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/FocStich_RGB200.tif
# INFO - 2020-09-08 10:40:12,489 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 198.4501655951608
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Focused Image16.tif
# INFO - 2020-09-08 10:41:11,188 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 39.641601181123406
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/MAX_160610_test_ocelli_ok_but_useless_cause_differs_a_lot_from_ommatidia.lif - test_visualization_head_ommatidia_32h_APF_2c.tif
# INFO - 2020-09-08 10:41:28,949 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 14.507123892894015
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/MAX_160610_test_ocelli_ok_but_useless_cause_differs_a_lot_from_ommatidia.lif - test_visualization_head_ommatidia_32h_APF_ok_2.tif
# INFO - 2020-09-08 10:41:42,890 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 13.884486364899203
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/MAX_ECadGFP_120410_2_090.tif
# INFO - 2020-09-08 10:41:47,395 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.173132434953004
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/MAX_ECadGFP_120410_2_091.tif
# INFO - 2020-09-08 10:41:50,490 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.09780628583394
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/MAX_ECadGFP_120410_2_092.tif
# INFO - 2020-09-08 10:41:53,667 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.1736521390266716
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/MAX_ECadGFP_120410_2_093.tif
# INFO - 2020-09-08 10:41:56,873 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.216935507953167
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/MAX_ECadGFP_120410_2_094.tif
# INFO - 2020-09-08 10:41:59,984 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 3.10473800287582
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Optimized_projection_018.tif
# INFO - 2020-09-08 10:44:51,691 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 195.3538196219597
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Optimized_projection_061.tif
# INFO - 2020-09-08 10:48:11,802 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 200.71830472000875
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Optimized_projection_066.tif
# INFO - 2020-09-08 10:51:35,335 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 203.37293418985792
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Optimized_projection_070.tif
# INFO - 2020-09-08 10:54:55,405 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 200.38133086496964
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/Series019.tif
# INFO - 2020-09-08 10:55:31,549 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 12.970223133917898
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_000.tif
# INFO - 2020-09-08 10:55:40,162 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 7.961171072907746
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_016.tif
# INFO - 2020-09-08 10:55:48,247 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 8.091942163882777
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_032.tif
# INFO - 2020-09-08 10:55:56,318 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 8.069108976982534
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_048.tif
# INFO - 2020-09-08 10:56:04,325 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 8.004049139097333
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_064.tif
# INFO - 2020-09-08 10:56:12,382 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 8.088477168930694
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_080.tif
# INFO - 2020-09-08 10:56:20,448 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 8.039556092815474
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_096.tif
# INFO - 2020-09-08 10:56:28,440 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 7.987037570914254
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_112.tif
# INFO - 2020-09-08 10:56:36,418 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 7.992303601931781
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_256.tif
# INFO - 2020-09-08 10:56:44,424 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 7.9964883690699935
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/StackFocused_Endocad-GFP(6-12-13)#19_400.tif
# INFO - 2020-09-08 10:56:52,258 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 7.823508135974407
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/T21a920000.tif
# INFO - 2020-09-08 10:56:58,225 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 5.743339963955805
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/T21a920069.tif
# INFO - 2020-09-08 10:57:03,699 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 5.379117785021663
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img03.tif
# INFO - 2020-09-08 10:57:05,274 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 1.0500243220012635
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img07.tif
# INFO - 2020-09-08 10:57:06,389 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 1.1297991459723562
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img08.tif
# INFO - 2020-09-08 10:57:06,683 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.14257812
#
# loop duration 0.17633310402743518
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img18.tif
# INFO - 2020-09-08 10:57:08,052 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.14257812
#
# loop duration 1.5585627369582653
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img21.tif
# INFO - 2020-09-08 10:57:09,530 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.28710938
#
# loop duration 1.4409180879592896
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img22.tif
# INFO - 2020-09-08 10:57:09,917 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 0.23569744802080095
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/disc_0002_DCAD.tif
# INFO - 2020-09-08 11:00:40,501 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 240.3431613589637
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/disc_0003_DCAD.tif
# INFO - 2020-09-08 11:05:59,528 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 329.79293455113657
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/disc_0004.tif
# INFO - 2020-09-08 11:10:43,632 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 278.1878239570651
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series010.tif
# INFO - 2020-09-08 11:11:20,188 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.1808029308449477
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series016.tif
# INFO - 2020-09-08 11:11:22,331 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.143141306936741
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series031.tif
# INFO - 2020-09-08 11:11:24,456 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.1280170071404427
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series056.tif
# INFO - 2020-09-08 11:11:26,611 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.155403066193685
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series080.tif
# INFO - 2020-09-08 11:11:28,781 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.174913822906092
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series104.tif
# INFO - 2020-09-08 11:11:30,914 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.138198181055486
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series128.tif
# INFO - 2020-09-08 11:11:33,035 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.1152428360655904
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series165.tif
# INFO - 2020-09-08 11:11:35,170 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.1392317339777946
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series194.tif
# INFO - 2020-09-08 11:11:37,348 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.1838744960259646
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series212.tif
# INFO - 2020-09-08 11:11:39,618 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.275903246132657
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series239.tif
# INFO - 2020-09-08 11:11:41,843 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.215909095015377
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series269.tif
# INFO - 2020-09-08 11:11:43,977 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.130250509828329
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series291.tif
# INFO - 2020-09-08 11:11:46,182 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.203590342774987
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series312.tif
# INFO - 2020-09-08 11:11:48,382 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.2014496689662337
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/focused_Series316.tif
# INFO - 2020-09-08 11:11:50,516 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 2.1345030379015952
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/proj0016.tif
# INFO - 2020-09-08 11:12:25,496 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 39.66941298288293
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/stitched_00000_RGB.tif
# INFO - 2020-09-08 11:15:00,353 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 171.40589298889972
# processing /D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/wing_stitched.tif
# INFO - 2020-09-08 11:16:22,145 - refine_really_using_seeds_final_version.py - __init__ - line 107 - threshold used for producing the final mask=0.42773438
#
# loop duration 69.09804043103941
# total duration 3231.4851781229954
#
# Process finished with exit code 0

from scipy import ndimage
from skimage.filters import threshold_otsu
# from skimage.morphology import watershed
from skimage.segmentation import watershed

from epyseg.img import Img
from matplotlib import pyplot as plt
from skimage.measure import label, regionprops
import os
import numpy as np

# logging
from epyseg.tools.logger import TA_logger
import tempfile

from epyseg.postprocess.filtermask import FilterMask
from epyseg.postprocess.edmshed import sauvola

logger = TA_logger()


class RefineMaskUsingSeeds:
    stop_now = False

    # add these parameters
    # filter = None,
    # correction_factor = 2,
    # cutoff_cell_fusion = None,
    # restore_safe_cells = False,


    # store in temp dir by default
    def __init__(self, img_orig, _DEBUG=False, _VISUAL_DEBUG=False, output_folder=tempfile.gettempdir(), output_name='handCorrection.tif', threshold=None,
                 filter=None,
                 correction_factor=2,
                 cutoff_cell_fusion=None,
                 restore_safe_cells=False,
                 **kwargs):
        if not img_orig.has_c() or img_orig.shape[-1] != 7:
            logger.error('image must have 7 channels to be used for post process')
            return
        autothresholds = []

        # autothreshold all masks
        for i in range(img_orig.shape[-1]):
            # white bg masks need very low threshold
            # if i in [0, 3, 4, 6]: # before [3, 4, 6]
            #     auto_threshold = self.autothreshold(Img.invert(img[..., i])) / 4
            # else:
            auto_threshold = self.autothreshold(img[..., i])#self.phansalkarthreshold(img[..., i])
            autothresholds.append(auto_threshold)
            # autothresholds.append(0.15)

        # new corrections (avg on HQ pred)
        # autothresholds[0]/=7
        # autothresholds[1]/=2.5
        # autothresholds[2] = 10/100*autothresholds[2]+autothresholds[2]
        # autothresholds[3]/=5
        # autothresholds[4]/=3
        # autothresholds[5]/=2
        # autothresholds[6]/=6
        # bckup2
        # autothresholds[0] = 0.05
        # autothresholds[1] = 0.14
        # autothresholds[2] = 0.16
        # autothresholds[3] = 0.14
        # autothresholds[4] = 0.1
        # autothresholds[5] = 0.2
        # autothresholds[6] = 0.25
        # test 3
        autothresholds[0] = 0.01
        autothresholds[1] = 0.1
        autothresholds[2] = 0.2
        autothresholds[3] = 0.2
        autothresholds[4] = 0.125
        autothresholds[5] = 0.1
        autothresholds[6] = 0.2


        # bckup
        # autothresholds[0] /= 6
        # autothresholds[1] /= 3
        # autothresholds[3] /= 6
        # autothresholds[4] /= 4
        # autothresholds[5] /= 2
        # autothresholds[6] /= 6

        # old correction (max on HQ pred)
        # autothresholds[3] /= 4
        # autothresholds[4] /= 4
        # autothresholds[6] /= 4

        # keep because manual is sometimes better
        # manual_thresholds = [0.3, 0.6, 0.7, 0.1, 0.25, 0.5, 0.1] # normal
        # manual_thresholds = [0.075, 0.25, 0.5, 0.15, 0.4, 0.25, 0.25] # for avg --> better take those # pas mal mais tester sur d'autres image
        # print(autothresholds, 'vs', manual_thresholds)

        # print(autothresholds, 'vs', manual_thresholds)
        # autothresholds = manual_thresholds

        if _DEBUG:
            Img(img_orig, dimensions='hwc').save(os.path.join(output_folder, 'raw_input.tif'))

        differing_bonds = np.zeros_like(img_orig)
        bckup_img_wshed = img_orig[..., 0].copy()

        # if False:
        # binarise dark bg watershed masks
        img_orig[..., 0] = self.binarise(img_orig[..., 0], threshold=autothresholds[0])
        img_orig[..., 1] = self.binarise(img_orig[..., 1], threshold=autothresholds[1])
        img_orig[..., 2] = self.binarise(img_orig[..., 2], threshold=autothresholds[2])

        # binarise white bg watershed masks
        img_orig[..., 3] = Img.invert(img_orig[..., 3])
        img_orig[..., 3] = self.binarise(img_orig[..., 3], threshold=autothresholds[3])
        img_orig[..., 4] = Img.invert(img_orig[..., 4])
        img_orig[..., 4] = self.binarise(img_orig[..., 4], threshold=autothresholds[4])

        # binarise dark bg seeds
        img_orig[..., 5] = self.binarise(img_orig[..., 5], threshold=autothresholds[5])

        # binarise white bg seeds
        img_orig[..., 6] = Img.invert(img_orig[..., 6])
        img_orig[..., 6] = self.binarise(img_orig[..., 6], threshold=autothresholds[6])

        if _DEBUG:
            Img(img_orig, dimensions='hwc').save(os.path.join(output_folder, 'thresholded_masks.tif'))

        # get watershed mask for all images
        for i in range(img_orig.shape[-1]):
            if i < 5:
                final_seeds = label(Img.invert(img[..., i]), connectivity=1, background=0)
            else:
                final_seeds = label(img[..., i], connectivity=1, background=0)
            final_wshed = watershed(bckup_img_wshed, markers=final_seeds, watershed_line=True)
            final_wshed[final_wshed != 0] = 1
            final_wshed[final_wshed == 0] = 255
            final_wshed[final_wshed == 1] = 0
            differing_bonds[..., i] = final_wshed

            if _VISUAL_DEBUG:
                plt.imshow(img[..., i])
                plt.show()

            del final_seeds
            del final_wshed

        if _DEBUG:
            print(os.path.join(output_folder, 'differences.tif'))
            Img(differing_bonds, dimensions='hwc').save(os.path.join(output_folder, 'differences.tif'))
            Img(bckup_img_wshed, dimensions='hw').save(os.path.join(output_folder, 'orig_img.tif'))

        # avg
        avg = np.mean(differing_bonds, axis=-1)
        avg = avg / avg.max()

        if _DEBUG:
            Img(avg, dimensions='hw').save(os.path.join(output_folder, 'avg.tif'))


        if threshold is None:
            # threshold = self.phansalkarthreshold(avg)
            threshold = self.autothreshold(avg)


        # should I use local thresholds ??? could so the same
        logger.info('threshold used for producing the final mask=' + str(threshold))

        final_mask = avg.copy()
        final_mask = self.binarise(final_mask, threshold=threshold)

        if _DEBUG:
            Img(final_mask, dimensions='hw').save(os.path.join(output_folder, 'binarized.tif'))

        # close wshed mask to fill super tiny holes
        s = ndimage.generate_binary_structure(2, 1)
        final_mask = ndimage.grey_dilation(final_mask, footprint=s)

        # remove super tiny artificial cells (very small value cause already dilated)
        mask = label(Img.invert(final_mask), connectivity=1, background=0)
        for region in regionprops(mask):
            if region.area < 5:
                for coordinates in region.coords:
                    final_mask[coordinates[0], coordinates[1]] = 255
        del mask

        final_mask = label(Img.invert(final_mask), connectivity=1, background=0)
        final_mask = watershed(bckup_img_wshed, markers=final_mask, watershed_line=True)

        final_mask[final_mask != 0] = 1
        final_mask[final_mask == 0] = 255
        final_mask[final_mask == 1] = 0

        # remove all post process to keep things simpler
        # fast enough anyway that nothing needs be done
        # finalize doc fully

        # finalize full code
        if filter is None or filter==0:
        # if _DEBUG:
            print('saving', os.path.join(output_folder, output_name))
            Img(final_mask.astype(np.uint8), dimensions='hw').save(os.path.join(output_folder, output_name))

        # return avg

        # not clear the code works well but it's ok
        # pas clair que ça marche bien --> le cutoff par taille donne pas mal d'erreurs en fait
        # faudrait regarder le code ne profondeur et voir ce que je garde
        # voir comment faire mais je pense que je vais faire comme ça, mais est ce que je garde le vieux modèle ou pas ??? --> il est globalement bien plus mauvais en tout points
        # est-ce que je tente de garder le filtering ou pas ???

        # get the filter parameters and see
        else:
            FilterMask(bckup_img_wshed, avg, final_mask, os.path.join(output_folder,'refined_mask.tif'), filter=filter, restore_safe_cells=restore_safe_cells, cutoff_cell_fusion=cutoff_cell_fusion, correction_factor=correction_factor) # en fait le filtre domine sur le restore most likely cells but maybe change that some day??? --> see how I can do that and restore the code

        # pas trop mal

    def autothreshold(self, single_2D_img):
        return threshold_otsu(single_2D_img)

    def sauvolathreshold(self, single_2D_img):
        sauvola_thres =sauvola(single_2D_img)
        # single_2D_img[single_2D_img<phansalkar_threshold]=0
        # single_2D_img[single_2D_img >= phansalkar_threshold] = 1
        return sauvola_thres

    # TODO improve and allow for copy of image and move to the Img class or at least file
    def binarise(self, single_2D_img, threshold=0.5, bg_value=0, fg_value=255):
        single_2D_img[single_2D_img > threshold] = fg_value
        single_2D_img[single_2D_img <= threshold] = bg_value
        return single_2D_img


# now run for all and see what it does
# TODO need add output name --> allow it to loop over several images
if __name__ == '__main__':
    from timeit import default_timer as timer

    start = timer()

    # everything seems to work now finalize the GUI...
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/0.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/cellpose_img22.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/cellpose_img07.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/cellpose_img08.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/cellpose_img18.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/cellpose_img21.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/122.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/5.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/Bro43_avproj0000.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/100708_png06.tif') # quite bad...
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/proj0016.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/StackFocused_Endocad-GFP(6-12-13)#19_000.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/StackFocused_Endocad-GFP(6-12-13)#19_400.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/image_plant_best-zoomed.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/T21a920000.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/MAX_160610_test_ocelli_ok_but_useless_cause_differs_a_lot_from_ommatidia.lif - test_visualization_head_ommatidia_32h_APF_ok_2.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/MAX_160610_test_ocelli_ok_but_useless_cause_differs_a_lot_from_ommatidia.lif - test_visualization_head_ommatidia_32h_APF_2c.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/16.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/Series019.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/FocStich_RGB008.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/focused_Series194.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/focused_Series316.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/MAX_ECadGFP_120410_2_094.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/20190924_ecadGFP_400nM20E_000.tif')
    # img = Img('/home/aigouy/Bureau/tests_dual_resolution/predict/disc_0002_DCAD.tif')
    # should I keep the old codes can the secure cells be those of

    # root_path = '/home/aigouy/Bureau/test_plants/raw_images_denoiseg/predict/'  # 3
    # root_path = '/home/aigouy/Bureau/trash/test_new_seeds_seg_stuff/predict2/'  # 3
    # root_path = '/home/aigouy/Bureau/trash/test_new_seeds_seg_stuff/predict2/predict/'  # 3
    # root_path = '/D/final_folder_scoring/predict/'  # 3
    # root_path = '/home/aigouy/Bureau/test_plants/predict/'  # 3
    root_path = '/D/final_folder_scoring/predict_hybrid/'  # 3
    # root_path = '/home/aigouy/Dropbox/seg_vertebrate_full_resolution_actin/optimized_projection_1above_2_below/predict/'  # 3
    # root_path = '/home/aigouy/Bureau/test_plants/predict/'  # 3
    # root_path = '/D/Sample_images/sample_images_PA/test_pedro/predict/'  # 3
    # root_path = '/home/aigouy/Dropbox/seg_vertebrate_full_resolution_actin/optimized_projection_2above_4_below/predict/'  # 3
    # root_path = '/home/aigouy/Dropbox/seg_vertebrate_full_resolution_actin/optimized_projection_1above_2_below/predict/'  # 3
    # root_path = '/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/'  # 3
    # root_path = '/home/aigouy/Bureau/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317_rot_HQ_only/' #4

    import glob
    from natsort import natsorted

    list_of_files = glob.glob(root_path + "*.png") + glob.glob(root_path + "*.jpg") + glob.glob(
        root_path + "*.jpeg") + glob.glob(
        root_path + "*.tif") + glob.glob(root_path + "*.tiff")+ glob.glob(root_path + "*.lsm")+ glob.glob(root_path + "*.czi") + glob.glob(root_path + "*.lif")
    list_of_files = natsorted(list_of_files)

    # list_of_files=['/home/aigouy/Bureau/tests_dual_resolution/predict/0.tif']
    # list_of_files=['/D/Sample_images/sample_images_PA/test_pedro/predict/100708_png06_mean_all.tif', '/D/Sample_images/sample_images_PA/test_pedro/predict/100708_png06_max_all.tif', '/D/Sample_images/sample_images_PA/test_pedro/predict/Bro43_avproj0000.tif']
    # list_of_files=['/D/Sample_images/sample_images_PA/test_pedro/predict/100708_png06_mean_all.tif']# not so much better now in fact --> is that really better ???
    # list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/MAX_160610_test_ocelli_ok_but_useless_cause_differs_a_lot_from_ommatidia.lif - test_visualization_head_ommatidia_32h_APF_ok_2.tif']
    # list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/5.tif']
    # list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/11.tif']
    # list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/focused_Series194.tif']
    # list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/cellpose_img22.tif']
    # list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/T21a920000.tif']
    list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/StackFocused_Endocad-GFP(6-12-13)#19_000.tif'] # terrible
    # list_of_files=['/D/final_folder_scoring/predict_avg_hq_correction_ensemble_wshed/StackFocused_Endocad-GFP(6-12-13)#19_400.tif'] # terrible
    # list_of_files=['/home/aigouy/Bureau/test_plants/predict/image_plant_best-zoomed.tif']

#     list_of_files=['/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/100708_png06.tif',
# '/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/100708_png07.tif',
# '/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/AVG_070219.lif - Series0020000.tif',
# '/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img08.tif',
# '/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img18.tif',
# '/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img21.tif']

    # list_of_files = ['/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/AVG_070219.lif - Series0020000.tif']
    # list_of_files = ['/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/AVG_070219.lif - Series0020000.tif']
    # list_of_files = ['/D/final_folder_scoring/predict_linknet-vgg16-sigmoid-ep0191-l0.144317/cellpose_img08.tif']

    # call it from other code

    # maybe dissociate the code for thresholding and the code for the avg so that I can produce what I need and ease stuff
    # ask whether interactive

    # test glob and quantif all

    for file in list_of_files:
        loop_time = timer()
        img = Img(file)
        print('processing', file)
        filename0_without_path = os.path.basename(file)

        # maybe always use this default threshold
        post_proc = RefineMaskUsingSeeds(img_orig=img, restore_safe_cells=True, _DEBUG=True, _VISUAL_DEBUG=False,
                                         output_folder='/home/aigouy/Bureau/trash/test_new_seeds_seg_stuff/', output_name=filename0_without_path, threshold=None)# threshold=0.24 # threshold=0.42773438
        print('\n\nloop duration', timer() - loop_time)

    # tester les scores pr voir si ok ou pas

    print('total duration', timer() - start)

    # TODO run the score for all but seems great

    # should I remove all other codes and model
    # if always better then remove all other parameters
    # then really need do the score and offer parameter selection
    # maybe offer three or 4 thresholds and ask user to select one
    # maybe plot the image too so that people can see score
    # try original wshed


    # it does not work better for the vertebrate epiboly stuff --> maybe due to threshold --> try with better default parameters
