#!/usr/bin/python
# -*- coding: utf-8 -*-

# 2018-05-10 MW
# 1 - image preparation
#     binarisation
#     segmentation + labelling

import numpy
import tifffile

import spam.label.ITKwatershed as ws
import spam.label.toolkit as ltk
from spam.label import contacts

folder = "monotonic/images/"
# input
filenames    = ["triax.-1.eps=0.spheres_image_gaussian=08_noise=03",
                #"triax.0.eps=-0.0025.spheres_image_gaussian=08_noise=03",
                #"triax.1.eps=-0.005.spheres_image_gaussian=08_noise=03",
                #"triax.2.eps=-0.01.spheres_image_gaussian=08_noise=03",
                #"triax.3.eps=-0.02.spheres_image_gaussian=08_noise=03",
                #"triax.4.eps=-0.03.spheres_image_gaussian=08_noise=03",
                #"triax.5.eps=-0.04.spheres_image_gaussian=08_noise=03",
                #"triax.6.eps=-0.05.spheres_image_gaussian=08_noise=03",
                #"triax.7.eps=-0.06.spheres_image_gaussian=08_noise=03",
                #"triax.8.eps=-0.07.spheres_image_gaussian=08_noise=03",
                #"triax.9.eps=-0.08.spheres_image_gaussian=08_noise=03",
                #"triax.10.eps=-0.09.spheres_image_gaussian=08_noise=03",
                #"triax.11.eps=-0.1.spheres_image_gaussian=08_noise=03",
                #"triax.12.eps=-50124.6.spheres_image_gaussian=08_noise=03",
                ]

pixelSizeMicrons = 15 #mum

threshold     = 128
threshOverseg = 0
radiusThreshMicrons = 50. #mum

radiusThresh = radiusThreshMicrons/pixelSizeMicrons

for filename in filenames:
    print "\tLoading the image ...",
    grey_vol = tifffile.imread(folder+filename+".tif")
    print "done."

    # binarisation
    bin_vol = ((grey_vol > threshold)*1).astype('uint8')

    tifffile.imsave(folder+filename+"-bin.tif", bin_vol)

    # segmentation and labelling
    lab_vol = ws.watershed(bin_vol)

    # revome labels smaller than volThreshMicrons
    radii = ltk.equivalentRadii( lab_vol )
    labelsToRemove = numpy.where( radii < radiusThresh )

    if len(labelsToRemove[0]) > 1:
        lab_vol = ltk.removeLabels( lab_vol, labelsToRemove)
        lab_vol = ltk.makeLabelsSequential( lab_vol )

    if threshOverseg!=0 :
        # fixing over-segmentation
        lab_vol = contacts.detectAndFixOversegmentation(lab_vol, nVoxThreshold=threshOverseg)
        lab_vol = ltk.makeLabelsSequential( lab_vol )


    max_label = lab_vol.max()
    print "\tNumber of particles identified ", max_label

    if max_label < 255:
        tifffile.imsave(folder+filename+"-lab.tif", lab_vol.astype('uint8'))
    elif max_label < 65535:
        tifffile.imsave(folder+filename+"-lab.tif", lab_vol.astype('uint16'))
    else:
        tifffile.imsave(folder+filename+"-lab.tif", lab_vol.astype('uint32'))
