import labkeyInterface
import labkeyFileBrowser
import io
import pydicom
import numpy
import itk

net=labkeyInterface.labkeyInterface()
net.init('/home/studen/.labkey/merlin.json')
b=labkeyFileBrowser.labkeyFileBrowser(net)

url=b.formatPathURL('DORA/Radiomics',"")
ok,dirs=b.listRemoteDir(url)
url=dirs[10]

ok,dirs=b.listRemoteDir(url)
url=dirs[0]

ok,dirs=b.listRemoteDir(url)
fileUrl=dirs[0]

resp=net.get(fileUrl)
fileObj=io.BytesIO(resp.data)

#get dcm representation of the file
dcm=pydicom.dcmread(fileObj)

#matrix dimension
ConstPixelDims = (int(dcm.Rows), int(dcm.Columns))
npArray = numpy.zeros(ConstPixelDims, dtype=dcm.pixel_array.dtype)

npArray[:, :] = dcm.pixel_array

#get it to itk
itkImg=itk.GetImageFromArray(npArray)


#works for DORA dicoms, but it would be great to be able to get that from itkImg
InputPixelType = itk.SS
#required by Canny
OutputPixelType = itk.F

Dimension = 2

InputImageType = itk.Image[InputPixelType, Dimension]
OutputImageType = itk.Image[OutputPixelType, Dimension]

#recast to F
castImageFilter = itk.CastImageFilter[InputImageType, OutputImageType].New()
castImageFilter.SetInput(itkImg)

#for debugging

castImageFilter.Update()
itkImg1=castImageFilter.GetOutput()

variance=2
upperThreshold=5
lowerThreshold=0.4*upperThreshold

cannyFilter = itk.CannyEdgeDetectionImageFilter[
    OutputImageType,
    OutputImageType].New()
cannyFilter.SetInput(castImageFilter.GetOutput())
cannyFilter.SetVariance(variance)
cannyFilter.SetLowerThreshold(lowerThreshold)
cannyFilter.SetUpperThreshold(upperThreshold)

cannyFilter.Update()

canny=cannyFilter.GetOutput()

npCanny=itk.GetArrayFromImage(canny)