andreped commited on
Commit
9435739
1 Parent(s): f339a16

Added support for accessing livermask as python package [no ci]

Browse files
livermask/livermask.py CHANGED
@@ -1,70 +1,13 @@
1
- import numpy as np
2
- import os
3
  import sys
4
- from tqdm import tqdm
5
- import nibabel as nib
6
- from nibabel.processing import resample_to_output, resample_from_to
7
- from scipy.ndimage import zoom
8
- from tensorflow.python.keras.models import load_model
9
- from skimage.morphology import remove_small_holes, binary_dilation, binary_erosion, ball
10
- from skimage.measure import label, regionprops
11
  import warnings
12
  import argparse
13
- import pkg_resources
14
- import tensorflow as tf
15
- import logging as log
16
- import chainer
17
- import math
18
- from .utils.unet3d import UNet3D
19
- import yaml
20
- from tensorflow.keras import backend as K
21
- from numba import cuda
22
- from .utils.process import liver_segmenter_wrapper, vessel_segmenter, intensity_normalization
23
- from .utils.utils import verboseHandler
24
- import logging as log
25
- from .utils.utils import get_model, get_vessel_model
26
 
27
 
28
  os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' # due to this: https://github.com/tensorflow/tensorflow/issues/35029
29
  warnings.filterwarnings('ignore', '.*output shape of zoom.*') # mute some warnings
30
 
31
 
32
- def func(path, output, cpu, verbose, vessels, extension):
33
- # enable verbose or not
34
- log = verboseHandler(verbose)
35
-
36
- cwd = "/".join(os.path.realpath(__file__).replace("\\", "/").split("/")[:-1]) + "/"
37
- name = cwd + "model.h5"
38
- name_vessel = cwd + "model-hepatic_vessel.npz"
39
-
40
- # get models
41
- get_model(name)
42
-
43
- if vessels:
44
- get_vessel_model(name_vessel)
45
-
46
- if not os.path.isdir(path):
47
- paths = [path]
48
- else:
49
- paths = [path + "/" + p for p in os.listdir(path)]
50
-
51
- multiple_flag = len(paths) > 1
52
- if multiple_flag:
53
- os.makedirs(output + "/", exist_ok=True)
54
-
55
- for curr in tqdm(paths, "CT:"):
56
- # check if current file is a nifti file, if not, skip
57
- if curr.endswith(".nii") or curr.endswith(".nii.gz"):
58
- # perform liver parenchyma segmentation, launch it in separate process to properly clear memory
59
- pred = liver_segmenter_wrapper(curr, output, cpu, verbose, multiple_flag, name, extension)
60
-
61
- if vessels:
62
- # perform liver vessel segmentation
63
- vessel_segmenter(curr, output, cpu, verbose, multiple_flag, pred, name_vessel, extension)
64
- else:
65
- log.info("Unsuported file: " + curr)
66
-
67
-
68
  def main():
69
  parser = argparse.ArgumentParser()
70
  parser.add_argument('-i', '--input', type=str, nargs='?',
@@ -79,7 +22,11 @@ def main():
79
  help="segment vessels.")
80
  parser.add_argument('-e', '--extension', type=str, default=".nii",
81
  help="define the output extension. (default: .nii)")
82
- ret = parser.parse_args(sys.argv[1:]); print(ret)
 
 
 
 
83
 
84
  if ret.cpu:
85
  os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
@@ -114,7 +61,9 @@ def main():
114
  if ret.extension not in [".nii", ".nii.gz"]:
115
  raise ValueError("Extension not supported. Expected: .nii or .nii.gz")
116
 
117
- func(*vars(ret).values())
 
 
118
 
119
 
120
  if __name__ == "__main__":
 
 
 
1
  import sys
2
+ import os
 
 
 
 
 
 
3
  import warnings
4
  import argparse
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
 
7
  os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' # due to this: https://github.com/tensorflow/tensorflow/issues/35029
8
  warnings.filterwarnings('ignore', '.*output shape of zoom.*') # mute some warnings
9
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def main():
12
  parser = argparse.ArgumentParser()
13
  parser.add_argument('-i', '--input', type=str, nargs='?',
 
22
  help="segment vessels.")
23
  parser.add_argument('-e', '--extension', type=str, default=".nii",
24
  help="define the output extension. (default: .nii)")
25
+ ret = parser.parse_args(sys.argv[1:])
26
+ print(ret)
27
+
28
+ # only now do we call tensorflow, if necessary (to avoid redundant imports for livermask -h call)
29
+ import tensorflow as tf
30
 
31
  if ret.cpu:
32
  os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
 
61
  if ret.extension not in [".nii", ".nii.gz"]:
62
  raise ValueError("Extension not supported. Expected: .nii or .nii.gz")
63
 
64
+ # finally, import run_analysis method with relevant imports and run analysis
65
+ from .utils.run import run_analysis
66
+ run_analysis(*vars(ret).values())
67
 
68
 
69
  if __name__ == "__main__":
livermask/utils/__init__.py CHANGED
@@ -1,2 +0,0 @@
1
-
2
-
 
 
 
livermask/utils/run.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import os
3
+ import sys
4
+ from tqdm import tqdm
5
+ import nibabel as nib
6
+ from nibabel.processing import resample_to_output, resample_from_to
7
+ from scipy.ndimage import zoom
8
+ from tensorflow.python.keras.models import load_model
9
+ from skimage.morphology import remove_small_holes, binary_dilation, binary_erosion, ball
10
+ from skimage.measure import label, regionprops
11
+ import warnings
12
+ import argparse
13
+ import pkg_resources
14
+ import tensorflow as tf
15
+ import logging as log
16
+ import math
17
+ from .unet3d import UNet3D
18
+ import yaml
19
+ from tensorflow.keras import backend as K
20
+ from numba import cuda
21
+ from .process import liver_segmenter_wrapper, vessel_segmenter, intensity_normalization
22
+ from .utils import verboseHandler
23
+ import logging as log
24
+ from .utils import get_model, get_vessel_model
25
+
26
+
27
+ def run_analysis(path, output, cpu, verbose, vessels, extension):
28
+ # fix paths (necessary if called as a package and not CLI)
29
+ path = path.replace("\\", "/")
30
+ output = output.replace("\\", "/")
31
+
32
+ # enable verbose or not
33
+ log = verboseHandler(verbose)
34
+
35
+ cwd = "/".join(os.path.realpath(__file__).replace("\\", "/").split("/")[:-1]) + "/"
36
+ name = cwd + "model.h5"
37
+ name_vessel = cwd + "model-hepatic_vessel.npz"
38
+
39
+ # get models
40
+ get_model(name)
41
+
42
+ if vessels:
43
+ get_vessel_model(name_vessel)
44
+
45
+ if not os.path.isdir(path):
46
+ paths = [path]
47
+ else:
48
+ paths = [path + "/" + p for p in os.listdir(path)]
49
+
50
+ multiple_flag = len(paths) > 1
51
+ if multiple_flag:
52
+ os.makedirs(output + "/", exist_ok=True)
53
+
54
+ for curr in tqdm(paths, "CT:"):
55
+ # check if current file is a nifti file, if not, skip
56
+ if curr.endswith(".nii") or curr.endswith(".nii.gz"):
57
+ # perform liver parenchyma segmentation, launch it in separate process to properly clear memory
58
+ pred = liver_segmenter_wrapper(curr, output, cpu, verbose, multiple_flag, name, extension)
59
+
60
+ if vessels:
61
+ # perform liver vessel segmentation
62
+ vessel_segmenter(curr, output, cpu, verbose, multiple_flag, pred, name_vessel, extension)
63
+ else:
64
+ log.info("Unsuported file: " + curr)
setup.py CHANGED
@@ -19,13 +19,7 @@ setup(
19
  long_description_content_type="text/markdown",
20
  url="https://github.com/andreped/livermask",
21
  include_package_data=True,
22
- packages=find_packages(
23
- include=[
24
- 'livermask',
25
- 'livermask.utils',
26
- 'livermask.configs',
27
- ]
28
- ),
29
  entry_points={
30
  'console_scripts': [
31
  'livermask = livermask.livermask:main',
 
19
  long_description_content_type="text/markdown",
20
  url="https://github.com/andreped/livermask",
21
  include_package_data=True,
22
+ packages=find_packages(exclude=('figures')),
 
 
 
 
 
 
23
  entry_points={
24
  'console_scripts': [
25
  'livermask = livermask.livermask:main',