Skip to content

Commit

Permalink
add keep objects filter
Browse files Browse the repository at this point in the history
  • Loading branch information
PeterMcGor committed Nov 20, 2017
1 parent cb5d26c commit b6c698f
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 10 deletions.
65 changes: 65 additions & 0 deletions Filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import SimpleITK

from Segmentation import A_Filter, FILTER_TYPE, UTILITIES_DIR, External_Filter, Simple_ITK_Filter, Fiji_Filter
from UsefullFunctions import AttrDict


class Apply_Median(External_Filter):
Expand Down Expand Up @@ -261,6 +262,70 @@ def set_Filter_ITK(self):
self.simple_itk_filter.SetKernelType(self.kernel)
def set_params(self):
self.params = [self.backgorund, self.foregorund, self.boundary_foreground]

class Keep_N_Objects(A_Filter):
"""
Input should be a label image
order 0 for descending order
works fine up to 2^16 labels
"""
SIZE = 'Physical Size'
FERET_DIAMETER = 'Feret Diameter'
PERIMETER = 'Perimeter'
ELONGATION = 'Elongation'
SPHERICAL_DIAMETER = 'Spherical Diameter'
SPHERICAL_RADIUS = 'Spherical Radius'
FLATNESS = 'Flatness'
PIXELS = 'Number of Pixels'
PIXELS_ON_BORDER = 'Number of pixels on border'
PERIMETER_ON_BORDER = 'Perimeter on border'
PERIMETER_ON_BORDER_RATIO = 'Perimeter on border ratio'
ROUNDNESS = 'Roundness'


def __init__(self, n_objects = 3, feature = SIZE, order = 0, bck_val = 0, save_img =(None,True) ):
A_Filter.__init__(self, 'Keep-Objects', FILTER_TYPE.OTHERS, built_in=True, save_img=save_img)
self.n_objects = n_objects
self.feature = feature
self.order = order
self.bck_val = bck_val

def execute(self,inputimage, output = None):
self.to_interface(inputimage)
shape_stats = SimpleITK.LabelShapeStatisticsImageFilter()
FEATS = {Keep_N_Objects.SIZE:shape_stats.GetPhysicalSize,
Keep_N_Objects.ELONGATION:shape_stats.GetElongation,
Keep_N_Objects.SPHERICAL_DIAMETER:shape_stats.GetEquivalentSphericalPerimeter,
Keep_N_Objects.SPHERICAL_RADIUS:shape_stats.GetEquivalentSphericalRadius,
Keep_N_Objects.FERET_DIAMETER:shape_stats.GetFeretDiameter,
Keep_N_Objects.FLATNESS:shape_stats.GetFlatness,
Keep_N_Objects.PIXELS:shape_stats.GetNumberOfPixels,
Keep_N_Objects.PIXELS_ON_BORDER:shape_stats.GetNumberOfPixelsOnBorder,
Keep_N_Objects.PERIMETER:shape_stats.GetPerimeter,
Keep_N_Objects.PERIMETER_ON_BORDER:shape_stats.GetPerimeterOnBorder,
Keep_N_Objects.PERIMETER_ON_BORDER_RATIO:shape_stats.GetPerimeterOnBorderRatio,
Keep_N_Objects.ROUNDNESS:shape_stats.GetRoundness}
shape_stats.Execute(self.input_path_and_image.image, self.bck_val,
self.feature == Keep_N_Objects.FERET_DIAMETER, self.feature == Keep_N_Objects.PERIMETER)
measures = np.array([FEATS[self.feature](l) for l in shape_stats.GetLabels() ])
sorted_selec_labels = np.array(shape_stats.GetLabels())[measures.argsort()[:self.n_objects]] if self.order != 0 else np.array(shape_stats.GetLabels())[measures.argsort()[-self.n_objects:]]

type_im = SimpleITK.sitkUInt8 if np.max(sorted_selec_labels)/256 < 1 else SimpleITK.sitkUInt16
print type_im
self.output_path_and_image.image = SimpleITK.Image(self.input_path_and_image.image.GetSize(),type_im)
self.output_path_and_image.image.CopyInformation(self.input_path_and_image.image)
print sorted_selec_labels
for l in sorted_selec_labels:
print l
masked = self.input_path_and_image.image == l if type_im == SimpleITK.sitkUInt8 else SimpleITK.Cast(self.input_path_and_image.image == l, SimpleITK.sitkUInt16)
self.output_path_and_image.image += masked*l

self.output_path_and_image.path = self.output_path_and_image.path if output is None else output
SimpleITK.WriteImage(self.output_path_and_image.image,self.output_path_and_image.path)

return self




class Hu_Threshold(A_Filter):
Expand Down
10 changes: 8 additions & 2 deletions SRM.ijm
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@
#@int q
#@String averages
#@String threeD
run("Image Sequence...", "open="+image_path+" sort");
#@String image_out_path
print (File.isDirectory(image_path));
if (File.isDirectory(image_path) == "1") {
run("Image Sequence...", "open="+image_path+" sort");
} else {
open(image_path);
}
run("8-bit");
run("Statistical Region Merging", "q="+q+" "+averages+" "+threeD);
saveAs("Tiff", "/tmp/outSRM.tif");
run("Save", "save="+image_out_path);
exit ("No argument!");
3 changes: 2 additions & 1 deletion Segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,13 @@ class Fiji_Filter(A_Filter):
def execute(self, a_filter, output = None): #Input and Output can be just paths
"""
a_filter and image or another filter
This version will close all Fiji instances
"""
self.input_path_and_image.path = a_filter.output_path_and_image.path if isinstance(a_filter,A_Filter) else a_filter
self.output_path_and_image.path = self.output_path_and_image.path if output is None else output
self.set_params()
self.check_params()
calling_external('pkill',[ '-f', 'ImageJ*'])
calling_external('pkill',[ '-f', 'ImageJ-lin*'])
calling_external(self.path, ['--ij2', '--headless', '--run', ]+self.params)
return self

Expand Down
5 changes: 5 additions & 0 deletions UsefullFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ def hdr_to_mhd(pathimages):
pathfinal=os.path.join(os.path.abspath(os.path.join(i, os.pardir)),os.path.basename(os.path.normpath(i)).split('.')[0]+'.mhd')
SimpleITK.WriteImage(image,pathfinal)

class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self


if __name__ == "__main__":
print 'Functions'
Expand Down
39 changes: 32 additions & 7 deletions utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@
import time
import os

import glob

from Filters import SRM





def itkImageToSLIC(itk_image, n_seg = 1000, compactness = 0.0001, return_itk_image = True):
"""
Save space
Expand Down Expand Up @@ -52,22 +56,43 @@ def srm(itk_image, q = 25, three_dim = True, averages = False ):
temp_image_path_input = os.path.join(tempfile.gettempdir(),str(time.time())+'.mhd')
SimpleITK.WriteImage(itk_image, temp_image_path_input)
temp_image_path_output = os.path.join(tempfile.gettempdir(),str(time.time())+'.mhd')
srm = SRM(save_img=(temp_image_path_output, False),q=25)
srm = SRM(save_img=(temp_image_path_output, False),q=q)
srm.execute(temp_image_path_input)
srm_itk_image = SimpleITK.ReadImage(temp_image_path_output)
srm_itk_image.CopyInformation(itk_image)
return srm_itk_image

def test_label_bck():
folders = glob.glob('/media/pmacias/DATA2/amunoz/NUS_DATA_2016/PLTB7*/*/')
for i, folder in enumerate(folders):
images = glob.glob(folder+'/*/*UMAP*')
print i, images
for image in images:
t1s = glob.glob(os.path.split(image)[0]+'/*t1*')
for t1 in t1s:
print t1
t1_im = read_dicom(t1)
study = image.split('/')[-2]
image_im = read_dicom(image)
mask = image_im==0
SimpleITK.WriteImage(mask, os.path.join('/tmp/'+study+'.mhd'))
SimpleITK.WriteImage(t1_im, os.path.join('/tmp/t1'+study+'.mhd'))
SimpleITK.WriteImage(resamplig(t1_im, mask, interpolator=SimpleITK.sitkNearestNeighbor), os.path.join('/tmp/resam'+study+'.mhd'))




if __name__ == "__main__":
t1_fat_sup_dcm = '/media/pmacias/DATA2/amunoz/NUS_DATA_2016/PLTB706/20131121/102152_812000/t1_vibe_tra_bh_fatsat_exsp_0037'
t1_fat_sup = read_dicom(t1_fat_sup_dcm)
# t1_fat_sup_dcm = '/media/pmacias/DATA2/amunoz/NUS_DATA_2016/PLTB706/20131121/102152_812000/t1_vibe_tra_bh_fatsat_exsp_0037'
# t1_fat_sup = read_dicom(t1_fat_sup_dcm)
# t1_fat_sup_slic = itkImageToSLIC(t1_fat_sup)
# SimpleITK.WriteImage(t1_fat_sup_slic, '/tmp/slic_res.mhd')
t1_seg = srm(t1_fat_sup)
pt_dcm = '/media/pmacias/DATA2/amunoz/NUS_DATA_2016/PLTB706/20131121/102152_812000/_Tho_MRAC_PET_15_min_list_AC_Images_0020/'
pt = read_dicom(pt_dcm)
SimpleITK.WriteImage(resamplig(pt,t1_seg), 'labels_to_pet.mhd')
# t1_seg = srm(t1_fat_sup, q=2)
# pt_dcm = '/media/pmacias/DATA2/amunoz/NUS_DATA_2016/PLTB706/20131121/102152_812000/_Tho_MRAC_PET_15_min_list_AC_Images_0020/'
# pt = read_dicom(pt_dcm)
# SimpleITK.WriteImage(resamplig(pt,t1_seg, interpolator=SimpleITK.sitkNearestNeighbor), '/tmp/labels_to_pet_NN.mhd')
# pt = SimpleITK.Cast(pt, SimpleITK.sitkFloat32)
# SimpleITK.WriteImage(pt,'/tmp/pt.mhd')
test_label_bck()


0 comments on commit b6c698f

Please sign in to comment.