guohanghui commited on
Commit
58df9da
·
verified ·
1 Parent(s): dcc205c

Upload 230 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +11 -0
  2. medpy/mcp_output/README_MCP.md +107 -0
  3. medpy/mcp_output/analysis.json +516 -0
  4. medpy/mcp_output/env_info.json +15 -0
  5. medpy/mcp_output/mcp_logs/llm_statistics.json +11 -0
  6. medpy/mcp_output/mcp_logs/run_log.json +65 -0
  7. medpy/mcp_output/mcp_plugin/__init__.py +0 -0
  8. medpy/mcp_output/mcp_plugin/__pycache__/adapter.cpython-310.pyc +0 -0
  9. medpy/mcp_output/mcp_plugin/__pycache__/mcp_service.cpython-310.pyc +0 -0
  10. medpy/mcp_output/mcp_plugin/adapter.py +117 -0
  11. medpy/mcp_output/mcp_plugin/main.py +13 -0
  12. medpy/mcp_output/mcp_plugin/mcp_service.py +617 -0
  13. medpy/mcp_output/requirements.txt +8 -0
  14. medpy/mcp_output/simple_revise_error_analysis.json +6 -0
  15. medpy/mcp_output/start_mcp.py +33 -0
  16. medpy/mcp_output/tests_mcp/test_mcp_basic.py +49 -0
  17. medpy/mcp_output/tests_smoke/test_smoke.py +29 -0
  18. medpy/source/.github/workflows/README.md +16 -0
  19. medpy/source/.github/workflows/build-publish-test.yml +54 -0
  20. medpy/source/.github/workflows/pre-commit.yml +30 -0
  21. medpy/source/.github/workflows/publish.yml +56 -0
  22. medpy/source/.github/workflows/run-tests-gc.yml +55 -0
  23. medpy/source/.github/workflows/run-tests.yml +43 -0
  24. medpy/source/.gitignore +97 -0
  25. medpy/source/.pre-commit-config.yaml +35 -0
  26. medpy/source/CHANGES.txt +17 -0
  27. medpy/source/LICENSE.txt +674 -0
  28. medpy/source/MANIFEST.in +7 -0
  29. medpy/source/README.md +38 -0
  30. medpy/source/README_PYPI.md +157 -0
  31. medpy/source/RELEASE.md +28 -0
  32. medpy/source/__init__.py +4 -0
  33. medpy/source/bin/medpy_anisotropic_diffusion.py +150 -0
  34. medpy/source/bin/medpy_apparent_diffusion_coefficient.py +218 -0
  35. medpy/source/bin/medpy_binary_resampling.py +313 -0
  36. medpy/source/bin/medpy_convert.py +107 -0
  37. medpy/source/bin/medpy_create_empty_volume_by_example.py +101 -0
  38. medpy/source/bin/medpy_dicom_slices_to_volume.py +105 -0
  39. medpy/source/bin/medpy_dicom_to_4D.py +171 -0
  40. medpy/source/bin/medpy_diff.py +124 -0
  41. medpy/source/bin/medpy_extract_contour.py +188 -0
  42. medpy/source/bin/medpy_extract_min_max.py +127 -0
  43. medpy/source/bin/medpy_extract_sub_volume.py +190 -0
  44. medpy/source/bin/medpy_extract_sub_volume_auto.py +189 -0
  45. medpy/source/bin/medpy_extract_sub_volume_by_example.py +199 -0
  46. medpy/source/bin/medpy_fit_into_shape.py +143 -0
  47. medpy/source/bin/medpy_gradient.py +120 -0
  48. medpy/source/bin/medpy_graphcut_label.py +212 -0
  49. medpy/source/bin/medpy_graphcut_label_bgreduced.py +271 -0
  50. medpy/source/bin/medpy_graphcut_label_w_regional.py +249 -0
.gitattributes CHANGED
@@ -33,3 +33,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ medpy/source/notebooks/scripts/images/adc.png filter=lfs diff=lfs merge=lfs -text
37
+ medpy/source/notebooks/scripts/images/b0.png filter=lfs diff=lfs merge=lfs -text
38
+ medpy/source/notebooks/scripts/images/b0gclabelstawiaski.png filter=lfs diff=lfs merge=lfs -text
39
+ medpy/source/notebooks/scripts/images/b0gcvoxelmax.png filter=lfs diff=lfs merge=lfs -text
40
+ medpy/source/notebooks/scripts/images/b0gradient.png filter=lfs diff=lfs merge=lfs -text
41
+ medpy/source/notebooks/scripts/images/b0wmarker.png filter=lfs diff=lfs merge=lfs -text
42
+ medpy/source/notebooks/scripts/images/b1000.png filter=lfs diff=lfs merge=lfs -text
43
+ medpy/source/notebooks/scripts/images/graphcut_voxel_gradient.png filter=lfs diff=lfs merge=lfs -text
44
+ medpy/source/notebooks/scripts/images/graphcut_voxel_grayvalues.png filter=lfs diff=lfs merge=lfs -text
45
+ medpy/source/notebooks/scripts/images/watershed_colored.png filter=lfs diff=lfs merge=lfs -text
46
+ medpy/source/notebooks/scripts/images/watershed.png filter=lfs diff=lfs merge=lfs -text
medpy/mcp_output/README_MCP.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MedPy Plugin
2
+
3
+ ## Overview
4
+
5
+ MedPy is a comprehensive library designed for medical image processing. It provides a wide range of tools and functionalities to facilitate the analysis and manipulation of medical images. The library supports various image formats and offers numerous utilities for image filtering, segmentation, and feature extraction.
6
+
7
+ The repository for MedPy can be found at [GitHub - MedPy](https://github.com/loli/medpy).
8
+
9
+ ## Installation
10
+
11
+ To install MedPy, ensure you have Python installed on your system. You can then clone the repository and install the package using the following commands:
12
+
13
+ ```bash
14
+ git clone https://github.com/loli/medpy.git
15
+ cd medpy
16
+ python setup.py install
17
+ ```
18
+
19
+ ### Dependencies
20
+
21
+ MedPy requires the following Python packages:
22
+
23
+ - `numpy`
24
+ - `scipy`
25
+ - `matplotlib`
26
+
27
+ Optional dependency:
28
+
29
+ - `pydicom` (for handling DICOM files)
30
+
31
+ ## Usage
32
+
33
+ MedPy provides several command-line interface (CLI) tools for various image processing tasks. Below are some of the available tools and their descriptions:
34
+
35
+ ### CLI Tools
36
+
37
+ - **medpy_anisotropic_diffusion**: Performs anisotropic diffusion on images.
38
+ - **medpy_convert**: Converts image formats.
39
+
40
+ To use a CLI tool, run the following command in your terminal:
41
+
42
+ ```bash
43
+ python -m bin.<tool_name> [options]
44
+ ```
45
+
46
+ Replace `<tool_name>` with the desired tool, such as `medpy_anisotropic_diffusion`.
47
+
48
+ ## Available Tool Endpoints
49
+
50
+ MedPy includes a variety of tools for different image processing needs. Here is a list of available tools:
51
+
52
+ - `medpy_anisotropic_diffusion.py`
53
+ - `medpy_apparent_diffusion_coefficient.py`
54
+ - `medpy_binary_resampling.py`
55
+ - `medpy_convert.py`
56
+ - `medpy_create_empty_volume_by_example.py`
57
+ - `medpy_dicom_slices_to_volume.py`
58
+ - `medpy_dicom_to_4D.py`
59
+ - `medpy_diff.py`
60
+ - `medpy_extract_contour.py`
61
+ - `medpy_extract_min_max.py`
62
+ - `medpy_extract_sub_volume.py`
63
+ - `medpy_extract_sub_volume_auto.py`
64
+ - `medpy_extract_sub_volume_by_example.py`
65
+ - `medpy_fit_into_shape.py`
66
+ - `medpy_gradient.py`
67
+ - `medpy_graphcut_label.py`
68
+ - `medpy_graphcut_label_bgreduced.py`
69
+ - `medpy_graphcut_label_w_regional.py`
70
+ - `medpy_graphcut_label_wsplit.py`
71
+ - `medpy_graphcut_voxel.py`
72
+ - `medpy_grid.py`
73
+ - `medpy_info.py`
74
+ - `medpy_intensity_range_standardization.py`
75
+ - `medpy_intersection.py`
76
+ - `medpy_join_masks.py`
77
+ - `medpy_join_xd_to_xplus1d.py`
78
+ - `medpy_label_count.py`
79
+ - `medpy_label_fit_to_mask.py`
80
+ - `medpy_label_superimposition.py`
81
+ - `medpy_merge.py`
82
+ - `medpy_morphology.py`
83
+ - `medpy_resample.py`
84
+ - `medpy_reslice_3d_to_4d.py`
85
+ - `medpy_set_pixel_spacing.py`
86
+ - `medpy_shrink_image.py`
87
+ - `medpy_split_xd_to_xminus1d.py`
88
+ - `medpy_stack_sub_volumes.py`
89
+ - `medpy_swap_dimensions.py`
90
+ - `medpy_watershed.py`
91
+ - `medpy_zoom_image.py`
92
+
93
+ ## Notes and Troubleshooting
94
+
95
+ - Ensure all dependencies are installed before running the tools.
96
+ - If you encounter issues with DICOM files, verify that `pydicom` is installed.
97
+ - For detailed usage of each tool, refer to the help command:
98
+
99
+ ```bash
100
+ python -m bin.<tool_name> --help
101
+ ```
102
+
103
+ - If you experience any issues or have questions, please refer to the [GitHub repository](https://github.com/loli/medpy) for further documentation and support.
104
+
105
+ ## License
106
+
107
+ MedPy is licensed under the MIT License. For more details, see the `LICENSE.txt` file in the repository.
medpy/mcp_output/analysis.json ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "summary": {
3
+ "repository_url": "https://github.com/loli/medpy",
4
+ "summary": "Imported via zip fallback, file count: 124",
5
+ "file_tree": {
6
+ ".github/workflows/README.md": {
7
+ "size": 1018
8
+ },
9
+ ".github/workflows/build-publish-test.yml": {
10
+ "size": 1666
11
+ },
12
+ ".github/workflows/pre-commit.yml": {
13
+ "size": 746
14
+ },
15
+ ".github/workflows/publish.yml": {
16
+ "size": 1554
17
+ },
18
+ ".github/workflows/run-tests-gc.yml": {
19
+ "size": 1942
20
+ },
21
+ ".github/workflows/run-tests.yml": {
22
+ "size": 1147
23
+ },
24
+ ".pre-commit-config.yaml": {
25
+ "size": 838
26
+ },
27
+ "CHANGES.txt": {
28
+ "size": 1297
29
+ },
30
+ "LICENSE.txt": {
31
+ "size": 35147
32
+ },
33
+ "README.md": {
34
+ "size": 1892
35
+ },
36
+ "README_PYPI.md": {
37
+ "size": 5614
38
+ },
39
+ "RELEASE.md": {
40
+ "size": 1077
41
+ },
42
+ "bin/medpy_anisotropic_diffusion.py": {
43
+ "size": 4486
44
+ },
45
+ "bin/medpy_apparent_diffusion_coefficient.py": {
46
+ "size": 7368
47
+ },
48
+ "bin/medpy_binary_resampling.py": {
49
+ "size": 10766
50
+ },
51
+ "bin/medpy_convert.py": {
52
+ "size": 3071
53
+ },
54
+ "bin/medpy_create_empty_volume_by_example.py": {
55
+ "size": 2984
56
+ },
57
+ "bin/medpy_dicom_slices_to_volume.py": {
58
+ "size": 3086
59
+ },
60
+ "bin/medpy_dicom_to_4D.py": {
61
+ "size": 6511
62
+ },
63
+ "bin/medpy_diff.py": {
64
+ "size": 3769
65
+ },
66
+ "bin/medpy_extract_contour.py": {
67
+ "size": 6209
68
+ },
69
+ "bin/medpy_extract_min_max.py": {
70
+ "size": 3669
71
+ },
72
+ "bin/medpy_extract_sub_volume.py": {
73
+ "size": 6589
74
+ },
75
+ "bin/medpy_extract_sub_volume_auto.py": {
76
+ "size": 6149
77
+ },
78
+ "bin/medpy_extract_sub_volume_by_example.py": {
79
+ "size": 6700
80
+ },
81
+ "bin/medpy_fit_into_shape.py": {
82
+ "size": 4225
83
+ },
84
+ "bin/medpy_gradient.py": {
85
+ "size": 3589
86
+ },
87
+ "bin/medpy_graphcut_label.py": {
88
+ "size": 7371
89
+ },
90
+ "bin/medpy_graphcut_label_bgreduced.py": {
91
+ "size": 9004
92
+ },
93
+ "bin/medpy_graphcut_label_w_regional.py": {
94
+ "size": 8936
95
+ },
96
+ "bin/medpy_graphcut_label_wsplit.py": {
97
+ "size": 5636
98
+ },
99
+ "bin/medpy_graphcut_voxel.py": {
100
+ "size": 8923
101
+ },
102
+ "bin/medpy_grid.py": {
103
+ "size": 9151
104
+ },
105
+ "bin/medpy_info.py": {
106
+ "size": 3332
107
+ },
108
+ "bin/medpy_intensity_range_standardization.py": {
109
+ "size": 10440
110
+ },
111
+ "bin/medpy_intersection.py": {
112
+ "size": 4582
113
+ },
114
+ "bin/medpy_join_masks.py": {
115
+ "size": 4645
116
+ },
117
+ "bin/medpy_join_xd_to_xplus1d.py": {
118
+ "size": 5622
119
+ },
120
+ "bin/medpy_label_count.py": {
121
+ "size": 3048
122
+ },
123
+ "bin/medpy_label_fit_to_mask.py": {
124
+ "size": 4521
125
+ },
126
+ "bin/medpy_label_superimposition.py": {
127
+ "size": 6311
128
+ },
129
+ "bin/medpy_merge.py": {
130
+ "size": 3361
131
+ },
132
+ "bin/medpy_morphology.py": {
133
+ "size": 5073
134
+ },
135
+ "bin/medpy_resample.py": {
136
+ "size": 4721
137
+ },
138
+ "bin/medpy_reslice_3d_to_4d.py": {
139
+ "size": 5650
140
+ },
141
+ "bin/medpy_set_pixel_spacing.py": {
142
+ "size": 2771
143
+ },
144
+ "bin/medpy_shrink_image.py": {
145
+ "size": 4676
146
+ },
147
+ "bin/medpy_split_xd_to_xminus1d.py": {
148
+ "size": 4587
149
+ },
150
+ "bin/medpy_stack_sub_volumes.py": {
151
+ "size": 5128
152
+ },
153
+ "bin/medpy_swap_dimensions.py": {
154
+ "size": 4357
155
+ },
156
+ "bin/medpy_watershed.py": {
157
+ "size": 4492
158
+ },
159
+ "bin/medpy_zoom_image.py": {
160
+ "size": 5514
161
+ },
162
+ "doc/README.md": {
163
+ "size": 225
164
+ },
165
+ "doc/source/conf.py": {
166
+ "size": 6612
167
+ },
168
+ "lib/maxflow/src/CMakeLists.txt": {
169
+ "size": 589
170
+ },
171
+ "lib/maxflow/src/get_edge_test.py": {
172
+ "size": 1970
173
+ },
174
+ "lib/maxflow/src/sum_edge_test.py": {
175
+ "size": 1931
176
+ },
177
+ "medpy/__init__.py": {
178
+ "size": 1002
179
+ },
180
+ "medpy/core/__init__.py": {
181
+ "size": 2282
182
+ },
183
+ "medpy/core/exceptions.py": {
184
+ "size": 1720
185
+ },
186
+ "medpy/core/logger.py": {
187
+ "size": 4681
188
+ },
189
+ "medpy/features/__init__.py": {
190
+ "size": 7493
191
+ },
192
+ "medpy/features/histogram.py": {
193
+ "size": 18892
194
+ },
195
+ "medpy/features/intensity.py": {
196
+ "size": 33952
197
+ },
198
+ "medpy/features/texture.py": {
199
+ "size": 12870
200
+ },
201
+ "medpy/features/utilities.py": {
202
+ "size": 6124
203
+ },
204
+ "medpy/filter/IntensityRangeStandardization.py": {
205
+ "size": 24588
206
+ },
207
+ "medpy/filter/__init__.py": {
208
+ "size": 5301
209
+ },
210
+ "medpy/filter/binary.py": {
211
+ "size": 4808
212
+ },
213
+ "medpy/filter/houghtransform.py": {
214
+ "size": 9622
215
+ },
216
+ "medpy/filter/image.py": {
217
+ "size": 19807
218
+ },
219
+ "medpy/filter/label.py": {
220
+ "size": 5891
221
+ },
222
+ "medpy/filter/noise.py": {
223
+ "size": 7399
224
+ },
225
+ "medpy/filter/smoothing.py": {
226
+ "size": 6120
227
+ },
228
+ "medpy/filter/utilities.py": {
229
+ "size": 11284
230
+ },
231
+ "medpy/graphcut/__init__.py": {
232
+ "size": 7613
233
+ },
234
+ "medpy/graphcut/energy_label.py": {
235
+ "size": 19015
236
+ },
237
+ "medpy/graphcut/energy_voxel.py": {
238
+ "size": 26949
239
+ },
240
+ "medpy/graphcut/generate.py": {
241
+ "size": 16053
242
+ },
243
+ "medpy/graphcut/graph.py": {
244
+ "size": 19756
245
+ },
246
+ "medpy/graphcut/wrapper.py": {
247
+ "size": 10794
248
+ },
249
+ "medpy/graphcut/write.py": {
250
+ "size": 2620
251
+ },
252
+ "medpy/io/__init__.py": {
253
+ "size": 2057
254
+ },
255
+ "medpy/io/header.py": {
256
+ "size": 10789
257
+ },
258
+ "medpy/io/load.py": {
259
+ "size": 4413
260
+ },
261
+ "medpy/io/save.py": {
262
+ "size": 4309
263
+ },
264
+ "medpy/iterators/__init__.py": {
265
+ "size": 1532
266
+ },
267
+ "medpy/iterators/patchwise.py": {
268
+ "size": 26214
269
+ },
270
+ "medpy/metric/__init__.py": {
271
+ "size": 5837
272
+ },
273
+ "medpy/metric/binary.py": {
274
+ "size": 44707
275
+ },
276
+ "medpy/metric/histogram.py": {
277
+ "size": 32470
278
+ },
279
+ "medpy/metric/image.py": {
280
+ "size": 4150
281
+ },
282
+ "medpy/neighbours/__init__.py": {
283
+ "size": 1387
284
+ },
285
+ "medpy/neighbours/knn.py": {
286
+ "size": 4364
287
+ },
288
+ "medpy/utilities/__init__.py": {
289
+ "size": 1138
290
+ },
291
+ "medpy/utilities/argparseu.py": {
292
+ "size": 7217
293
+ },
294
+ "notebooks/scripts/images/b0.txt": {
295
+ "size": 171
296
+ },
297
+ "notebooks/scripts/images/b1000.txt": {
298
+ "size": 171
299
+ },
300
+ "pytest.ini": {
301
+ "size": 43
302
+ },
303
+ "setup.py": {
304
+ "size": 8290
305
+ },
306
+ "tests/README.md": {
307
+ "size": 591
308
+ },
309
+ "tests/__init__.py": {
310
+ "size": 42
311
+ },
312
+ "tests/features_/__init__.py": {
313
+ "size": 289
314
+ },
315
+ "tests/features_/histogram.py": {
316
+ "size": 11950
317
+ },
318
+ "tests/features_/intensity.py": {
319
+ "size": 17154
320
+ },
321
+ "tests/features_/texture.py": {
322
+ "size": 5375
323
+ },
324
+ "tests/filter_/IntensityRangeStandardization.py": {
325
+ "size": 6566
326
+ },
327
+ "tests/filter_/__init__.py": {
328
+ "size": 263
329
+ },
330
+ "tests/filter_/anisotropic_diffusion.py": {
331
+ "size": 1535
332
+ },
333
+ "tests/filter_/houghtransform.py": {
334
+ "size": 8391
335
+ },
336
+ "tests/filter_/image.py": {
337
+ "size": 9081
338
+ },
339
+ "tests/filter_/utilities.py": {
340
+ "size": 4678
341
+ },
342
+ "tests/graphcut_/__init__.py": {
343
+ "size": 280
344
+ },
345
+ "tests/graphcut_/cut.py": {
346
+ "size": 7482
347
+ },
348
+ "tests/graphcut_/energy_label.py": {
349
+ "size": 11363
350
+ },
351
+ "tests/graphcut_/energy_voxel.py": {
352
+ "size": 7144
353
+ },
354
+ "tests/graphcut_/graph.py": {
355
+ "size": 3850
356
+ },
357
+ "tests/io_/__init__.py": {
358
+ "size": 191
359
+ },
360
+ "tests/io_/loadsave.py": {
361
+ "size": 13662
362
+ },
363
+ "tests/io_/metadata.py": {
364
+ "size": 19296
365
+ },
366
+ "tests/metric_/__init__.py": {
367
+ "size": 0
368
+ },
369
+ "tests/metric_/binary.py": {
370
+ "size": 1762
371
+ },
372
+ "tests/metric_/histogram.py": {
373
+ "size": 3360
374
+ },
375
+ "tests/support.py": {
376
+ "size": 889
377
+ }
378
+ },
379
+ "processed_by": "zip_fallback",
380
+ "success": true
381
+ },
382
+ "structure": {
383
+ "packages": [
384
+ "source.medpy",
385
+ "source.medpy.core",
386
+ "source.medpy.features",
387
+ "source.medpy.filter",
388
+ "source.medpy.graphcut",
389
+ "source.medpy.io",
390
+ "source.medpy.iterators",
391
+ "source.medpy.metric",
392
+ "source.medpy.neighbours",
393
+ "source.medpy.utilities",
394
+ "source.tests",
395
+ "source.tests.features_",
396
+ "source.tests.filter_",
397
+ "source.tests.graphcut_",
398
+ "source.tests.io_",
399
+ "source.tests.metric_"
400
+ ]
401
+ },
402
+ "dependencies": {
403
+ "has_environment_yml": false,
404
+ "has_requirements_txt": false,
405
+ "pyproject": false,
406
+ "setup_cfg": false,
407
+ "setup_py": true
408
+ },
409
+ "entry_points": {
410
+ "imports": [],
411
+ "cli": [],
412
+ "modules": []
413
+ },
414
+ "llm_analysis": {
415
+ "core_modules": [
416
+ {
417
+ "package": "source.medpy.core",
418
+ "module": "exceptions",
419
+ "functions": [],
420
+ "classes": [
421
+ "MedPyError",
422
+ "MedPyWarning"
423
+ ],
424
+ "description": "Defines core exceptions and warnings for MedPy."
425
+ },
426
+ {
427
+ "package": "source.medpy.features",
428
+ "module": "histogram",
429
+ "functions": [
430
+ "calculate_histogram",
431
+ "normalize_histogram"
432
+ ],
433
+ "classes": [],
434
+ "description": "Provides functions to calculate and normalize histograms."
435
+ },
436
+ {
437
+ "package": "source.medpy.filter",
438
+ "module": "image",
439
+ "functions": [
440
+ "anisotropic_diffusion",
441
+ "gaussian_filter"
442
+ ],
443
+ "classes": [],
444
+ "description": "Contains image filtering functions including diffusion and Gaussian filters."
445
+ },
446
+ {
447
+ "package": "source.medpy.graphcut",
448
+ "module": "graph",
449
+ "functions": [
450
+ "create_graph",
451
+ "cut_graph"
452
+ ],
453
+ "classes": [],
454
+ "description": "Implements graph-based segmentation methods."
455
+ },
456
+ {
457
+ "package": "source.medpy.io",
458
+ "module": "load",
459
+ "functions": [
460
+ "load_image"
461
+ ],
462
+ "classes": [],
463
+ "description": "Handles loading of medical images."
464
+ }
465
+ ],
466
+ "cli_commands": [
467
+ {
468
+ "name": "medpy_anisotropic_diffusion",
469
+ "module": "bin.medpy_anisotropic_diffusion",
470
+ "description": "CLI tool for performing anisotropic diffusion on images."
471
+ },
472
+ {
473
+ "name": "medpy_convert",
474
+ "module": "bin.medpy_convert",
475
+ "description": "CLI tool for converting image formats."
476
+ }
477
+ ],
478
+ "import_strategy": {
479
+ "primary": "import",
480
+ "fallback": "cli",
481
+ "confidence": 0.85
482
+ },
483
+ "dependencies": {
484
+ "required": [
485
+ "numpy",
486
+ "scipy",
487
+ "matplotlib"
488
+ ],
489
+ "optional": [
490
+ "pydicom"
491
+ ]
492
+ },
493
+ "risk_assessment": {
494
+ "import_feasibility": 0.8,
495
+ "intrusiveness_risk": "medium",
496
+ "complexity": "medium"
497
+ }
498
+ },
499
+ "deepwiki_analysis": {
500
+ "repo_url": "https://github.com/loli/medpy",
501
+ "repo_name": "medpy",
502
+ "content": null,
503
+ "model": "gpt-4o",
504
+ "source": "selenium",
505
+ "success": true
506
+ },
507
+ "deepwiki_options": {
508
+ "enabled": true,
509
+ "model": "gpt-4o"
510
+ },
511
+ "risk": {
512
+ "import_feasibility": 0.8,
513
+ "intrusiveness_risk": "medium",
514
+ "complexity": "medium"
515
+ }
516
+ }
medpy/mcp_output/env_info.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "environment": {
3
+ "type": "conda",
4
+ "name": "medpy_136254_env",
5
+ "files": {},
6
+ "python": "3.10",
7
+ "exec_prefix": []
8
+ },
9
+ "original_tests": {
10
+ "passed": true,
11
+ "report_path": null
12
+ },
13
+ "timestamp": 1761136573.9414783,
14
+ "conda_available": true
15
+ }
medpy/mcp_output/mcp_logs/llm_statistics.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "total_calls": 5,
3
+ "failed_calls": 0,
4
+ "retry_count": 0,
5
+ "total_prompt_tokens": 21657,
6
+ "total_completion_tokens": 5063,
7
+ "total_tokens": 26720,
8
+ "average_prompt_tokens": 4331.4,
9
+ "average_completion_tokens": 1012.6,
10
+ "average_tokens": 5344.0
11
+ }
medpy/mcp_output/mcp_logs/run_log.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": 1761136873.6488183,
3
+ "node": "RunNode",
4
+ "test_result": {
5
+ "passed": false,
6
+ "report_path": null,
7
+ "stdout": "",
8
+ "stderr": "ERROR conda.cli.main_run:execute(41): `conda run python mcp_output/start_mcp.py` failed. (See above for error)\nTraceback (most recent call last):\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/start_mcp.py\", line 17, in <module>\n from mcp_service import create_app\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin/mcp_service.py\", line 13, in <module>\n from medpy.features.histogram import (\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/source/medpy/features/__init__.py\", line 154, in <module>\n from .histogram import fuzzy_histogram as fuzzy_histogram\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/source/medpy/features/histogram.py\", line 25, in <module>\n import numpy\nModuleNotFoundError: No module named 'numpy'\n\n"
9
+ },
10
+ "run_result": {
11
+ "success": false,
12
+ "test_passed": false,
13
+ "exit_code": 1,
14
+ "stdout": "",
15
+ "stderr": "ERROR conda.cli.main_run:execute(41): `conda run python mcp_output/start_mcp.py` failed. (See above for error)\nTraceback (most recent call last):\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/start_mcp.py\", line 17, in <module>\n from mcp_service import create_app\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin/mcp_service.py\", line 13, in <module>\n from medpy.features.histogram import (\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/source/medpy/features/__init__.py\", line 154, in <module>\n from .histogram import fuzzy_histogram as fuzzy_histogram\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/source/medpy/features/histogram.py\", line 25, in <module>\n import numpy\nModuleNotFoundError: No module named 'numpy'\n\n",
16
+ "timestamp": 1761136873.6488087,
17
+ "error_type": "ImportError",
18
+ "error": "Module import failed: ERROR conda.cli.main_run:execute(41): `conda run python mcp_output/start_mcp.py` failed. (See above for error)\nTraceback (most recent call last):\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/start_mcp.py\", line 17, in <module>\n from mcp_service import create_app\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin/mcp_service.py\", line 13, in <module>\n from medpy.features.histogram import (\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/source/medpy/features/__init__.py\", line 154, in <module>\n from .histogram import fuzzy_histogram as fuzzy_histogram\n File \"/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/source/medpy/features/histogram.py\", line 25, in <module>\n import numpy\nModuleNotFoundError: No module named 'numpy'\n\n",
19
+ "details": {
20
+ "command": "/home/wshiah/code/miniconda3/bin/conda run -n medpy_136254_env --cwd /export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy python mcp_output/start_mcp.py",
21
+ "working_directory": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy",
22
+ "environment_type": "conda"
23
+ }
24
+ },
25
+ "environment": {
26
+ "type": "conda",
27
+ "name": "medpy_136254_env",
28
+ "files": {},
29
+ "python": "3.10",
30
+ "exec_prefix": []
31
+ },
32
+ "plugin_info": {
33
+ "files": {
34
+ "mcp_output/start_mcp.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/start_mcp.py",
35
+ "mcp_output/mcp_plugin/__init__.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin/__init__.py",
36
+ "mcp_output/mcp_plugin/mcp_service.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin/mcp_service.py",
37
+ "mcp_output/mcp_plugin/adapter.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin/adapter.py",
38
+ "mcp_output/mcp_plugin/main.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin/main.py",
39
+ "mcp_output/requirements.txt": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/requirements.txt",
40
+ "mcp_output/README_MCP.md": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/README_MCP.md",
41
+ "mcp_output/tests_mcp/test_mcp_basic.py": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/tests_mcp/test_mcp_basic.py"
42
+ },
43
+ "adapter_mode": "import",
44
+ "endpoints": [
45
+ "medpyerror",
46
+ "medpywarning",
47
+ "calculate_histogram",
48
+ "normalize_histogram",
49
+ "anisotropic_diffusion",
50
+ "gaussian_filter",
51
+ "create_graph",
52
+ "cut_graph",
53
+ "load_image"
54
+ ],
55
+ "mcp_dir": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/mcp_plugin",
56
+ "tests_dir": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/tests_mcp",
57
+ "main_entry": "start_mcp.py",
58
+ "readme_path": "/export/project/shiweijie/ghh/LLM_MCP_RAG/MCP-agent-github-repo-output/workspace/medpy/mcp_output/README_MCP.md",
59
+ "requirements": [
60
+ "fastmcp>=0.1.0",
61
+ "pydantic>=2.0.0"
62
+ ]
63
+ },
64
+ "fastmcp_installed": false
65
+ }
medpy/mcp_output/mcp_plugin/__init__.py ADDED
File without changes
medpy/mcp_output/mcp_plugin/__pycache__/adapter.cpython-310.pyc ADDED
Binary file (3.99 kB). View file
 
medpy/mcp_output/mcp_plugin/__pycache__/mcp_service.cpython-310.pyc ADDED
Binary file (8.68 kB). View file
 
medpy/mcp_output/mcp_plugin/adapter.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ # Path settings
5
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
6
+ sys.path.insert(0, source_path)
7
+
8
+ # Import statements
9
+ try:
10
+ from medpy.features.histogram import Histogram
11
+ from medpy.features.intensity import Intensity
12
+ from medpy.filter.image import ImageFilter
13
+ from medpy.io.load import load
14
+ from medpy.io.save import save
15
+ except ImportError as e:
16
+ print(f"Import error: {e}. Some functionalities may not be available.")
17
+
18
+ class Adapter:
19
+ """
20
+ Adapter class for the MCP plugin, providing access to various functionalities
21
+ from the medpy library.
22
+ """
23
+
24
+ def __init__(self):
25
+ self.mode = "import"
26
+
27
+ # -------------------------------------------------------------------------
28
+ # Feature Extraction Methods
29
+ # -------------------------------------------------------------------------
30
+
31
+ def create_histogram(self, image_data):
32
+ """
33
+ Create a histogram from the given image data.
34
+
35
+ :param image_data: The image data to process.
36
+ :return: A dictionary with the status and histogram data.
37
+ """
38
+ try:
39
+ histogram = Histogram(image_data)
40
+ return {"status": "success", "histogram": histogram}
41
+ except Exception as e:
42
+ return {"status": "error", "message": str(e)}
43
+
44
+ def calculate_intensity(self, image_data):
45
+ """
46
+ Calculate intensity features from the given image data.
47
+
48
+ :param image_data: The image data to process.
49
+ :return: A dictionary with the status and intensity data.
50
+ """
51
+ try:
52
+ intensity = Intensity(image_data)
53
+ return {"status": "success", "intensity": intensity}
54
+ except Exception as e:
55
+ return {"status": "error", "message": str(e)}
56
+
57
+ # -------------------------------------------------------------------------
58
+ # Image Filtering Methods
59
+ # -------------------------------------------------------------------------
60
+
61
+ def apply_image_filter(self, image_data, filter_type):
62
+ """
63
+ Apply a specified filter to the image data.
64
+
65
+ :param image_data: The image data to filter.
66
+ :param filter_type: The type of filter to apply.
67
+ :return: A dictionary with the status and filtered image data.
68
+ """
69
+ try:
70
+ image_filter = ImageFilter()
71
+ filtered_image = image_filter.apply_filter(image_data, filter_type)
72
+ return {"status": "success", "filtered_image": filtered_image}
73
+ except Exception as e:
74
+ return {"status": "error", "message": str(e)}
75
+
76
+ # -------------------------------------------------------------------------
77
+ # IO Methods
78
+ # -------------------------------------------------------------------------
79
+
80
+ def load_image(self, file_path):
81
+ """
82
+ Load an image from the specified file path.
83
+
84
+ :param file_path: The path to the image file.
85
+ :return: A dictionary with the status and loaded image data.
86
+ """
87
+ try:
88
+ image_data, header = load(file_path)
89
+ return {"status": "success", "image_data": image_data, "header": header}
90
+ except Exception as e:
91
+ return {"status": "error", "message": str(e)}
92
+
93
+ def save_image(self, image_data, file_path):
94
+ """
95
+ Save the image data to the specified file path.
96
+
97
+ :param image_data: The image data to save.
98
+ :param file_path: The path to save the image file.
99
+ :return: A dictionary with the status of the save operation.
100
+ """
101
+ try:
102
+ save(image_data, file_path)
103
+ return {"status": "success", "message": "Image saved successfully."}
104
+ except Exception as e:
105
+ return {"status": "error", "message": str(e)}
106
+
107
+ # -------------------------------------------------------------------------
108
+ # Fallback Handling
109
+ # -------------------------------------------------------------------------
110
+
111
+ def fallback_mode(self):
112
+ """
113
+ Handle operations in fallback mode when imports fail.
114
+
115
+ :return: A dictionary with the status and message.
116
+ """
117
+ return {"status": "warning", "message": "Running in fallback mode. Some functionalities are limited."}
medpy/mcp_output/mcp_plugin/main.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Service Auto-Wrapper - Auto-generated
3
+ """
4
+ from mcp_service import create_app
5
+
6
+ def main():
7
+ """Main entry point"""
8
+ app = create_app()
9
+ return app
10
+
11
+ if __name__ == "__main__":
12
+ app = main()
13
+ app.run()
medpy/mcp_output/mcp_plugin/mcp_service.py ADDED
@@ -0,0 +1,617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import numpy as np
4
+ import json
5
+
6
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
7
+ sys.path.insert(0, source_path)
8
+
9
+ from fastmcp import FastMCP
10
+ from medpy.core.exceptions import (
11
+ ArgumentError, DependencyError, FunctionError, ImageLoadingError,
12
+ ImageSavingError, ImageTypeError, MetaDataError, SubprocessError
13
+ )
14
+ from medpy.core.logger import Logger
15
+ from medpy.features.histogram import (
16
+ fuzzy_histogram, gaussian_membership, sigmoidal_difference_membership,
17
+ trapezoid_membership, triangular_membership
18
+ )
19
+ from medpy.features.intensity import (
20
+ centerdistance, centerdistance_xdminus1, gaussian_gradient_magnitude,
21
+ hemispheric_difference, indices, intensities, local_histogram,
22
+ local_mean_gauss, mask_distance, median, shifted_mean_gauss
23
+ )
24
+ from medpy.features.utilities import append, join, normalize, normalize_with_model
25
+ from medpy.filter.IntensityRangeStandardization import (
26
+ InformationLossException, IntensityRangeStandardization,
27
+ SingleIntensityAccumulationError, UntrainedException
28
+ )
29
+ from medpy.filter.binary import bounding_box, largest_connected_component, size_threshold
30
+ from medpy.filter.houghtransform import ght, ght_alternative, template_ellipsoid, template_sphere
31
+ from medpy.filter.image import (
32
+ average_filter, local_minima, otsu, resample, sls, ssd, sum_filter
33
+ )
34
+ from medpy.filter.label import fit_labels_to_mask, relabel, relabel_map, relabel_non_zero
35
+ from medpy.filter.noise import immerkaer, immerkaer_local, separable_convolution
36
+ from medpy.filter.smoothing import anisotropic_diffusion, gauss_xminus1d
37
+ from medpy.filter.utilities import intersection, pad, xminus1d
38
+ from medpy.graphcut.energy_label import (
39
+ boundary_difference_of_means, boundary_stawiaski, boundary_stawiaski_directed,
40
+ regional_atlas
41
+ )
42
+ from medpy.graphcut.energy_voxel import (
43
+ boundary_difference_division, boundary_difference_exponential,
44
+ boundary_difference_linear, boundary_difference_power, boundary_maximum_division,
45
+ boundary_maximum_exponential, boundary_maximum_linear, boundary_maximum_power,
46
+ regional_probability_map
47
+ )
48
+ from medpy.graphcut.generate import graph_from_labels, graph_from_voxels
49
+ from medpy.graphcut.graph import GCGraph, Graph
50
+ from medpy.graphcut.wrapper import graphcut_split, graphcut_stawiaski, graphcut_subprocesses, split_marker
51
+ from medpy.graphcut.write import graph_to_dimacs
52
+ from medpy.io.header import (
53
+ Header, copy_meta_data, get_offset, get_pixel_spacing, get_voxel_spacing,
54
+ set_offset, set_pixel_spacing, set_voxel_spacing
55
+ )
56
+ from medpy.io.load import load
57
+ from medpy.io.save import save
58
+ from medpy.iterators.patchwise import CentredPatchIterator, CentredPatchIteratorOverlapping, SlidingWindowIterator
59
+ from medpy.metric.binary import (
60
+ asd, assd, dc, hd, hd95, jc, obj_asd, obj_assd, obj_fpr, obj_tpr,
61
+ positive_predictive_value, precision, ravd, recall, sensitivity, specificity,
62
+ true_negative_rate, true_positive_rate, volume_change_correlation, volume_correlation
63
+ )
64
+ from medpy.metric.histogram import (
65
+ chebyshev, chebyshev_neg, chi_square, correlate, correlate_1, cosine, cosine_1,
66
+ cosine_2, cosine_alt, euclidean, fidelity_based, histogram_intersection,
67
+ histogram_intersection_1, jensen_shannon, kullback_leibler, manhattan, minowski,
68
+ noelle_1, noelle_2, noelle_3, noelle_4, noelle_5, quadratic_forms,
69
+ relative_bin_deviation, relative_deviation
70
+ )
71
+ from medpy.metric.image import mutual_information
72
+ from medpy.neighbours.knn import mkneighbors_graph, pdist
73
+ from medpy.utilities import argparseu
74
+
75
+ mcp = FastMCP("medpy_service")
76
+
77
+ @mcp.tool(name="log_exception", description="Log an exception using the MedPy logger.")
78
+ def log_exception(exception: Exception) -> dict:
79
+ """
80
+ Logs an exception using the MedPy logger.
81
+
82
+ Parameters:
83
+ - exception: Exception instance to be logged.
84
+
85
+ Returns:
86
+ - dict: Contains success status and result message.
87
+ """
88
+ try:
89
+ Logger().exception(exception)
90
+ return {"success": True, "result": "Exception logged successfully", "error": None}
91
+ except Exception as e:
92
+ return {"success": False, "result": None, "error": str(e)}
93
+
94
+ # ===== IO 工具 =====
95
+ @mcp.tool(name="load_image", description="Load medical image from file.")
96
+ def load_image(file_path: str) -> dict:
97
+ """
98
+ Loads a medical image from file.
99
+
100
+ Parameters:
101
+ - file_path: Path to the image file.
102
+
103
+ Returns:
104
+ - dict: Contains success status, image data, and metadata.
105
+ """
106
+ try:
107
+ image_data, meta_data = load(file_path)
108
+ return {
109
+ "success": True,
110
+ "result": {
111
+ "image": image_data.tolist() if isinstance(image_data, np.ndarray) else image_data,
112
+ "shape": list(image_data.shape) if hasattr(image_data, 'shape') else None,
113
+ "dtype": str(image_data.dtype) if hasattr(image_data, 'dtype') else None,
114
+ "metadata": str(meta_data)
115
+ },
116
+ "error": None
117
+ }
118
+ except Exception as e:
119
+ return {"success": False, "result": None, "error": str(e)}
120
+
121
+ @mcp.tool(name="save_image", description="Save image to file.")
122
+ def save_image(image_data: list, file_path: str, metadata: dict = None) -> dict:
123
+ """
124
+ Saves an image to file with optional metadata.
125
+
126
+ Parameters:
127
+ - image_data: Image data as list/array.
128
+ - file_path: Output file path.
129
+ - metadata: Optional metadata dictionary.
130
+
131
+ Returns:
132
+ - dict: Contains success status and result message.
133
+ """
134
+ try:
135
+ image_array = np.asarray(image_data)
136
+ meta = Header() if metadata is None else metadata
137
+ save(image_array, file_path, meta)
138
+ return {
139
+ "success": True,
140
+ "result": f"Image saved successfully to {file_path}",
141
+ "error": None
142
+ }
143
+ except Exception as e:
144
+ return {"success": False, "result": None, "error": str(e)}
145
+
146
+ # ===== 二值化和标记处理工具 =====
147
+ @mcp.tool(name="bounding_box", description="Compute bounding box of a binary image.")
148
+ def bounding_box_tool(binary_image: list) -> dict:
149
+ """
150
+ Computes the bounding box of a binary image.
151
+
152
+ Parameters:
153
+ - binary_image: Binary image data.
154
+
155
+ Returns:
156
+ - dict: Contains bounding box slices.
157
+ """
158
+ try:
159
+ binary_array = np.asarray(binary_image, dtype=bool)
160
+ slices = bounding_box(binary_array)
161
+ return {
162
+ "success": True,
163
+ "result": {
164
+ "slices": str(slices),
165
+ "bounds": [(s.start, s.stop) for s in slices]
166
+ },
167
+ "error": None
168
+ }
169
+ except Exception as e:
170
+ return {"success": False, "result": None, "error": str(e)}
171
+
172
+ @mcp.tool(name="largest_connected_component", description="Extract largest connected component from binary image.")
173
+ def largest_connected_component_tool(binary_image: list, connectivity: int = 1) -> dict:
174
+ """
175
+ Extracts the largest connected component from a binary image.
176
+
177
+ Parameters:
178
+ - binary_image: Binary image data.
179
+ - connectivity: Connectivity type (1 or 2, default: 1).
180
+
181
+ Returns:
182
+ - dict: Contains result image with only the largest component.
183
+ """
184
+ try:
185
+ binary_array = np.asarray(binary_image, dtype=bool)
186
+ result = largest_connected_component(binary_array, connectivity=connectivity)
187
+ return {
188
+ "success": True,
189
+ "result": result.tolist() if isinstance(result, np.ndarray) else result,
190
+ "error": None
191
+ }
192
+ except Exception as e:
193
+ return {"success": False, "result": None, "error": str(e)}
194
+
195
+ @mcp.tool(name="size_threshold", description="Remove small connected components below size threshold.")
196
+ def size_threshold_tool(binary_image: list, size_threshold: int = 100, connectivity: int = 1) -> dict:
197
+ """
198
+ Removes connected components smaller than the threshold.
199
+
200
+ Parameters:
201
+ - binary_image: Binary image data.
202
+ - size_threshold: Minimum size for components to keep (default: 100).
203
+ - connectivity: Connectivity type (1 or 2, default: 1).
204
+
205
+ Returns:
206
+ - dict: Contains filtered image.
207
+ """
208
+ try:
209
+ binary_array = np.asarray(binary_image, dtype=bool)
210
+ result = size_threshold(binary_array, size_threshold=size_threshold, connectivity=connectivity)
211
+ return {
212
+ "success": True,
213
+ "result": result.tolist() if isinstance(result, np.ndarray) else result,
214
+ "error": None
215
+ }
216
+ except Exception as e:
217
+ return {"success": False, "result": None, "error": str(e)}
218
+
219
+ @mcp.tool(name="relabel", description="Relabel connected components in a labeled image.")
220
+ def relabel_tool(labeled_image: list, with_background: bool = True) -> dict:
221
+ """
222
+ Relabels connected components with consecutive integers.
223
+
224
+ Parameters:
225
+ - labeled_image: Labeled image data.
226
+ - with_background: Whether to relabel background (default: True).
227
+
228
+ Returns:
229
+ - dict: Contains relabeled image and number of labels.
230
+ """
231
+ try:
232
+ labeled_array = np.asarray(labeled_image)
233
+ result, num_labels = relabel(labeled_array, with_background=with_background)
234
+ return {
235
+ "success": True,
236
+ "result": {
237
+ "image": result.tolist() if isinstance(result, np.ndarray) else result,
238
+ "num_labels": int(num_labels)
239
+ },
240
+ "error": None
241
+ }
242
+ except Exception as e:
243
+ return {"success": False, "result": None, "error": str(e)}
244
+
245
+ # ===== 度量工具 =====
246
+ @mcp.tool(name="dice_coefficient", description="Compute Dice coefficient between two binary images.")
247
+ def dice_coefficient_tool(result_image: list, reference_image: list) -> dict:
248
+ """
249
+ Computes the Dice coefficient (F1 score) between two binary images.
250
+
251
+ Parameters:
252
+ - result_image: Predicted/result binary image.
253
+ - reference_image: Ground truth reference image.
254
+
255
+ Returns:
256
+ - dict: Contains Dice coefficient value (0-1, higher is better).
257
+ """
258
+ try:
259
+ result_array = np.asarray(result_image, dtype=bool)
260
+ reference_array = np.asarray(reference_image, dtype=bool)
261
+ dice = dc(result_array, reference_array)
262
+ return {
263
+ "success": True,
264
+ "result": {"dice_coefficient": float(dice)},
265
+ "error": None
266
+ }
267
+ except Exception as e:
268
+ return {"success": False, "result": None, "error": str(e)}
269
+
270
+ @mcp.tool(name="hausdorff_distance", description="Compute Hausdorff distance between two binary images.")
271
+ def hausdorff_distance_tool(result_image: list, reference_image: list) -> dict:
272
+ """
273
+ Computes the Hausdorff distance between two binary images (distance measure).
274
+
275
+ Parameters:
276
+ - result_image: Predicted/result binary image.
277
+ - reference_image: Ground truth reference image.
278
+
279
+ Returns:
280
+ - dict: Contains Hausdorff distance and 95% Hausdorff distance.
281
+ """
282
+ try:
283
+ result_array = np.asarray(result_image, dtype=bool)
284
+ reference_array = np.asarray(reference_image, dtype=bool)
285
+ hd_dist = hd(result_array, reference_array)
286
+ hd95_dist = hd95(result_array, reference_array)
287
+ return {
288
+ "success": True,
289
+ "result": {
290
+ "hausdorff_distance": float(hd_dist),
291
+ "hausdorff_95": float(hd95_dist)
292
+ },
293
+ "error": None
294
+ }
295
+ except Exception as e:
296
+ return {"success": False, "result": None, "error": str(e)}
297
+
298
+ @mcp.tool(name="average_surface_distance", description="Compute average surface distance between two binary images.")
299
+ def average_surface_distance_tool(result_image: list, reference_image: list) -> dict:
300
+ """
301
+ Computes the average surface distance and symmetric average surface distance.
302
+
303
+ Parameters:
304
+ - result_image: Predicted/result binary image.
305
+ - reference_image: Ground truth reference image.
306
+
307
+ Returns:
308
+ - dict: Contains ASD and ASSD values.
309
+ """
310
+ try:
311
+ result_array = np.asarray(result_image, dtype=bool)
312
+ reference_array = np.asarray(reference_image, dtype=bool)
313
+ asd_dist = asd(result_array, reference_array)
314
+ assd_dist = assd(result_array, reference_array)
315
+ return {
316
+ "success": True,
317
+ "result": {
318
+ "average_surface_distance": float(asd_dist),
319
+ "symmetric_average_surface_distance": float(assd_dist)
320
+ },
321
+ "error": None
322
+ }
323
+ except Exception as e:
324
+ return {"success": False, "result": None, "error": str(e)}
325
+
326
+ @mcp.tool(name="sensitivity_specificity", description="Compute sensitivity and specificity metrics.")
327
+ def sensitivity_specificity_tool(result_image: list, reference_image: list) -> dict:
328
+ """
329
+ Computes sensitivity (recall) and specificity metrics.
330
+
331
+ Parameters:
332
+ - result_image: Predicted/result binary image.
333
+ - reference_image: Ground truth reference image.
334
+
335
+ Returns:
336
+ - dict: Contains sensitivity, specificity, and related metrics.
337
+ """
338
+ try:
339
+ result_array = np.asarray(result_image, dtype=bool)
340
+ reference_array = np.asarray(reference_image, dtype=bool)
341
+ sens = sensitivity(result_array, reference_array)
342
+ spec = specificity(result_array, reference_array)
343
+ prec = precision(result_array, reference_array)
344
+ recall_val = recall(result_array, reference_array)
345
+ ppv = positive_predictive_value(result_array, reference_array)
346
+
347
+ return {
348
+ "success": True,
349
+ "result": {
350
+ "sensitivity": float(sens),
351
+ "specificity": float(spec),
352
+ "precision": float(prec),
353
+ "recall": float(recall_val),
354
+ "positive_predictive_value": float(ppv)
355
+ },
356
+ "error": None
357
+ }
358
+ except Exception as e:
359
+ return {"success": False, "result": None, "error": str(e)}
360
+
361
+ # ===== 图像滤波工具 =====
362
+ @mcp.tool(name="otsu_threshold", description="Apply Otsu's method for automatic thresholding.")
363
+ def otsu_threshold_tool(image_data: list) -> dict:
364
+ """
365
+ Applies Otsu's method to find optimal threshold value.
366
+
367
+ Parameters:
368
+ - image_data: Input image data.
369
+
370
+ Returns:
371
+ - dict: Contains threshold value and binary result.
372
+ """
373
+ try:
374
+ image_array = np.asarray(image_data)
375
+ threshold = otsu(image_array)
376
+ binary_result = (image_array >= threshold).astype(int)
377
+ return {
378
+ "success": True,
379
+ "result": {
380
+ "threshold": float(threshold),
381
+ "binary_image": binary_result.tolist(),
382
+ "shape": list(binary_result.shape)
383
+ },
384
+ "error": None
385
+ }
386
+ except Exception as e:
387
+ return {"success": False, "result": None, "error": str(e)}
388
+
389
+ @mcp.tool(name="gaussian_gradient_magnitude", description="Compute Gaussian gradient magnitude of image.")
390
+ def gaussian_gradient_magnitude_tool(image_data: list, sigma: float = 1.0) -> dict:
391
+ """
392
+ Computes the Gaussian gradient magnitude of an image.
393
+
394
+ Parameters:
395
+ - image_data: Input image data.
396
+ - sigma: Standard deviation for Gaussian filter (default: 1.0).
397
+
398
+ Returns:
399
+ - dict: Contains gradient magnitude image.
400
+ """
401
+ try:
402
+ image_array = np.asarray(image_data, dtype=np.float32)
403
+ result = gaussian_gradient_magnitude(image_array, sigma=sigma)
404
+ return {
405
+ "success": True,
406
+ "result": result.tolist() if isinstance(result, np.ndarray) else result,
407
+ "error": None
408
+ }
409
+ except Exception as e:
410
+ return {"success": False, "result": None, "error": str(e)}
411
+
412
+ # ===== 特征提取工具 =====
413
+ @mcp.tool(name="local_histogram", description="Compute local histogram around each voxel.")
414
+ def local_histogram_tool(image_data: list, size: int = 3, bins: int = 32) -> dict:
415
+ """
416
+ Computes local histogram around each voxel.
417
+
418
+ Parameters:
419
+ - image_data: Input image data.
420
+ - size: Size of local region (default: 3).
421
+ - bins: Number of histogram bins (default: 32).
422
+
423
+ Returns:
424
+ - dict: Contains local histogram features.
425
+ """
426
+ try:
427
+ image_array = np.asarray(image_data, dtype=np.float32)
428
+ result = local_histogram(image_array, size=size, bins=bins)
429
+ return {
430
+ "success": True,
431
+ "result": {
432
+ "shape": list(result.shape) if hasattr(result, 'shape') else None,
433
+ "dtype": str(result.dtype) if hasattr(result, 'dtype') else None,
434
+ "summary": "Local histogram computed successfully"
435
+ },
436
+ "error": None
437
+ }
438
+ except Exception as e:
439
+ return {"success": False, "result": None, "error": str(e)}
440
+
441
+ @mcp.tool(name="median_intensity", description="Compute median intensity in image.")
442
+ def median_intensity_tool(image_data: list) -> dict:
443
+ """
444
+ Computes the median intensity value.
445
+
446
+ Parameters:
447
+ - image_data: Input image data.
448
+
449
+ Returns:
450
+ - dict: Contains median intensity value.
451
+ """
452
+ try:
453
+ image_array = np.asarray(image_data)
454
+ result = median(image_array)
455
+ return {
456
+ "success": True,
457
+ "result": {"median_intensity": float(result)},
458
+ "error": None
459
+ }
460
+ except Exception as e:
461
+ return {"success": False, "result": None, "error": str(e)}
462
+
463
+ @mcp.tool(name="compute_fuzzy_histogram", description="Compute a fuzzy histogram from image data.")
464
+ def compute_fuzzy_histogram(image_data: list, bins: int = 10, membership_function: str = "triangular",
465
+ smoothness: float = None, normed: bool = False) -> dict:
466
+ """
467
+ Computes a fuzzy histogram from image data with complete parameter control.
468
+
469
+ Parameters:
470
+ - image_data: List of image data.
471
+ - bins: Number of equal-width bins (default: 10).
472
+ - membership_function: Type of membership function ('triangular', 'trapezoid', 'gaussian', 'sigmoid').
473
+ - smoothness: The smoothness parameter for the histogram.
474
+ - normed: If True, normalize the result as probability density function.
475
+
476
+ Returns:
477
+ - dict: Contains success status, histogram values, and bin edges.
478
+ """
479
+ try:
480
+ image_array = np.asarray(image_data)
481
+ hist, bin_edges = fuzzy_histogram(image_array, bins=bins, membership=membership_function,
482
+ smoothness=smoothness, normed=normed)
483
+ return {
484
+ "success": True,
485
+ "result": {
486
+ "histogram": hist.tolist() if isinstance(hist, np.ndarray) else hist,
487
+ "bin_edges": bin_edges.tolist() if isinstance(bin_edges, np.ndarray) else bin_edges,
488
+ "bins": bins,
489
+ "membership_function": membership_function
490
+ },
491
+ "error": None
492
+ }
493
+ except Exception as e:
494
+ return {"success": False, "result": None, "error": str(e)}
495
+
496
+ @mcp.tool(name="normalize_features", description="Normalize feature vectors.")
497
+ def normalize_features(features: list) -> dict:
498
+ """
499
+ Normalizes feature vectors using L2 normalization.
500
+
501
+ Parameters:
502
+ - features: List of feature vectors.
503
+
504
+ Returns:
505
+ - dict: Contains success status and normalized features.
506
+ """
507
+ try:
508
+ features_array = np.asarray(features)
509
+ result = normalize(features_array)
510
+ return {
511
+ "success": True,
512
+ "result": result.tolist() if isinstance(result, np.ndarray) else result,
513
+ "error": None
514
+ }
515
+ except Exception as e:
516
+ return {"success": False, "result": None, "error": str(e)}
517
+
518
+ @mcp.tool(name="apply_anisotropic_diffusion", description="Apply anisotropic diffusion to an image.")
519
+ def apply_anisotropic_diffusion(image_data: list, niter: int = 1, kappa: float = 50,
520
+ gamma: float = 0.1, voxelspacing: list = None, option: int = 1) -> dict:
521
+ """
522
+ Applies anisotropic diffusion to an image for edge-preserving smoothing.
523
+
524
+ Parameters:
525
+ - image_data: List of image data.
526
+ - niter: Number of iterations (default: 1).
527
+ - kappa: Conduction coefficient, 20-100 recommended (default: 50).
528
+ - gamma: Max value should be ≤ 0.25 for stability (default: 0.1).
529
+ - voxelspacing: Voxel spacing (optional).
530
+ - option: Diffusion equation option (default: 1).
531
+
532
+ Returns:
533
+ - dict: Contains success status and smoothed image data.
534
+ """
535
+ try:
536
+ if gamma > 0.25:
537
+ return {"success": False, "result": None, "error": "gamma must be ≤ 0.25 for stability"}
538
+ if niter <= 0:
539
+ return {"success": False, "result": None, "error": "niter must be positive"}
540
+
541
+ image_array = np.asarray(image_data, dtype=np.float32)
542
+ voxelspacing_array = np.asarray(voxelspacing) if voxelspacing else None
543
+
544
+ result = anisotropic_diffusion(image_array, niter=niter, kappa=kappa,
545
+ gamma=gamma, voxelspacing=voxelspacing_array, option=option)
546
+ return {
547
+ "success": True,
548
+ "result": result.tolist() if isinstance(result, np.ndarray) else result,
549
+ "error": None
550
+ }
551
+ except Exception as e:
552
+ return {"success": False, "result": None, "error": str(e)}
553
+
554
+ @mcp.tool(name="segment_with_graphcut", description="Perform graphcut segmentation on an image.")
555
+ def segment_with_graphcut(image_data: list, fg_markers: list, bg_markers: list,
556
+ boundary_term_type: str = "difference_of_means",
557
+ boundary_term_args: list = None) -> dict:
558
+ """
559
+ Performs graphcut segmentation on an image with specified boundary term.
560
+
561
+ Parameters:
562
+ - image_data: List of image data.
563
+ - fg_markers: Foreground markers.
564
+ - bg_markers: Background markers.
565
+ - boundary_term_type: Type of boundary term ('difference_of_means', 'stawiaski', 'division', etc).
566
+ - boundary_term_args: Arguments for the boundary term function.
567
+
568
+ Returns:
569
+ - dict: Contains success status and segmented image data.
570
+ """
571
+ try:
572
+ image_array = np.asarray(image_data)
573
+ fg_markers_array = np.asarray(fg_markers, dtype=bool)
574
+ bg_markers_array = np.asarray(bg_markers, dtype=bool)
575
+ boundary_term_args = tuple(boundary_term_args) if boundary_term_args else ()
576
+
577
+ # Map boundary term names to functions
578
+ boundary_functions = {
579
+ "difference_of_means": boundary_difference_of_means,
580
+ "stawiaski": boundary_stawiaski,
581
+ "stawiaski_directed": boundary_stawiaski_directed,
582
+ "division": boundary_difference_division,
583
+ "exponential": boundary_difference_exponential,
584
+ "linear": boundary_difference_linear,
585
+ "power": boundary_difference_power,
586
+ "maximum_division": boundary_maximum_division,
587
+ "maximum_exponential": boundary_maximum_exponential,
588
+ "maximum_linear": boundary_maximum_linear,
589
+ "maximum_power": boundary_maximum_power,
590
+ }
591
+
592
+ if boundary_term_type not in boundary_functions:
593
+ return {"success": False, "result": None,
594
+ "error": f"Unknown boundary_term_type: {boundary_term_type}"}
595
+
596
+ boundary_func = boundary_functions[boundary_term_type]
597
+ gcgraph = graph_from_voxels(fg_markers_array, bg_markers_array, boundary_func, boundary_term_args)
598
+ maxflow = gcgraph.maxflow()
599
+ result = gcgraph.get_segmented_image()
600
+
601
+ return {
602
+ "success": True,
603
+ "result": result.tolist() if isinstance(result, np.ndarray) else result,
604
+ "maxflow": float(maxflow),
605
+ "error": None
606
+ }
607
+ except Exception as e:
608
+ return {"success": False, "result": None, "error": str(e)}
609
+
610
+ def create_app() -> FastMCP:
611
+ """
612
+ Creates and returns the FastMCP application instance.
613
+
614
+ Returns:
615
+ - FastMCP: The FastMCP application instance.
616
+ """
617
+ return mcp
medpy/mcp_output/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ fastmcp>=0.1.0
2
+ pydantic>=2.0.0
3
+ numpy
4
+ scipy
5
+ matplotlib
6
+
7
+ # Optional Dependencies
8
+ # pydicom
medpy/mcp_output/simple_revise_error_analysis.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "status": "FAIL",
3
+ "next_action": "fix_directly",
4
+ "confidence": 0.9,
5
+ "summary": "The error is due to a missing 'numpy' module, which is required by the script. This can be fixed directly by ensuring that the 'numpy' package is installed in the conda environment being used. The error message indicates that the script is being run using 'conda run', so the appropriate fix is to activate the conda environment and install 'numpy' using the command 'conda install numpy'."
6
+ }
medpy/mcp_output/start_mcp.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Service Startup Entry
3
+ """
4
+ import sys
5
+ import os
6
+
7
+ project_root = os.path.dirname(os.path.abspath(__file__))
8
+ mcp_plugin_dir = os.path.join(project_root, "mcp_plugin")
9
+ if mcp_plugin_dir not in sys.path:
10
+ sys.path.insert(0, mcp_plugin_dir)
11
+
12
+ # Set path to source directory
13
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
14
+ sys.path.insert(0, source_path)
15
+
16
+ from mcp_service import create_app
17
+
18
+ def main():
19
+ """Start FastMCP service"""
20
+ app = create_app()
21
+ # Use environment variable to configure port, default 8000
22
+ port = int(os.environ.get("MCP_PORT", "8000"))
23
+
24
+ # Choose transport mode based on environment variable
25
+ transport = os.environ.get("MCP_TRANSPORT", "stdio")
26
+ if transport == "http":
27
+ app.run(transport="http", host="0.0.0.0", port=port)
28
+ else:
29
+ # Default to STDIO mode
30
+ app.run()
31
+
32
+ if __name__ == "__main__":
33
+ main()
medpy/mcp_output/tests_mcp/test_mcp_basic.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Service Basic Test
3
+ """
4
+ import sys
5
+ import os
6
+
7
+ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
8
+ mcp_plugin_dir = os.path.join(project_root, "mcp_plugin")
9
+ if mcp_plugin_dir not in sys.path:
10
+ sys.path.insert(0, mcp_plugin_dir)
11
+
12
+ source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "source")
13
+ sys.path.insert(0, source_path)
14
+
15
+ def test_import_mcp_service():
16
+ """Test if MCP service can be imported normally"""
17
+ try:
18
+ from mcp_service import create_app
19
+ app = create_app()
20
+ assert app is not None
21
+ print("MCP service imported successfully")
22
+ return True
23
+ except Exception as e:
24
+ print("MCP service import failed: " + str(e))
25
+ return False
26
+
27
+ def test_adapter_init():
28
+ """Test if adapter can be initialized normally"""
29
+ try:
30
+ from adapter import Adapter
31
+ adapter = Adapter()
32
+ assert adapter is not None
33
+ print("Adapter initialized successfully")
34
+ return True
35
+ except Exception as e:
36
+ print("Adapter initialization failed: " + str(e))
37
+ return False
38
+
39
+ if __name__ == "__main__":
40
+ print("Running MCP service basic test...")
41
+ test1 = test_import_mcp_service()
42
+ test2 = test_adapter_init()
43
+
44
+ if test1 and test2:
45
+ print("All basic tests passed")
46
+ sys.exit(0)
47
+ else:
48
+ print("Some tests failed")
49
+ sys.exit(1)
medpy/mcp_output/tests_smoke/test_smoke.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib, sys
2
+ import os
3
+
4
+ # Add current directory to Python path
5
+ sys.path.insert(0, os.getcwd())
6
+
7
+ source_dir = os.path.join(os.getcwd(), "source")
8
+ if os.path.exists(source_dir):
9
+ sys.path.insert(0, source_dir)
10
+
11
+
12
+ try:
13
+ importlib.import_module("medpy")
14
+ print("OK - Successfully imported medpy")
15
+ except ImportError as e:
16
+ print(f"Failed to import medpy: {e}")
17
+ fallback_packages = []
18
+
19
+ fallback_packages = ['medpy']
20
+
21
+ for pkg in fallback_packages:
22
+ try:
23
+ importlib.import_module(pkg)
24
+ print(f"OK - Successfully imported {pkg}")
25
+ break
26
+ except ImportError:
27
+ continue
28
+ else:
29
+ print("All import attempts failed")
medpy/source/.github/workflows/README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MedPy's CI/CD workflows
2
+
3
+ ## Build & release
4
+ Upon creating a release or a pre-release on GitHub, the package is *build* and *published* to [test.pypi.org](https://test.pypi.org).
5
+
6
+ Install from test PyPi with `python -m pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple medpy==x.y.z.`. This ensures that the dependencies are installed from the proper PyPI.
7
+
8
+ After making sure that the package published there is installable and passes all tests, the final *publish* to [pypi.org](https://pypi.org) can be triggered manually from the GitHub UI.
9
+
10
+ Note that publishing only works for releases created directly from the `master` branch. Releasees published from other branches should always be pre-releases and never published to [pypi.org](https://pypi.org), but only [test.pypi.org](https://test.pypi.org).
11
+
12
+ ## pre-commit.yml
13
+ Makes sure that all PRs and all releases adhere to the pre-commit rules.
14
+
15
+ ## run-test*.yml
16
+ Makes sure that all PRs and all releases pass the tests.
medpy/source/.github/workflows/build-publish-test.yml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build package & publish a release to PyPI (test)
2
+ # Given a tag, downloads the associated code, builds the package, and uploads the source tarball as artifact
3
+ # This version releases to https://test.pypi.org/ for testing purposes
4
+ # Triggers on: all published releases (incl pre-releases)
5
+
6
+ name: Build package & release to PyPI (test)
7
+
8
+ on:
9
+ release:
10
+ types: [published]
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ build:
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ - name: Set up Python
21
+ uses: actions/setup-python@v5
22
+ with:
23
+ python-version: 3.x
24
+ - name: Install dependencies
25
+ run: |
26
+ python -m pip install --upgrade pip
27
+ pip install build
28
+ - name: Build a source tarball
29
+ run: python -m build --sdist
30
+ - name: Store the distribution packages
31
+ uses: actions/upload-artifact@v4.3.0
32
+ with:
33
+ name: python-package-distributions-${{ github.ref_name }}
34
+ path: dist/
35
+
36
+ publish-test:
37
+ needs:
38
+ - build
39
+ runs-on: ubuntu-latest
40
+ environment:
41
+ name: pypi-publish-test
42
+ url: https://test.pypi.org/p/medpy
43
+ permissions:
44
+ id-token: write # IMPORTANT: mandatory for trusted publishing
45
+ steps:
46
+ - name: Download dists
47
+ uses: actions/download-artifact@v4.1.1 # make sure that same major version as actions/upload-artifact
48
+ with:
49
+ name: python-package-distributions-${{ github.ref_name }}
50
+ path: dist/
51
+ - name: Publish package
52
+ uses: pypa/gh-action-pypi-publish@v1.8.11
53
+ with:
54
+ repository-url: https://test.pypi.org/legacy/ # test publish platform
medpy/source/.github/workflows/pre-commit.yml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Runs the pre-commit hooks to make sure that all changes are properly formatted and such
2
+ # Triggers on: All PRs that are mergable, but not for draft PRs
3
+ # Triggers on: all published releases (incl draft releases)
4
+
5
+ name: Pre-commit hooks
6
+
7
+ on:
8
+ pull_request:
9
+ types: [opened, synchronize, reopened, ready_for_review]
10
+ release:
11
+ types: [published]
12
+
13
+ permissions:
14
+ contents: read
15
+
16
+ jobs:
17
+ pre-commit:
18
+ if: github.event.pull_request.draft == false
19
+
20
+ runs-on: ubuntu-latest
21
+
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+ - name: Set up Python
25
+ uses: actions/setup-python@v5
26
+ with:
27
+ python-version: 3.x
28
+ - uses: pre-commit/action@v3.0.0
29
+ - uses: pre-commit-ci/lite-action@v1.0.1
30
+ if: always()
medpy/source/.github/workflows/publish.yml ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Publish a release to PyPI
2
+ # Requires build package workflow to run first
3
+ # This version releases to https://pypi.org/, only trigger if the release has been thorough tested
4
+
5
+ name: Build package & release to PyPI
6
+
7
+ on:
8
+ workflow_dispatch:
9
+ inputs:
10
+ tag:
11
+ description: "Select release to publish"
12
+ required: true
13
+
14
+ permissions:
15
+ contents: read
16
+
17
+ jobs:
18
+ build:
19
+ runs-on: ubuntu-latest
20
+ steps:
21
+ - uses: actions/checkout@v4
22
+ with:
23
+ ref: ${{ inputs.tag }}
24
+ - name: Set up Python
25
+ uses: actions/setup-python@v5
26
+ with:
27
+ python-version: 3.x
28
+ - name: Install dependencies
29
+ run: |
30
+ python -m pip install --upgrade pip
31
+ pip install build
32
+ - name: Build a source tarball
33
+ run: python -m build --sdist
34
+ - name: Store the distribution packages
35
+ uses: actions/upload-artifact@v4.3.0
36
+ with:
37
+ name: python-package-distributions-${{ inputs.tag }}
38
+ path: dist/
39
+
40
+ publish:
41
+ needs:
42
+ - build
43
+ runs-on: ubuntu-latest
44
+ environment:
45
+ name: pypi-publish
46
+ url: https://pypi.org/p/medpy
47
+ permissions:
48
+ id-token: write # IMPORTANT: mandatory for trusted publishing
49
+ steps:
50
+ - name: Download dists
51
+ uses: actions/download-artifact@v4.1.1 # make sure that same major version as actions/upload-artifact
52
+ with:
53
+ name: python-package-distributions-${{ inputs.tag }}
54
+ path: dist/
55
+ - name: Publish package
56
+ uses: pypa/gh-action-pypi-publish@v1.8.11
medpy/source/.github/workflows/run-tests-gc.yml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install the package and run the graph-cut tests
2
+ # This test is kept separate, as the graphcut functionality is optional and unstable
3
+ # Triggers on: All PRs that are mergable, but not for draft PRs
4
+ # Triggers on: all published releases (incl pre-releases)
5
+
6
+ # Note: the dependency libboost_python will always be installed against the OS's main python version,
7
+ # independent of the python version set-up. They are 22.04 = 3.10 and 20.04 = 3.8.
8
+
9
+ name: Run tests (graphcut only)
10
+
11
+ on:
12
+ pull_request:
13
+ types: [opened, synchronize, reopened, ready_for_review]
14
+ release:
15
+ types: [published]
16
+
17
+ permissions:
18
+ contents: read
19
+
20
+ jobs:
21
+ run-tests-gc-ubuntu-22_04:
22
+ if: github.event.pull_request.draft == false
23
+ runs-on: ubuntu-22.04
24
+ steps:
25
+ - uses: actions/checkout@v4
26
+ - name: Set up Python 3.10
27
+ uses: actions/setup-python@v5
28
+ with:
29
+ python-version: "3.10"
30
+ - name: Install system dependencies for graphcut functionality
31
+ run: sudo apt-get install -y libboost-python-dev build-essential
32
+ - name: Install with test dependencies
33
+ run: |
34
+ python -m pip install --upgrade pip
35
+ python -m pip install -v .[test]
36
+ - name: Test with pytest (graphcut test only)
37
+ run: cd tests && pytest graphcut_/*
38
+
39
+ run-tests-gc-test-ubuntu-20_04:
40
+ if: github.event.pull_request.draft == false
41
+ runs-on: ubuntu-20.04
42
+ steps:
43
+ - uses: actions/checkout@v4
44
+ - name: Set up Python 3.8
45
+ uses: actions/setup-python@v5
46
+ with:
47
+ python-version: "3.8"
48
+ - name: Install system dependencies for graphcut functionality
49
+ run: sudo apt-get install -y libboost-python-dev build-essential
50
+ - name: Install with test dependencies
51
+ run: |
52
+ python -m pip install --upgrade pip
53
+ python -m pip install -v .[test]
54
+ - name: Test with pytest (graphcut test only)
55
+ run: cd tests && pytest graphcut_/*
medpy/source/.github/workflows/run-tests.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install the package and run all tests except the graph-cut ones
2
+ # Triggers on: All PRs that are mergable, but not for draft PRs
3
+ # Triggers on: all published releases (incl pre-releases)
4
+
5
+ name: Run tests (wo graphcut)
6
+
7
+ on:
8
+ pull_request:
9
+ types: [opened, synchronize, reopened, ready_for_review]
10
+ release:
11
+ types: [published]
12
+
13
+ permissions:
14
+ contents: read
15
+
16
+ jobs:
17
+ run-tests:
18
+ if: github.event.pull_request.draft == false
19
+
20
+ strategy:
21
+ fail-fast: false
22
+ matrix:
23
+ python-version: ["3.8", "3.9", "3.10", "3.11"]
24
+ os: [ubuntu-latest, macos-latest]
25
+
26
+ runs-on: ${{ matrix.os }}
27
+
28
+ steps:
29
+ - uses: actions/checkout@v4
30
+ - name: Set up Python ${{ matrix.python-version }}
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: ${{ matrix.python-version }}
34
+ - name: Install with test dependencies
35
+ run: |
36
+ python -m pip install --upgrade pip
37
+ python -m pip install .[test]
38
+ - name: Test with pytest
39
+ run: |
40
+ pytest tests/features_/*
41
+ pytest tests/filter_/*
42
+ pytest tests/io_/*
43
+ pytest tests/metric_/*
medpy/source/.gitignore ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TODO.txt
2
+
3
+
4
+ # Images
5
+ *.nii
6
+ *.mhd
7
+ *.raw
8
+
9
+ # Local virtual envs
10
+ .venv/
11
+
12
+ # DOC dirs
13
+ doc/build/
14
+ doc/generated/
15
+ doc/source/generated/
16
+
17
+ # Notebooks dirs
18
+ .ipynb_checkpoints
19
+
20
+ # BUILD dirs
21
+ build/
22
+ dist/
23
+ MedPy.egg-info/
24
+
25
+ # Only locally used, temporary .py scripts.
26
+ _*.py
27
+ !__init__.py
28
+
29
+ # Backup files
30
+ *.bak
31
+
32
+ # Compiled source
33
+ *.com
34
+ *.class
35
+ *.dll
36
+ *.exe
37
+ *.o
38
+ *.so
39
+ *.pyc
40
+ *.pyo
41
+
42
+ # Packages
43
+ # it's better to unpack these files and commit the raw source
44
+ # git has its own built in compression methods
45
+ *.7z
46
+ *.dmg
47
+ *.gz
48
+ *.iso
49
+ *.jar
50
+ *.rar
51
+ *.tar
52
+ *.zip
53
+
54
+ # Logs and databases
55
+ *.log
56
+ *.sql
57
+ *.sqlite
58
+
59
+ # OS generated files
60
+ .DS_Store*
61
+ ehthumbs.db
62
+ Icon?
63
+ Thumbs.db
64
+ *~
65
+
66
+ # Eclipse and PyDev project files
67
+ .project
68
+ .pydevproject
69
+ .settings/
70
+ .metadata/
71
+
72
+ # Suggestions by GitHub for Python projects
73
+ # Packages
74
+ *.egg
75
+ *.egg-info
76
+ dist
77
+ build
78
+ eggs
79
+ parts
80
+ var
81
+ sdist
82
+ develop-eggs
83
+ .installed.cfg
84
+
85
+ # Installer logs
86
+ pip-log.txt
87
+
88
+ # Unit test / coverage reports
89
+ .coverage
90
+ .tox
91
+ .hypothesis
92
+
93
+ #Translations
94
+ *.mo
95
+
96
+ #Mr Developer
97
+ .mr.developer.cfg
medpy/source/.pre-commit-config.yaml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ default_stages: [commit]
2
+ repos:
3
+ - repo: https://github.com/pre-commit/pre-commit-hooks
4
+ rev: v4.5.0
5
+ hooks:
6
+ - id: check-added-large-files
7
+ - id: check-merge-conflict
8
+ - id: check-yaml
9
+ - id: end-of-file-fixer
10
+ - id: trailing-whitespace
11
+ - id: debug-statements
12
+
13
+ - repo: https://github.com/pycqa/isort
14
+ rev: "5.13.2"
15
+ hooks:
16
+ - id: isort
17
+ args: ["--profile", "black", "--line-length=88"]
18
+
19
+ - repo: https://github.com/psf/black
20
+ rev: 23.12.0
21
+ hooks:
22
+ - id: black
23
+ args: ["--line-length=88"]
24
+
25
+ - repo: https://github.com/hadialqattan/pycln
26
+ rev: "v2.4.0"
27
+ hooks:
28
+ - id: pycln
29
+ args: ["--all"]
30
+
31
+ - repo: https://github.com/Yelp/detect-secrets
32
+ rev: v1.4.0
33
+ hooks:
34
+ - id: detect-secrets
35
+ args: ["--exclude-files", ".*\\.ipynb"]
medpy/source/CHANGES.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ v0.5.2, 2024-07-23 -- Hotfixes
2
+ v0.5.1, 2024-04-03 -- Hotfixes
3
+ v0.5.0, 2024-04-03 -- Addressed all depreciation warnings and incompatabilities
4
+ Updated documentation
5
+ Updated and fixed tests
6
+ Added github workflows as system
7
+ Introduced formatting rules and pre-commit to enforce them
8
+ Removed dockerfile creation files
9
+ v0.4.0, 2018-02-XX -- Switched to Python 3: finally compatible with modern development environements
10
+ Switched to simple itk for image loading/saving: read dicom series, more formats, less dependencies, cleaner code, easier to maintain
11
+ Documentation: installation instructions for Windows and OsX
12
+ Others: improved filters, cleanup, bugfixes
13
+ v0.3.0, 2017-09-20 -- Extensive cleanup, many new functionalities, updated documentation, notebook tutorials, Python 3 branch
14
+ v0.2.2, 2014-09-18 -- Changes the documentation engine to Sphinx and fixed a number of bugs
15
+ v0.2.1, 2014-08-19 -- ez_setup.py has not been include
16
+ v0.2.0, 2014-08-19 -- Little clean-up, many new functionalities; in generally simpler structure and usage; complilation of C++ module not required anymore
17
+ v0.1.0, 2013-04-15 -- Initial release.
medpy/source/LICENSE.txt ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <http://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
medpy/source/MANIFEST.in ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ include *.txt
2
+ include *.md
3
+
4
+ include lib/maxflow/src/*.h
5
+ include lib/maxflow/src/*.cpp
6
+ include lib/maxflow/src/instances.inc
7
+ include lib/maxflow/src/README
medpy/source/README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [![PyPI version](https://badge.fury.io/py/MedPy.svg)](https://pypi.python.org/pypi/MedPy/)
2
+ [![anaconda version](https://anaconda.org/conda-forge/medpy/badges/version.svg)](https://anaconda.org/conda-forge/medpy)
3
+ [![PyPI pyversions](https://img.shields.io/pypi/pyversions/MedPy.svg)](https://pypi.python.org/pypi/MedPy/)
4
+ [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
5
+ [![Downloads](https://pepy.tech/badge/medpy/month)](https://pepy.tech/project/medpy)
6
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.2565940.svg)](https://doi.org/10.5281/zenodo.2565940)
7
+
8
+
9
+ [GitHub](https://github.com/loli/medpy/) | [Documentation](http://loli.github.io/medpy/) | [Tutorials](http://loli.github.io/medpy/) | [Issue tracker](https://github.com/loli/medpy/issues)
10
+
11
+ # medpy - Medical Image Processing in Python
12
+
13
+ MedPy is an image processing library and collection of scripts targeted towards medical (i.e. high dimensional) image processing.
14
+
15
+ ## Stable releases
16
+
17
+ - Download (stable release): https://pypi.python.org/pypi/medpy
18
+ - HTML documentation and installation instruction (stable release): http://loli.github.io/medpy/
19
+ - Download from [Conda-Forge](https://conda-forge.org): https://anaconda.org/conda-forge/medpy
20
+
21
+ ## Development version
22
+
23
+ - Download (development version): https://github.com/loli/medpy
24
+ - HTML documentation and installation instruction (development version): create this from doc/ folder following instructions in contained README file
25
+
26
+ ## Contribute
27
+
28
+ - Clone `master` branch from [github](https://github.com/loli/medpy)
29
+ - Install [pre-commit](https://pre-commit.com/) hooks or with `[dev,test]` extras
30
+ - Submit your change as a PR request
31
+
32
+ ## Python 2 version
33
+
34
+ Python 2 is no longer supported. But you can still use the older releases `<=0.3.0`.
35
+
36
+ ## Other links
37
+
38
+ - Issue tracker: https://github.com/loli/medpy/issues
medpy/source/README_PYPI.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MedPy
2
+
3
+ [GitHub](https://github.com/loli/medpy/) | [Documentation](http://loli.github.io/medpy/) | [Tutorials](http://loli.github.io/medpy/) | [Issue tracker](https://github.com/loli/medpy/issues)
4
+
5
+ **MedPy** is a library and script collection for medical image processing in Python, providing basic functionalities for **reading**, **writing** and **manipulating** large images of **arbitrary dimensionality**.
6
+ Its main contributions are n-dimensional versions of popular **image filters**, a collection of **image feature extractors**, ready to be used with [scikit-learn](http://scikit-learn.org), and an exhaustive n-dimensional **graph-cut** package.
7
+
8
+ * [Installation](#installation)
9
+ * [Getting started with the library](#getting-started-with-the-library)
10
+ * [Getting started with the scripts](#getting-started-with-the-scripts)
11
+ * [Support of medical image formats](#support-of-medical-image-formats)
12
+ * [Requirements](#requirements)
13
+ * [License](#license)
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ sudo apt-get install libboost-python-dev build-essential
19
+ pip3 install medpy
20
+ ```
21
+
22
+ **MedPy** requires **Python 3** and officially supports Ubuntu as well as other Debian derivatives.
23
+ For installation instructions on other operating systems see the [documentation](http://loli.github.io/medpy/).
24
+ While the library itself is written purely in Python, the **graph-cut** extension comes in C++ and has [it's own requirements](http://loli.github.io/medpy/installation/graphcutsupport.html).
25
+
26
+ ## Getting started with the library
27
+
28
+ If you already have a medical image at hand in [one of the supported formats](http://loli.github.io/medpy/information/imageformats.html), you can use it for this introduction. If not, navigate to http://www.nitrc.org/projects/inia19, click on the *Download Now* button, unpack and look for the *inia19-t1.nii* file. Open it in your favorite medical image viewer (I personally fancy [itksnap](http://www.itksnap.org)) and beware: the INIA19 primate brain atlas.
29
+
30
+ Load the image
31
+
32
+ ```python
33
+ from medpy.io import load
34
+ image_data, image_header = load('/path/to/image.xxx')
35
+ ```
36
+
37
+ The data is stored in a numpy ndarray, the header is an object containing additional metadata, such as the voxel-spacing. Now lets take a look at some of the image metadata
38
+
39
+ ```python
40
+ image_data.shape
41
+ ```
42
+
43
+ `(168, 206, 128)`
44
+
45
+ ```python
46
+ image_data.dtype
47
+ ```
48
+
49
+ `dtype(float32)`
50
+
51
+ And the header gives us
52
+
53
+ ```python
54
+ image_header.get_voxel_spacing()
55
+ ```
56
+
57
+ `(0.5, 0.5, 0.5)`
58
+
59
+ ```python
60
+ image_header.get_offset()
61
+ ```
62
+
63
+ `(0.0, 0.0, 0.0)`
64
+
65
+ Now lets apply one of the **MedPy** filter, more exactly the [Otsu thresholding](https://en.wikipedia.org/wiki/Otsu%27s_method), which can be used for automatic background removal
66
+
67
+ ```python
68
+ from medpy.filter import otsu
69
+ threshold = otsu(image_data)
70
+ output_data = image_data > threshold
71
+ ```
72
+
73
+ And save the binary image, marking the foreground
74
+
75
+ ```python
76
+ from medpy.io import save
77
+ save(output_data, '/path/to/otsu.xxx', image_header)
78
+ ```
79
+
80
+ After taking a look at it, you might want to dive deeper with the tutorials found in the [documentation](http://loli.github.io/medpy/information/commandline_tools_listing.html).
81
+
82
+ ## Getting started with the scripts
83
+
84
+ **MedPy** comes with a range of read-to-use commandline scripts, which are all prefixed by `medpy_`.
85
+ To try these examples, first get an image as described in the previous section. Now call
86
+
87
+ ```bash
88
+ medpy_info.py /path/to/image.xxx
89
+ ```
90
+
91
+ will give you some details about the image. With
92
+
93
+ ```bash
94
+ medpy_diff.py /path/to/image1.xxx /path/to/image2.xxx
95
+ ```
96
+
97
+ you can compare two image. And
98
+
99
+ ```bash
100
+ medpy_anisotropic_diffusion.py /path/to/image.xxx /path/to/output.xxx
101
+ ```
102
+
103
+ lets you apply an edge preserving anisotropic diffusion filter. For a list of all scripts, see the [documentation](http://loli.github.io/medpy/).
104
+
105
+ ## Support of medical image formats
106
+
107
+ MedPy relies on SimpleITK, which enables the power of ITK for image loading and saving.
108
+ The supported image file formats should include at least the following. Note that not all might be supported by your machine.
109
+
110
+ **Medical formats:**
111
+
112
+ * ITK MetaImage (.mha/.raw, .mhd)
113
+ * Neuroimaging Informatics Technology Initiative (NIfTI) (.nia, .nii, .nii.gz, .hdr, .img, .img.gz)
114
+ * Analyze (plain, SPM99, SPM2) (.hdr/.img, .img.gz)
115
+ * Digital Imaging and Communications in Medicine (DICOM) (.dcm, .dicom)
116
+ * Digital Imaging and Communications in Medicine (DICOM) series (<directory>/)
117
+ * Nearly Raw Raster Data (Nrrd) (.nrrd, .nhdr)
118
+ * Medical Imaging NetCDF (MINC) (.mnc, .MNC)
119
+ * Guys Image Processing Lab (GIPL) (.gipl, .gipl.gz)
120
+
121
+ **Microscopy formats:**
122
+
123
+ * Medical Research Council (MRC) (.mrc, .rec)
124
+ * Bio-Rad (.pic, .PIC)
125
+ * LSM (Zeiss) microscopy images (.tif, .TIF, .tiff, .TIFF, .lsm, .LSM)
126
+ * Stimulate / Signal Data (SDT) (.sdt)
127
+
128
+ **Visualization formats:**
129
+
130
+ * VTK images (.vtk)
131
+
132
+ **Other formats:**
133
+
134
+ * Portable Network Graphics (PNG) (.png, .PNG)
135
+ * Joint Photographic Experts Group (JPEG) (.jpg, .JPG, .jpeg, .JPEG)
136
+ * Tagged Image File Format (TIFF) (.tif, .TIF, .tiff, .TIFF)
137
+ * Windows bitmap (.bmp, .BMP)
138
+ * Hierarchical Data Format (HDF5) (.h5 , .hdf5 , .he5)
139
+ * MSX-DOS Screen-x (.ge4, .ge5)
140
+
141
+ ## Requirements
142
+
143
+ MedPy comes with a number of dependencies and optional functionality that can require you to install additional packages.
144
+
145
+ ### Main dependencies
146
+
147
+ * [scipy](http://www.scipy.org)
148
+ * [numpy](http://www.numpy.org)
149
+ * [SimpleITK](https://simpleitk.readthedocs.io)
150
+
151
+ ### Optional functionalities
152
+
153
+ * compilation with `max-flow/min-cut` (enables the GraphCut functionalities)
154
+
155
+ ## License
156
+
157
+ MedPy is distributed under the GNU General Public License, a version of which can be found in the LICENSE.txt file.
medpy/source/RELEASE.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Steps for a new release
2
+
3
+ ## Preparations
4
+ - Create a branch `Release_x.y.z` to work towards the release
5
+ - Bump up the library version
6
+ - `setup.py`
7
+ - `medpy/__init__.py`
8
+ - `doc/source/conf.py`
9
+ - Run tests and make sure that all work
10
+ - Run notebooks and make sure that all work
11
+ - Check documentation and make sure that up to date
12
+ - Update `CHANGES.txt`, highlighting only major changes
13
+ - Test releases by publishing a pre-release, using the workflow detailed under [.github/workflows](.github/workflows)
14
+ - Re-create documentation and upload to gihub pages to test, then revert to previous version
15
+
16
+
17
+ ## Release
18
+ - Open PR to master, review, and merge
19
+ - Create a pre-release from master and test
20
+ - Create final release from master and test
21
+ - You might need to delete test package with same version number ion from test.pypi.org
22
+ - Trigger publish to PyPi workflow (see under [.github/workflows](.github/workflows))
23
+ - Update conda-force recipe to new version (PR)
24
+ - Update DOI
25
+
26
+ ## Further readings
27
+ - https://packaging.python.org/
28
+ - https://docs.github.com/en/actions
medpy/source/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ medpy Project Package Initialization File
4
+ """
medpy/source/bin/medpy_anisotropic_diffusion.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Executes gradient anisotropic diffusion filter over an image.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ # build-in modules
23
+ import argparse
24
+ import logging
25
+ import os
26
+
27
+ from medpy.core import Logger
28
+ from medpy.filter.smoothing import anisotropic_diffusion
29
+
30
+ # own modules
31
+ from medpy.io import get_pixel_spacing, load, save
32
+
33
+ # third-party modules
34
+
35
+ # path changes
36
+
37
+
38
+ # information
39
+ __author__ = "Oskar Maier"
40
+ __version__ = "r0.1.0, 2013-08-24"
41
+ __email__ = "oskar.maier@googlemail.com"
42
+ __status__ = "Release"
43
+ __description__ = """
44
+ Executes gradient anisotropic diffusion filter over an image.
45
+ This smoothing algorithm is edges preserving.
46
+ To achieve the best effects, the image should be scaled to
47
+ values between 0 and 1 beforehand.
48
+
49
+ Note that the images voxel-spacing will be taken into account.
50
+
51
+ Copyright (C) 2013 Oskar Maier
52
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
53
+ and you are welcome to redistribute it under certain conditions; see
54
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
55
+ """
56
+
57
+
58
+ # code
59
+ def main():
60
+ # parse cmd arguments
61
+ parser = getParser()
62
+ parser.parse_args()
63
+ args = getArguments(parser)
64
+
65
+ # prepare logger
66
+ logger = Logger.getInstance()
67
+ if args.debug:
68
+ logger.setLevel(logging.DEBUG)
69
+ elif args.verbose:
70
+ logger.setLevel(logging.INFO)
71
+
72
+ # check if output image exists (will also be performed before saving, but as the smoothing might be very time intensity, a initial check can save frustration)
73
+ if not args.force:
74
+ if os.path.exists(args.output):
75
+ raise parser.error(
76
+ "The output image {} already exists.".format(args.output)
77
+ )
78
+
79
+ # loading image
80
+ data_input, header_input = load(args.input)
81
+
82
+ # apply the watershed
83
+ logger.info(
84
+ "Applying anisotropic diffusion with settings: niter={} / kappa={} / gamma={}...".format(
85
+ args.iterations, args.kappa, args.gamma
86
+ )
87
+ )
88
+ data_output = anisotropic_diffusion(
89
+ data_input,
90
+ args.iterations,
91
+ args.kappa,
92
+ args.gamma,
93
+ get_pixel_spacing(header_input),
94
+ )
95
+
96
+ # save file
97
+ save(data_output, args.output, header_input, args.force)
98
+
99
+ logger.info("Successfully terminated.")
100
+
101
+
102
+ def getArguments(parser):
103
+ "Provides additional validation of the arguments collected by argparse."
104
+ return parser.parse_args()
105
+
106
+
107
+ def getParser():
108
+ "Creates and returns the argparse parser object."
109
+ parser = argparse.ArgumentParser(description=__description__)
110
+ parser.add_argument("input", help="Source volume.")
111
+ parser.add_argument("output", help="Target volume.")
112
+ parser.add_argument(
113
+ "-i",
114
+ "--iterations",
115
+ type=int,
116
+ default=1,
117
+ help="The number of smoothing iterations. Strong parameter.",
118
+ )
119
+ parser.add_argument(
120
+ "-k",
121
+ "--kappa",
122
+ type=int,
123
+ default=50,
124
+ help="The algorithms kappa parameter. The higher the more edges are smoothed over.",
125
+ )
126
+ parser.add_argument(
127
+ "-g",
128
+ "--gamma",
129
+ type=float,
130
+ default=0.1,
131
+ help="The algorithms gamma parameter. The higher, the stronger the plateaus between edges are smeared.",
132
+ )
133
+ parser.add_argument(
134
+ "-v", dest="verbose", action="store_true", help="Display more information."
135
+ )
136
+ parser.add_argument(
137
+ "-d", dest="debug", action="store_true", help="Display debug information."
138
+ )
139
+ parser.add_argument(
140
+ "-f",
141
+ dest="force",
142
+ action="store_true",
143
+ help="Silently override existing output images.",
144
+ )
145
+
146
+ return parser
147
+
148
+
149
+ if __name__ == "__main__":
150
+ main()
medpy/source/bin/medpy_apparent_diffusion_coefficient.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Computes the apparent diffusion coefficient from two diffusion weighted MRI images.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ # build-in modules
23
+ import argparse
24
+ import logging
25
+
26
+ # third-party modules
27
+ import numpy
28
+ from scipy.ndimage import binary_dilation, binary_erosion, binary_fill_holes
29
+
30
+ # own modules
31
+ from medpy.core import Logger
32
+ from medpy.core.exceptions import ArgumentError
33
+ from medpy.filter import otsu
34
+ from medpy.filter.binary import largest_connected_component
35
+ from medpy.io import header, load, save
36
+
37
+ # path changes
38
+
39
+
40
+ # information
41
+ __author__ = "Oskar Maier"
42
+ __version__ = "r0.1.1, 2013-07-18"
43
+ __email__ = "oskar.maier@googlemail.com"
44
+ __status__ = "Release"
45
+ __description__ = """
46
+ Computes the apparent diffusion coefficient from two diffusion weighted
47
+ MRI images. The output image will be of type float.
48
+
49
+ Normally diffusion weight (DW) MRI images are acquired once with a
50
+ b-value of 0 (which we call b0) and once with another b-value (which we
51
+ call bx) such as 500, 800 or 1000. The latter is typical for brain MRIs.
52
+ This results in a single b0 DW image and three bx DW images, one for each
53
+ direction.
54
+
55
+ Usually the three bx DW images are already combined into an isotropic
56
+ average image (which we call abx) denoting the length of the three-dimensional
57
+ vector formed by the the three bx images.
58
+
59
+ The formula presented in [1] is applied to the b0 and abx images to
60
+ compute the apparent diffusion coefficient (ADC):
61
+
62
+ ADC = -bx-value * ln(abx-image / b0-image)
63
+
64
+ To cope with zero-values in the images, we apply a-priori a
65
+ thresholding to the b0 + abx DW image, set all lower values to 0 and
66
+ apply the formula only to the remaining intensities. Note that the
67
+ default threshold is chosen using Otsu's and is good for most cases.
68
+ (Thanks to Nils at the UKE in Hamburg, Germany for this hint!)
69
+
70
+ We restrain from implementing a method working on more DW images, that
71
+ were acquired with multiple b-values, as [2] observed that this might
72
+ lead to worse results.
73
+
74
+ [1] "Understanding Diffusion MR Imaging Techniques: From Scalar
75
+ Diffusion-weighted Imaging to Diffusion Tensor Imaging and Beyond" by
76
+ Patric Hagmann et al.
77
+ [2] "Understanding the Mathematics Involved in Calculating Apparent
78
+ Diffusion Coefficient Maps" by Michael Yong Park and Jae Young Byun
79
+
80
+ Copyright (C) 2013 Oskar Maier
81
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
82
+ and you are welcome to redistribute it under certain conditions; see
83
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
84
+ """
85
+
86
+
87
+ # code
88
+ def main():
89
+ args = getArguments(getParser())
90
+
91
+ # prepare logger
92
+ logger = Logger.getInstance()
93
+ if args.debug:
94
+ logger.setLevel(logging.DEBUG)
95
+ elif args.verbose:
96
+ logger.setLevel(logging.INFO)
97
+
98
+ # loading input images
99
+ b0img, b0hdr = load(args.b0image)
100
+ bximg, bxhdr = load(args.bximage)
101
+
102
+ # convert to float
103
+ b0img = b0img.astype(float)
104
+ bximg = bximg.astype(float)
105
+
106
+ # check if image are compatible
107
+ if not b0img.shape == bximg.shape:
108
+ raise ArgumentError(
109
+ "The input images shapes differ i.e. {} != {}.".format(
110
+ b0img.shape, bximg.shape
111
+ )
112
+ )
113
+ if not header.get_pixel_spacing(b0hdr) == header.get_pixel_spacing(bxhdr):
114
+ raise ArgumentError(
115
+ "The input images voxel spacing differs i.e. {} != {}.".format(
116
+ header.get_pixel_spacing(b0hdr), header.get_pixel_spacing(bxhdr)
117
+ )
118
+ )
119
+
120
+ # check if supplied threshold value as well as the b value is above 0
121
+ if args.threshold is not None and not args.threshold >= 0:
122
+ raise ArgumentError(
123
+ "The supplied threshold value must be greater than 0, otherwise a division through 0 might occur."
124
+ )
125
+ if not args.b > 0:
126
+ raise ArgumentError("The supplied b-value must be greater than 0.")
127
+
128
+ # compute threshold value if not supplied
129
+ if args.threshold is None:
130
+ b0thr = otsu(b0img, 32) / 4.0 # divide by 4 to decrease impact
131
+ bxthr = otsu(bximg, 32) / 4.0
132
+ if 0 >= b0thr:
133
+ raise ArgumentError(
134
+ "The supplied b0image seems to contain negative values."
135
+ )
136
+ if 0 >= bxthr:
137
+ raise ArgumentError(
138
+ "The supplied bximage seems to contain negative values."
139
+ )
140
+ else:
141
+ b0thr = bxthr = args.threshold
142
+
143
+ logger.debug("thresholds={}/{}, b-value={}".format(b0thr, bxthr, args.b))
144
+
145
+ # threshold b0 + bx DW image to obtain a mask
146
+ # b0 mask avoid division through 0, bx mask avoids a zero in the ln(x) computation
147
+ mask = binary_fill_holes(b0img > b0thr) & binary_fill_holes(bximg > bxthr)
148
+
149
+ # perform a number of binary morphology steps to select the brain only
150
+ mask = binary_erosion(mask, iterations=1)
151
+ mask = largest_connected_component(mask)
152
+ mask = binary_dilation(mask, iterations=1)
153
+
154
+ logger.debug(
155
+ "excluding {} of {} voxels from the computation and setting them to zero".format(
156
+ numpy.count_nonzero(mask), numpy.prod(mask.shape)
157
+ )
158
+ )
159
+
160
+ # compute the ADC
161
+ adc = numpy.zeros(b0img.shape, b0img.dtype)
162
+ adc[mask] = -1.0 * args.b * numpy.log(bximg[mask] / b0img[mask])
163
+ adc[adc < 0] = 0
164
+
165
+ # saving the resulting image
166
+ save(adc, args.output, b0hdr, args.force)
167
+
168
+
169
+ def getArguments(parser):
170
+ "Provides additional validation of the arguments collected by argparse."
171
+ return parser.parse_args()
172
+
173
+
174
+ def getParser():
175
+ "Creates and returns the argparse parser object."
176
+ parser = argparse.ArgumentParser(
177
+ description=__description__,
178
+ formatter_class=argparse.RawDescriptionHelpFormatter,
179
+ )
180
+ parser.add_argument(
181
+ "b0image", help="the diffusion weighted image required with b=0"
182
+ )
183
+ parser.add_argument(
184
+ "bximage", help="the diffusion weighted image required with b=x"
185
+ )
186
+ parser.add_argument(
187
+ "b", type=int, help="the b-value used to acquire the bx-image (i.e. x)"
188
+ )
189
+ parser.add_argument(
190
+ "output", help="the computed apparent diffusion coefficient image"
191
+ )
192
+
193
+ parser.add_argument(
194
+ "-t",
195
+ "--threshold",
196
+ type=int,
197
+ dest="threshold",
198
+ help="set a fixed threshold for the input images to mask the computation",
199
+ )
200
+
201
+ parser.add_argument(
202
+ "-v", "--verbose", dest="verbose", action="store_true", help="verbose output"
203
+ )
204
+ parser.add_argument(
205
+ "-d", dest="debug", action="store_true", help="Display debug information."
206
+ )
207
+ parser.add_argument(
208
+ "-f",
209
+ "--force",
210
+ dest="force",
211
+ action="store_true",
212
+ help="overwrite existing files",
213
+ )
214
+ return parser
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()
medpy/source/bin/medpy_binary_resampling.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Re-samples a binary image according to a supplied voxel spacing.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+
25
+ # build-in modules
26
+ import os
27
+
28
+ # third-party modules
29
+ import numpy
30
+ from scipy.ndimage import binary_erosion, distance_transform_edt, label, zoom
31
+
32
+ # own modules
33
+ from medpy.core import Logger
34
+ from medpy.filter import resample
35
+ from medpy.io import header, load, save
36
+ from medpy.utilities import argparseu
37
+
38
+ # information
39
+ __author__ = "Oskar Maier"
40
+ __version__ = "r0.1.0, 2014-11-25"
41
+ __email__ = "oskar.maier@googlemail.com"
42
+ __status__ = "Release"
43
+ __description__ = """
44
+ Re-samples a binary image according to a supplied voxel spacing.
45
+
46
+ For an optimal results without outliers or holes in the case of up-sampling, the required
47
+ number of additional slices is added using shape based interpolation. All down-sampling
48
+ and the remaining small up-sampling operations are then executed with a nearest
49
+ neighbourhood interpolation of a chosen order.
50
+
51
+ BSpline is used for interpolation. A order between 0 and 5 can be selected. The default
52
+ is 0 (= nearest neighbour). In some rare case an order of 1 (= linear) might be
53
+ necessary.
54
+
55
+ Note that the pixel data type of the input image is treated as binary.
56
+
57
+ Copyright (C) 2013 Oskar Maier
58
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
59
+ and you are welcome to redistribute it under certain conditions; see
60
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
61
+ """
62
+
63
+
64
+ # code
65
+ def main():
66
+ parser = getParser()
67
+ args = getArguments(parser)
68
+
69
+ # prepare logger
70
+ logger = Logger.getInstance()
71
+ if args.debug:
72
+ logger.setLevel(logging.DEBUG)
73
+ elif args.verbose:
74
+ logger.setLevel(logging.INFO)
75
+
76
+ # loading input images
77
+ img, hdr = load(args.input)
78
+ img = img.astype(numpy.bool_)
79
+
80
+ # check spacing values
81
+ if not len(args.spacing) == img.ndim:
82
+ parser.error(
83
+ "The image has {} dimensions, but {} spacing parameters have been supplied.".format(
84
+ img.ndim, len(args.spacing)
85
+ )
86
+ )
87
+
88
+ # check if output image exists
89
+ if not args.force:
90
+ if os.path.exists(args.output):
91
+ parser.error("The output image {} already exists.".format(args.output))
92
+
93
+ logger.debug("target voxel spacing: {}".format(args.spacing))
94
+
95
+ # determine number of required complete slices for up-sampling
96
+ vs = header.get_pixel_spacing(hdr)
97
+ rcss = [
98
+ int(y // x - 1) for x, y in zip(args.spacing, vs)
99
+ ] # TODO: For option b, remove the - 1; better: no option b, since I am rounding later anyway
100
+
101
+ # remove negatives and round up to next even number
102
+ rcss = [x if x > 0 else 0 for x in rcss]
103
+ rcss = [x if 0 == x % 2 else x + 1 for x in rcss]
104
+ logger.debug("intermediate slices to add per dimension: {}".format(rcss))
105
+
106
+ # for each dimension requiring up-sampling, from the highest down, perform shape based slice interpolation
107
+ logger.info("Adding required slices using shape based interpolation.")
108
+ for dim, rcs in enumerate(rcss):
109
+ if rcs > 0:
110
+ logger.debug(
111
+ "adding {} intermediate slices to dimension {}".format(rcs, dim)
112
+ )
113
+ img = shape_based_slice_interpolation(img, dim, rcs)
114
+ logger.debug("resulting new image shape: {}".format(img.shape))
115
+
116
+ # compute and set new voxel spacing
117
+ nvs = [x / (y + 1.0) for x, y in zip(vs, rcss)]
118
+ header.set_pixel_spacing(hdr, nvs)
119
+ logger.debug("intermediate voxel spacing: {}".format(nvs))
120
+
121
+ # interpolate with nearest neighbour
122
+ logger.info("Re-sampling the image with a b-spline order of {}.".format(args.order))
123
+ img, hdr = resample(img, hdr, args.spacing, args.order, mode="nearest")
124
+
125
+ # saving the resulting image
126
+ save(img, args.output, hdr, args.force)
127
+
128
+
129
+ def shape_based_slice_interpolation(img, dim, nslices):
130
+ """
131
+ Adds `nslices` slices between all slices of the binary image `img` along dimension
132
+ `dim` respecting the original slice values to be situated in the middle of each
133
+ slice. Extrapolation situations are handled by simple repeating.
134
+
135
+ Interpolation of new slices is performed using shape based interpolation.
136
+
137
+ Parameters
138
+ ----------
139
+ img : array_like
140
+ A n-dimensional image.
141
+ dim : int
142
+ The dimension along which to add slices.
143
+ nslices : int
144
+ The number of slices to add. Must be an even number.
145
+
146
+ Returns
147
+ -------
148
+ out : ndarray
149
+ The re-sampled image.
150
+ """
151
+ # check arguments
152
+ if not 0 == nslices % 2:
153
+ raise ValueError("nslices must be an even number")
154
+
155
+ out = None
156
+ slicer = [slice(None)] * img.ndim
157
+ chunk_full_shape = list(img.shape)
158
+ chunk_full_shape[dim] = nslices + 2
159
+
160
+ for sl1, sl2 in zip(numpy.rollaxis(img, dim)[:-1], numpy.rollaxis(img, dim)[1:]):
161
+ if 0 == numpy.count_nonzero(sl1) and 0 == numpy.count_nonzero(sl2):
162
+ chunk = numpy.zeros(chunk_full_shape, dtype=numpy.bool_)
163
+ else:
164
+ chunk = shape_based_slice_insertation_object_wise(sl1, sl2, dim, nslices)
165
+ if out is None:
166
+ out = numpy.delete(chunk, -1, dim)
167
+ else:
168
+ out = numpy.concatenate((out, numpy.delete(chunk, -1, dim)), dim)
169
+
170
+ slicer[dim] = numpy.newaxis
171
+ out = numpy.concatenate((out, sl2[tuple(slicer)]), dim)
172
+
173
+ slicer[dim] = slice(0, 1)
174
+ for _ in range(nslices // 2):
175
+ out = numpy.concatenate((img[tuple(slicer)], out), dim)
176
+ slicer[dim] = slice(-1, None)
177
+ for _ in range(nslices // 2):
178
+ out = numpy.concatenate((out, img[tuple(slicer)]), dim)
179
+
180
+ return out
181
+
182
+
183
+ def shape_based_slice_insertation_object_wise(sl1, sl2, dim, nslices, order=3):
184
+ """
185
+ Wrapper to apply `shape_based_slice_insertation()` for each binary object
186
+ separately to ensure correct extrapolation behaviour.
187
+ """
188
+ out = None
189
+ sandwich = numpy.concatenate((sl1[numpy.newaxis], sl2[numpy.newaxis]), 0)
190
+ label_image, n_labels = label(sandwich)
191
+ for lid in range(1, n_labels + 1):
192
+ _sl1, _sl2 = label_image == lid
193
+ _out = shape_based_slice_insertation(_sl1, _sl2, dim, nslices, order=3)
194
+ if out is None:
195
+ out = _out
196
+ else:
197
+ out |= _out
198
+ return out
199
+
200
+
201
+ def shape_based_slice_insertation(sl1, sl2, dim, nslices, order=3):
202
+ """
203
+ Insert `nslices` new slices between `sl1` and `sl2` along dimension `dim` using shape
204
+ based binary interpolation.
205
+
206
+ Extrapolation is handled adding `nslices`/2 step-wise eroded copies of the last slice
207
+ in each direction.
208
+
209
+ Parameters
210
+ ----------
211
+ sl1 : array_like
212
+ First slice. Treated as binary data.
213
+ sl2 : array_like
214
+ Second slice. Treated as binary data.
215
+ dim : int
216
+ The new dimension along which to add the new slices.
217
+ nslices : int
218
+ The number of slices to add.
219
+ order : int
220
+ The b-spline interpolation order for re-sampling the distance maps.
221
+
222
+ Returns
223
+ -------
224
+ out : ndarray
225
+ A binary image of size `sl1`.shape() extend by `nslices`+2 along the new
226
+ dimension `dim`. The border slices are the original slices `sl1` and `sl2`.
227
+ """
228
+ sl1 = sl1.astype(numpy.bool_)
229
+ sl2 = sl2.astype(numpy.bool_)
230
+
231
+ # extrapolation through erosion
232
+ if 0 == numpy.count_nonzero(sl1):
233
+ slices = [sl1]
234
+ for _ in range(nslices / 2):
235
+ slices.append(numpy.zeros_like(sl1))
236
+ for i in range(1, nslices / 2 + nslices % 2 + 1)[::-1]:
237
+ slices.append(binary_erosion(sl2, iterations=i))
238
+ slices.append(sl2)
239
+ return numpy.rollaxis(numpy.asarray(slices), 0, dim + 1)
240
+ # return numpy.asarray([sl.T for sl in slices]).T
241
+ elif 0 == numpy.count_nonzero(sl2):
242
+ slices = [sl1]
243
+ for i in range(1, nslices / 2 + 1):
244
+ slices.append(binary_erosion(sl1, iterations=i))
245
+ for _ in range(0, nslices / 2 + nslices % 2):
246
+ slices.append(numpy.zeros_like(sl2))
247
+ slices.append(sl2)
248
+ return numpy.rollaxis(numpy.asarray(slices), 0, dim + 1)
249
+ # return numpy.asarray([sl.T for sl in slices]).T
250
+
251
+ # interpolation shape based
252
+ # note: distance_transform_edt shows strange behaviour for ones-arrays
253
+ dt1 = distance_transform_edt(~sl1) - distance_transform_edt(sl1)
254
+ dt2 = distance_transform_edt(~sl2) - distance_transform_edt(sl2)
255
+
256
+ slicer = [slice(None)] * dt1.ndim
257
+ slicer = slicer[:dim] + [numpy.newaxis] + slicer[dim:]
258
+ out = numpy.concatenate((dt1[tuple(slicer)], dt2[tuple(slicer)]), axis=dim)
259
+ zoom_factors = [1] * dt1.ndim
260
+ zoom_factors = zoom_factors[:dim] + [(nslices + 2) / 2.0] + zoom_factors[dim:]
261
+ out = zoom(out, zoom_factors, order=order)
262
+
263
+ return out <= 0
264
+
265
+
266
+ def getArguments(parser):
267
+ "Provides additional validation of the arguments collected by argparse."
268
+ args = parser.parse_args()
269
+ if args.order < 0 or args.order > 5:
270
+ parser.error("The order has to be a number between 0 and 5.")
271
+ return args
272
+
273
+
274
+ def getParser():
275
+ "Creates and returns the argparse parser object."
276
+ parser = argparse.ArgumentParser(
277
+ formatter_class=argparse.RawDescriptionHelpFormatter,
278
+ description=__description__,
279
+ )
280
+ parser.add_argument("input", help="the input image")
281
+ parser.add_argument("output", help="the output image")
282
+ parser.add_argument(
283
+ "spacing",
284
+ type=argparseu.sequenceOfFloatsGt,
285
+ help="the desired voxel spacing in colon-separated values, e.g. 1.2,1.2,5.0",
286
+ )
287
+ parser.add_argument(
288
+ "-o",
289
+ "--order",
290
+ type=int,
291
+ default=0,
292
+ dest="order",
293
+ help="the bspline order, default is 0 (= nearest neighbour)",
294
+ )
295
+
296
+ parser.add_argument(
297
+ "-v", "--verbose", dest="verbose", action="store_true", help="verbose output"
298
+ )
299
+ parser.add_argument(
300
+ "-d", dest="debug", action="store_true", help="Display debug information."
301
+ )
302
+ parser.add_argument(
303
+ "-f",
304
+ "--force",
305
+ dest="force",
306
+ action="store_true",
307
+ help="overwrite existing files",
308
+ )
309
+ return parser
310
+
311
+
312
+ if __name__ == "__main__":
313
+ main()
medpy/source/bin/medpy_convert.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Convert an image from one format into another.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ # build-in modules
23
+ import argparse
24
+ import logging
25
+
26
+ # own modules
27
+ from medpy.core import Logger
28
+ from medpy.io import load, save
29
+
30
+ # third-party modules
31
+
32
+ # path changes
33
+
34
+
35
+ # information
36
+ __author__ = "Oskar Maier"
37
+ __version__ = "r0.1.1, 2012-05-25"
38
+ __email__ = "oskar.maier@googlemail.com"
39
+ __status__ = "Release"
40
+ __description__ = """
41
+ Convert an image from one format into another. The image type is
42
+ determined by the file suffixes.
43
+
44
+ Copyright (C) 2013 Oskar Maier
45
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
46
+ and you are welcome to redistribute it under certain conditions; see
47
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
48
+ """
49
+
50
+
51
+ # code
52
+ def main():
53
+ args = getArguments(getParser())
54
+
55
+ # prepare logger
56
+ logger = Logger.getInstance()
57
+ if args.debug:
58
+ logger.setLevel(logging.DEBUG)
59
+ elif args.verbose:
60
+ logger.setLevel(logging.INFO)
61
+
62
+ # load input image
63
+ data_input, header_input = load(args.input)
64
+
65
+ # eventually empty data
66
+ if args.empty:
67
+ data_input.fill(False)
68
+
69
+ # save resulting volume
70
+ save(data_input, args.output, header_input, args.force)
71
+
72
+ logger.info("Successfully terminated.")
73
+
74
+
75
+ def getArguments(parser):
76
+ "Provides additional validation of the arguments collected by argparse."
77
+ return parser.parse_args()
78
+
79
+
80
+ def getParser():
81
+ "Creates and returns the argparse parser object."
82
+ parser = argparse.ArgumentParser(description=__description__)
83
+ parser.add_argument("input", help="Source volume.")
84
+ parser.add_argument("output", help="Target volume.")
85
+ parser.add_argument(
86
+ "-e",
87
+ dest="empty",
88
+ action="store_true",
89
+ help="Instead of copying the voxel data, create an empty copy conserving all meta-data if possible.",
90
+ )
91
+ parser.add_argument(
92
+ "-v", dest="verbose", action="store_true", help="Display more information."
93
+ )
94
+ parser.add_argument(
95
+ "-d", dest="debug", action="store_true", help="Display debug information."
96
+ )
97
+ parser.add_argument(
98
+ "-f",
99
+ dest="force",
100
+ action="store_true",
101
+ help="Silently override existing output images.",
102
+ )
103
+ return parser
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
medpy/source/bin/medpy_create_empty_volume_by_example.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Creates an empty volume with the same attributes as the passes example image.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>."""
20
+
21
+ # build-in modules
22
+ import argparse
23
+ import logging
24
+
25
+ # third-party modules
26
+ import numpy
27
+
28
+ # own modules
29
+ from medpy.core import Logger
30
+ from medpy.io import load, save
31
+
32
+ # path changes
33
+
34
+
35
+ # information
36
+ __author__ = "Oskar Maier"
37
+ __version__ = "r0.1.0, 2012-08-24"
38
+ __email__ = "oskar.maier@googlemail.com"
39
+ __status__ = "Release"
40
+ __description__ = """
41
+ Creates an empty volume with the same attributes as the passes example image.
42
+
43
+ Copyright (C) 2013 Oskar Maier
44
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
45
+ and you are welcome to redistribute it under certain conditions; see
46
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
47
+ """
48
+
49
+
50
+ # code
51
+ def main():
52
+ args = getArguments(getParser())
53
+
54
+ # prepare logger
55
+ logger = Logger.getInstance()
56
+ if args.debug:
57
+ logger.setLevel(logging.DEBUG)
58
+ elif args.verbose:
59
+ logger.setLevel(logging.INFO)
60
+
61
+ # loading input image
62
+ input_data, input_header = load(args.example)
63
+
64
+ # create empty volume with same attributes
65
+ output_data = numpy.zeros(input_data.shape, dtype=input_data.dtype)
66
+
67
+ # save resulting image
68
+ save(output_data, args.output, input_header, args.force)
69
+
70
+ logger.info("Successfully terminated.")
71
+
72
+
73
+ def getArguments(parser):
74
+ "Provides additional validation of the arguments collected by argparse."
75
+ return parser.parse_args()
76
+
77
+
78
+ def getParser():
79
+ "Creates and returns the argparse parser object."
80
+ parser = argparse.ArgumentParser(
81
+ description=__description__, formatter_class=argparse.RawTextHelpFormatter
82
+ )
83
+ parser.add_argument("example", help="The example volume.")
84
+ parser.add_argument("output", help="Target volume.")
85
+ parser.add_argument(
86
+ "-v", dest="verbose", action="store_true", help="Display more information."
87
+ )
88
+ parser.add_argument(
89
+ "-d", dest="debug", action="store_true", help="Display debug information."
90
+ )
91
+ parser.add_argument(
92
+ "-f",
93
+ dest="force",
94
+ action="store_true",
95
+ help="Silently override existing output images.",
96
+ )
97
+ return parser
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
medpy/source/bin/medpy_dicom_slices_to_volume.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Converts a collection of DICOM slices into a proper image volume.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>."""
20
+
21
+ # build-in modules
22
+ import argparse
23
+ import logging
24
+
25
+ # own modules
26
+ from medpy.core import Logger
27
+ from medpy.io import load, save
28
+
29
+ # third-party modules
30
+
31
+ # path changes
32
+
33
+
34
+ # information
35
+ __author__ = "Oskar Maier"
36
+ __version__ = "r0.2.1, 2012-06-13"
37
+ __email__ = "oskar.maier@googlemail.com"
38
+ __status__ = "Release"
39
+ __description__ = """
40
+ Converts a collection of DICOM slices (a DICOM series) into a proper
41
+ image volume. Note that this operation does not preserve header
42
+ information.
43
+
44
+ Copyright (C) 2013 Oskar Maier
45
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
46
+ and you are welcome to redistribute it under certain conditions; see
47
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
48
+ """
49
+
50
+
51
+ # code
52
+ def main():
53
+ args = getArguments(getParser())
54
+
55
+ # prepare logger
56
+ logger = Logger.getInstance()
57
+ if args.debug:
58
+ logger.setLevel(logging.DEBUG)
59
+ elif args.verbose:
60
+ logger.setLevel(logging.INFO)
61
+
62
+ img, hdr = load(args.input)
63
+
64
+ if args.spacing:
65
+ print("{}".format(hdr.get_voxel_spacing()))
66
+ return 0
67
+
68
+ logger.debug("Resulting shape is {}.".format(img.shape))
69
+
70
+ # save resulting volume
71
+ save(img, args.output, hdr, args.force)
72
+
73
+ logger.info("Successfully terminated.")
74
+
75
+
76
+ def getArguments(parser):
77
+ "Provides additional validation of the arguments collected by argparse."
78
+ return parser.parse_args()
79
+
80
+
81
+ def getParser():
82
+ "Creates and returns the argparse parser object."
83
+ parser = argparse.ArgumentParser(description=__description__)
84
+ parser.add_argument("input", help="Source folder.")
85
+ parser.add_argument("output", help="Target volume.")
86
+ parser.add_argument(
87
+ "-s", dest="spacing", action="store_true", help="Just print spacing and exit."
88
+ )
89
+ parser.add_argument(
90
+ "-v", dest="verbose", action="store_true", help="Display more information."
91
+ )
92
+ parser.add_argument(
93
+ "-d", dest="debug", action="store_true", help="Display debug information."
94
+ )
95
+ parser.add_argument(
96
+ "-f",
97
+ dest="force",
98
+ action="store_true",
99
+ help="Silently override existing output images.",
100
+ )
101
+ return parser
102
+
103
+
104
+ if __name__ == "__main__":
105
+ main()
medpy/source/bin/medpy_dicom_to_4D.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Takes a dicom folder, loads the contained slices and saves them as a proper 4D volume.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>."""
20
+
21
+ # build-in modules
22
+ import argparse
23
+ import logging
24
+
25
+ # third-party modules
26
+ import numpy
27
+
28
+ # own modules
29
+ from medpy.core import Logger
30
+ from medpy.core.exceptions import ArgumentError
31
+ from medpy.io import load, save
32
+
33
+ # path changes
34
+
35
+
36
+ # information
37
+ __author__ = "Oskar Maier"
38
+ __version__ = "d0.2.0, 2012-05-25"
39
+ __email__ = "oskar.maier@googlemail.com"
40
+ __status__ = "Development"
41
+ __description__ = """
42
+ Takes a dicom folder, loads the contained slices and saves them as a proper 4D volume.
43
+ The supplied target dimension parameter determines the dimension along which to split the
44
+ original image and the consecutive slices parameter determines the offset after which to
45
+ split.
46
+
47
+ A typical use-case are DICOM images, which often come with the temporal and third spatial
48
+ dimension stacked on top of each other.
49
+ Let us assume a (5000, 200, 190) 3D image. In reality this file contains a number of 50
50
+ volume of 100x200x190, which each represent a point in time. More concretely, always 50
51
+ slices of the first dimension show the transformation of a 2D image in time. Then occurs
52
+ a visible jump, when the view changes in space from the 50th to the 51th slice. The
53
+ following 50 slices are the temporal transformation of this new spatial slice and then
54
+ occur another jump, and so on.
55
+
56
+ Calling this script with a target dimension of 0 (meaning the first dimension of the
57
+ image containing the 5000 slices) and a consecutive slices parameter of 50 (which is used
58
+ to tell how many consecutive slices belong together), will result in a 4D image of the
59
+ shape (100, 50, 200, 190) containing the spatial volumes separated by an additional time
60
+ dimension.
61
+
62
+ Copyright (C) 2013 Oskar Maier
63
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
64
+ and you are welcome to redistribute it under certain conditions; see
65
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
66
+ """
67
+
68
+
69
+ # code
70
+ def main():
71
+ args = getArguments(getParser())
72
+
73
+ # prepare logger
74
+ logger = Logger.getInstance()
75
+ if args.debug:
76
+ logger.setLevel(logging.DEBUG)
77
+ elif args.verbose:
78
+ logger.setLevel(logging.INFO)
79
+
80
+ data_3d, _ = load(args.input)
81
+
82
+ # check parameters
83
+ if args.dimension >= data_3d.ndim or args.dimension < 0:
84
+ raise ArgumentError(
85
+ "The image has only {} dimensions. The supplied target dimension {} exceeds this number.".format(
86
+ data_3d.ndim, args.dimension
87
+ )
88
+ )
89
+ if not 0 == data_3d.shape[args.dimension] % args.offset:
90
+ raise ArgumentError(
91
+ "The number of slices {} in the target dimension {} of the image shape {} is not dividable by the supplied number of consecutive slices {}.".format(
92
+ data_3d.shape[args.dimension],
93
+ args.dimension,
94
+ data_3d.shape,
95
+ args.offset,
96
+ )
97
+ )
98
+
99
+ # prepare empty target volume
100
+ volumes_3d = data_3d.shape[args.dimension] / args.offset
101
+ shape_4d = list(data_3d.shape)
102
+ shape_4d[args.dimension] = volumes_3d
103
+ data_4d = numpy.zeros([args.offset] + shape_4d, dtype=data_3d.dtype)
104
+
105
+ logger.debug(
106
+ "Separating {} slices into {} 3D volumes of thickness {}.".format(
107
+ data_3d.shape[args.dimension], volumes_3d, args.offset
108
+ )
109
+ )
110
+
111
+ # iterate over 3D image and create sub volumes which are then added to the 4d volume
112
+ for idx in range(args.offset):
113
+ # collect the slices
114
+ for sl in range(volumes_3d):
115
+ idx_from = [slice(None), slice(None), slice(None)]
116
+ idx_from[args.dimension] = slice(
117
+ idx + sl * args.offset, idx + sl * args.offset + 1
118
+ )
119
+ idx_to = [slice(None), slice(None), slice(None)]
120
+ idx_to[args.dimension] = slice(sl, sl + 1)
121
+ # print 'Slice {} to {}.'.format(idx_from, idx_to)
122
+ data_4d[idx][tuple(idx_to)] = data_3d[tuple(idx_from)]
123
+
124
+ # flip dimensions such that the newly created is the last
125
+ data_4d = numpy.swapaxes(data_4d, 0, 3)
126
+
127
+ # save resulting 4D volume
128
+ save(data_4d, args.output, False, args.force)
129
+
130
+ logger.info("Successfully terminated.")
131
+
132
+
133
+ def getArguments(parser):
134
+ "Provides additional validation of the arguments collected by argparse."
135
+ return parser.parse_args()
136
+
137
+
138
+ def getParser():
139
+ "Creates and returns the argparse parser object."
140
+ parser = argparse.ArgumentParser(
141
+ description=__description__, formatter_class=argparse.RawTextHelpFormatter
142
+ )
143
+ parser.add_argument("input", help="Source directory.")
144
+ parser.add_argument("output", help="Target volume.")
145
+ parser.add_argument(
146
+ "dimension",
147
+ type=int,
148
+ help="The dimension in which to perform the cut (starting from 0).",
149
+ )
150
+ parser.add_argument(
151
+ "offset",
152
+ type=int,
153
+ help="How many consecutive slices belong together before a shift occurs. / The offset between the volumes.",
154
+ )
155
+ parser.add_argument(
156
+ "-v", dest="verbose", action="store_true", help="Display more information."
157
+ )
158
+ parser.add_argument(
159
+ "-d", dest="debug", action="store_true", help="Display debug information."
160
+ )
161
+ parser.add_argument(
162
+ "-f",
163
+ dest="force",
164
+ action="store_true",
165
+ help="Silently override existing output images.",
166
+ )
167
+ return parser
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()
medpy/source/bin/medpy_diff.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Compares the pixel values of two images and gives a measure of the difference.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>."""
20
+
21
+ import argparse
22
+ import logging
23
+
24
+ # build-in modules
25
+ import sys
26
+ from functools import reduce
27
+
28
+ # third-party modules
29
+ import numpy
30
+
31
+ # own modules
32
+ from medpy.core import Logger
33
+ from medpy.io import load
34
+
35
+ # path changes
36
+
37
+
38
+ # information
39
+ __author__ = "Oskar Maier"
40
+ __version__ = "r0.1.0, 2012-05-25"
41
+ __email__ = "oskar.maier@googlemail.com"
42
+ __status__ = "Release"
43
+ __description__ = """
44
+ Compares the pixel values of two images and gives a measure of the difference.
45
+
46
+ Also compares the dtype and shape.
47
+
48
+ Copyright (C) 2013 Oskar Maier
49
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
50
+ and you are welcome to redistribute it under certain conditions; see
51
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
52
+ """
53
+
54
+
55
+ # code
56
+ def main():
57
+ args = getArguments(getParser())
58
+
59
+ # prepare logger
60
+ logger = Logger.getInstance()
61
+ if args.debug:
62
+ logger.setLevel(logging.DEBUG)
63
+ elif args.verbose:
64
+ logger.setLevel(logging.INFO)
65
+
66
+ # load input image1
67
+ data_input1, _ = load(args.input1)
68
+
69
+ # load input image2
70
+ data_input2, _ = load(args.input2)
71
+
72
+ # compare dtype and shape
73
+ if not data_input1.dtype == data_input2.dtype:
74
+ print("Dtype differs: {} to {}".format(data_input1.dtype, data_input2.dtype))
75
+ if not data_input1.shape == data_input2.shape:
76
+ print("Shape differs: {} to {}".format(data_input1.shape, data_input2.shape))
77
+ print(
78
+ "The voxel content of images of different shape can not be compared. Exiting."
79
+ )
80
+ sys.exit(-1)
81
+
82
+ # compare image data
83
+ voxel_total = reduce(lambda x, y: x * y, data_input1.shape)
84
+ voxel_difference = len((data_input1 != data_input2).nonzero()[0])
85
+ if not 0 == voxel_difference:
86
+ print(
87
+ "Voxel differ: {} of {} total voxels".format(voxel_difference, voxel_total)
88
+ )
89
+ print(
90
+ "Max difference: {}".format(numpy.absolute(data_input1 - data_input2).max())
91
+ )
92
+ else:
93
+ print("No other difference.")
94
+
95
+ logger.info("Successfully terminated.")
96
+
97
+
98
+ def getArguments(parser):
99
+ "Provides additional validation of the arguments collected by argparse."
100
+ return parser.parse_args()
101
+
102
+
103
+ def getParser():
104
+ "Creates and returns the argparse parser object."
105
+ parser = argparse.ArgumentParser(description=__description__)
106
+ parser.add_argument("input1", help="Source volume one.")
107
+ parser.add_argument("input2", help="Source volume two.")
108
+ parser.add_argument(
109
+ "-v", dest="verbose", action="store_true", help="Display more information."
110
+ )
111
+ parser.add_argument(
112
+ "-d", dest="debug", action="store_true", help="Display debug information."
113
+ )
114
+ parser.add_argument(
115
+ "-f",
116
+ dest="force",
117
+ action="store_true",
118
+ help="Silently override existing output images.",
119
+ )
120
+ return parser
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
medpy/source/bin/medpy_extract_contour.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Convert a binary volume into a surface contour.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ # build-in modules
23
+ import argparse
24
+ import logging
25
+ import math
26
+
27
+ # third-party modules
28
+ import numpy
29
+ from scipy.ndimage import binary_dilation, binary_erosion, generate_binary_structure
30
+
31
+ # own modules
32
+ from medpy.core import Logger
33
+ from medpy.io import load, save
34
+
35
+ # path changes
36
+
37
+
38
+ # information
39
+ __author__ = "Oskar Maier"
40
+ __version__ = "r0.1.1, 2014-06-04"
41
+ __email__ = "oskar.maier@googlemail.com"
42
+ __status__ = "Release"
43
+ __description__ = """
44
+ Converts a binary volume into a surface contour. In the case of an even
45
+ contour width, the surface of the volume will correspond with the
46
+ middle of the contour line. In the case of an odd contour width, the
47
+ contour will be shifted by one voxel towards the inside of the volume.
48
+
49
+ In the case of 3D volumes, the contours result in shells, which might
50
+ not be desired, as they do not visualize well in 2D views. With the
51
+ '--dimension' argument, a dimension along which to extract the contours
52
+ can be supplied.
53
+
54
+ Copyright (C) 2013 Oskar Maier
55
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
56
+ and you are welcome to redistribute it under certain conditions; see
57
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
58
+ """
59
+
60
+
61
+ # code
62
+ def main():
63
+ args = getArguments(getParser())
64
+
65
+ # prepare logger
66
+ logger = Logger.getInstance()
67
+ if args.debug:
68
+ logger.setLevel(logging.DEBUG)
69
+ elif args.verbose:
70
+ logger.setLevel(logging.INFO)
71
+
72
+ # load input image
73
+ data_input, header_input = load(args.input)
74
+
75
+ # treat as binary
76
+ data_input = data_input.astype(numpy.bool_)
77
+
78
+ # check dimension argument
79
+ if args.dimension and (
80
+ not args.dimension >= 0 or not args.dimension < data_input.ndim
81
+ ):
82
+ argparse.ArgumentError(
83
+ args.dimension,
84
+ "Invalid dimension of {} supplied. Image has only {} dimensions.".format(
85
+ args.dimension, data_input.ndim
86
+ ),
87
+ )
88
+
89
+ # compute erosion and dilation steps
90
+ erosions = int(math.ceil(args.width / 2.0))
91
+ dilations = int(math.floor(args.width / 2.0))
92
+ logger.debug(
93
+ "Performing {} erosions and {} dilations to achieve a contour of width {}.".format(
94
+ erosions, dilations, args.width
95
+ )
96
+ )
97
+
98
+ # erode, dilate and compute contour
99
+ if not args.dimension:
100
+ eroded = (
101
+ binary_erosion(data_input, iterations=erosions)
102
+ if not 0 == erosions
103
+ else data_input
104
+ )
105
+ dilated = (
106
+ binary_dilation(data_input, iterations=dilations)
107
+ if not 0 == dilations
108
+ else data_input
109
+ )
110
+ data_output = numpy.logical_xor(dilated, eroded)
111
+ else:
112
+ slicer = [slice(None)] * data_input.ndim
113
+ bs_slicer = [slice(None)] * data_input.ndim
114
+ data_output = numpy.zeros_like(data_input)
115
+ for sl in range(data_input.shape[args.dimension]):
116
+ slicer[args.dimension] = slice(sl, sl + 1)
117
+ bs_slicer[args.dimension] = slice(1, 2)
118
+ bs = generate_binary_structure(data_input.ndim, 1)
119
+
120
+ eroded = (
121
+ binary_erosion(
122
+ data_input[tuple(slicer)],
123
+ structure=bs[tuple(bs_slicer)],
124
+ iterations=erosions,
125
+ )
126
+ if not 0 == erosions
127
+ else data_input[tuple(slicer)]
128
+ )
129
+ dilated = (
130
+ binary_dilation(
131
+ data_input[tuple(slicer)],
132
+ structure=bs[tuple(bs_slicer)],
133
+ iterations=dilations,
134
+ )
135
+ if not 0 == dilations
136
+ else data_input[tuple(slicer)]
137
+ )
138
+ data_output[tuple(slicer)] = numpy.logical_xor(dilated, eroded)
139
+ logger.debug(
140
+ "Contour image contains {} contour voxels.".format(
141
+ numpy.count_nonzero(data_output)
142
+ )
143
+ )
144
+
145
+ # save resulting volume
146
+ save(data_output, args.output, header_input, args.force)
147
+
148
+ logger.info("Successfully terminated.")
149
+
150
+
151
+ def getArguments(parser):
152
+ "Provides additional validation of the arguments collected by argparse."
153
+ args = parser.parse_args()
154
+ if args.width <= 0:
155
+ raise argparse.ArgumentError(
156
+ args.width, "The contour width must be a positive number."
157
+ )
158
+ return args
159
+
160
+
161
+ def getParser():
162
+ "Creates and returns the argparse parser object."
163
+ parser = argparse.ArgumentParser(description=__description__)
164
+ parser.add_argument("input", help="Source volume.")
165
+ parser.add_argument("output", help="Target volume.")
166
+ parser.add_argument(
167
+ "-w", "--width", dest="width", type=int, default=1, help="Width of the contour."
168
+ )
169
+ parser.add_argument(
170
+ "--dimension", type=int, help="Extract contours only along this dimension."
171
+ )
172
+ parser.add_argument(
173
+ "-v", dest="verbose", action="store_true", help="Display more information."
174
+ )
175
+ parser.add_argument(
176
+ "-d", dest="debug", action="store_true", help="Display debug information."
177
+ )
178
+ parser.add_argument(
179
+ "-f",
180
+ dest="force",
181
+ action="store_true",
182
+ help="Silently override existing output images.",
183
+ )
184
+ return parser
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()
medpy/source/bin/medpy_extract_min_max.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Extracts and displays the min/max values of a number of images.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ # build-in modules
23
+ import argparse
24
+ import logging
25
+ import os
26
+ import sys
27
+
28
+ # own modules
29
+ from medpy.core import Logger
30
+ from medpy.io import load
31
+
32
+ # third-party modules
33
+
34
+ # path changes
35
+
36
+
37
+ # information
38
+ __author__ = "Oskar Maier"
39
+ __version__ = "r0.2, 2011-12-13"
40
+ __email__ = "oskar.maier@googlemail.com"
41
+ __status__ = "Release"
42
+ __description__ = """
43
+ Extracts and displays the min/max values of a number of images
44
+ and prints the results to the stdout in csv format.
45
+
46
+ Copyright (C) 2013 Oskar Maier
47
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
48
+ and you are welcome to redistribute it under certain conditions; see
49
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
50
+ """
51
+
52
+
53
+ # code
54
+ def main():
55
+ # parse cmd arguments
56
+ parser = getParser()
57
+ parser.parse_args()
58
+ args = getArguments(parser)
59
+
60
+ # prepare logger
61
+ logger = Logger.getInstance()
62
+ if args.debug:
63
+ logger.setLevel(logging.DEBUG)
64
+ elif args.verbose:
65
+ logger.setLevel(logging.INFO)
66
+
67
+ # build output file name
68
+ file_csv_name = args.csv + ".csv"
69
+
70
+ # check if output file exists
71
+ if not args.force:
72
+ if os.path.exists(file_csv_name):
73
+ logger.warning(
74
+ "The output file {} already exists. Skipping.".format(file_csv_name)
75
+ )
76
+ sys.exit(0)
77
+
78
+ # write header line
79
+ print("image;min;max\n")
80
+
81
+ # iterate over input images
82
+ for image in args.images:
83
+ # get and prepare image data
84
+ logger.info("Processing image {}...".format(image))
85
+ image_data, _ = load(image)
86
+
87
+ # count number of labels and flag a warning if they reach the ushort border
88
+ min_value = image_data.min()
89
+ max_value = image_data.max()
90
+
91
+ # count number of labels and write
92
+ print("{};{};{}\n".format(image.split("/")[-1], min_value, max_value))
93
+
94
+ sys.stdout.flush()
95
+
96
+ logger.info("Successfully terminated.")
97
+
98
+
99
+ def getArguments(parser):
100
+ "Provides additional validation of the arguments collected by argparse."
101
+ return parser.parse_args()
102
+
103
+
104
+ def getParser():
105
+ "Creates and returns the argparse parser object."
106
+ parser = argparse.ArgumentParser(description=__description__)
107
+
108
+ parser.add_argument("csv", help="The file to store the results in (\wo suffix).")
109
+ parser.add_argument("images", nargs="+", help="One or more images.")
110
+ parser.add_argument(
111
+ "-v", dest="verbose", action="store_true", help="Display more information."
112
+ )
113
+ parser.add_argument(
114
+ "-d", dest="debug", action="store_true", help="Display debug information."
115
+ )
116
+ parser.add_argument(
117
+ "-f",
118
+ dest="force",
119
+ action="store_true",
120
+ help="Silently override existing output images.",
121
+ )
122
+
123
+ return parser
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
medpy/source/bin/medpy_extract_sub_volume.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Extracts a sub-volume from a medical image.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+ import os
25
+ import sys
26
+
27
+ # build-in modules
28
+ from argparse import RawTextHelpFormatter
29
+
30
+ # third-party modules
31
+ import numpy
32
+
33
+ # own modules
34
+ from medpy.core import ArgumentError, Logger
35
+ from medpy.io import load, save
36
+
37
+ # path changes
38
+
39
+
40
+ # information
41
+ __author__ = "Oskar Maier"
42
+ __version__ = "r0.3.0, 2011-12-11"
43
+ __email__ = "oskar.maier@googlemail.com"
44
+ __status__ = "Release"
45
+ __description__ = """
46
+ Takes a medical image of arbitrary dimensions and the dimensions
47
+ of a sub-volume that lies inside the dimensions of this images.
48
+ Extracts the sub-volume from the supplied image and saves it.
49
+
50
+ The volume to be extracted is defined by its slices, the syntax is the same as
51
+ for numpy array indexes (i.e. starting with zero-index, the first literal (x) of any
52
+ x:y included and the second (y) excluded).
53
+ E.g. '2:3,4:6' would extract the slice no. 3 in X and 5, 6 in Y direction of a 2D image.
54
+ E.g. '99:199,149:199,99:249' would extract the respective slices in X,Y and Z direction of a 3D image.
55
+ This could, for example, be used to extract the area of the liver form a CT scan.
56
+ To keep all slices in one direction just omit the respective value:
57
+ E.g. '99:199,149:199,' would work ust as example II, but extract all Z slices.
58
+ Note here the trailing colon.
59
+
60
+ Note to take into account the input images orientation when supplying the sub-volume.
61
+
62
+ Copyright (C) 2013 Oskar Maier
63
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
64
+ and you are welcome to redistribute it under certain conditions; see
65
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
66
+ """
67
+
68
+
69
+ # code
70
+ def main():
71
+ # parse cmd arguments
72
+ parser = getParser()
73
+ parser.parse_args()
74
+ args = getArguments(parser)
75
+
76
+ # prepare logger
77
+ logger = Logger.getInstance()
78
+ if args.debug:
79
+ logger.setLevel(logging.DEBUG)
80
+ elif args.verbose:
81
+ logger.setLevel(logging.INFO)
82
+
83
+ # check if output image exists
84
+ if not args.force:
85
+ if os.path.exists(args.output + args.image[-4:]):
86
+ logger.warning(
87
+ "The output file {} already exists. Breaking.".format(
88
+ args.output + args.image[-4:]
89
+ )
90
+ )
91
+ exit(1)
92
+
93
+ # load images
94
+ image_data, image_header = load(args.image)
95
+
96
+ # check image dimensions against sub-volume dimensions
97
+ if len(image_data.shape) != len(args.volume):
98
+ logger.critical(
99
+ "The supplied input image is of different dimension as the sub volume requested ({} to {})".format(
100
+ len(image_data.shape), len(args.volume)
101
+ )
102
+ )
103
+ raise ArgumentError(
104
+ "The supplied input image is of different dimension as the sub volume requested ({} to {})".format(
105
+ len(image_data.shape), len(args.volume)
106
+ )
107
+ )
108
+
109
+ # execute extraction of the sub-area
110
+ logger.info("Extracting sub-volume...")
111
+ index = [slice(x[0], x[1]) for x in args.volume]
112
+ volume = image_data[tuple(index)]
113
+
114
+ # check if the output image contains data
115
+ if 0 == len(volume):
116
+ logger.exception(
117
+ "The extracted sub-volume is of zero-size. This usual means that the supplied volume coordinates and the image coordinates do not intersect. Exiting the application."
118
+ )
119
+ sys.exit(-1)
120
+
121
+ # squeeze extracted sub-volume for the case in which one dimensions has been eliminated
122
+ volume = numpy.squeeze(volume)
123
+
124
+ logger.debug("Extracted volume is of shape {}.".format(volume.shape))
125
+
126
+ # save results in same format as input image
127
+ save(volume, args.output, image_header, args.force)
128
+
129
+ logger.info("Successfully terminated.")
130
+
131
+
132
+ def getArguments(parser):
133
+ "Provides additional validation of the arguments collected by argparse."
134
+ args = parser.parse_args()
135
+ # parse volume and adapt to zero-indexing
136
+ try:
137
+
138
+ def _to_int_or_none(string):
139
+ if 0 == len(string):
140
+ return None
141
+ return int(string)
142
+
143
+ def _to_int_or_none_double(string):
144
+ if 0 == len(string):
145
+ return [None, None]
146
+ return list(map(_to_int_or_none, string.split(":")))
147
+
148
+ args.volume = list(map(_to_int_or_none_double, args.volume.split(",")))
149
+ args.volume = [(x[0], x[1]) for x in args.volume]
150
+ except (ValueError, IndexError) as e:
151
+ raise ArgumentError(
152
+ 'Maleformed volume parameter "{}", see description with -h flag.'.format(
153
+ args.volume
154
+ ),
155
+ e,
156
+ )
157
+
158
+ return args
159
+
160
+
161
+ def getParser():
162
+ "Creates and returns the argparse parser object."
163
+ parser = argparse.ArgumentParser(
164
+ description=__description__, formatter_class=RawTextHelpFormatter
165
+ )
166
+
167
+ parser.add_argument("image", help="The source volume.")
168
+ parser.add_argument("output", help="The target volume.")
169
+ parser.add_argument(
170
+ "volume",
171
+ help="The coordinated of the sub-volume of the images that should be extracted.\nExample: 30:59,40:67,45:75 for a 3D image.\nSee -h for more information.",
172
+ )
173
+ parser.add_argument(
174
+ "-f",
175
+ dest="force",
176
+ action="store_true",
177
+ help="Set this flag to silently override files that exist.",
178
+ )
179
+ parser.add_argument(
180
+ "-v", dest="verbose", action="store_true", help="Display more information."
181
+ )
182
+ parser.add_argument(
183
+ "-d", dest="debug", action="store_true", help="Display debug information."
184
+ )
185
+
186
+ return parser
187
+
188
+
189
+ if __name__ == "__main__":
190
+ main()
medpy/source/bin/medpy_extract_sub_volume_auto.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Automatically extracts sub-volumes from a medical image.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+ import os
25
+
26
+ # build-in modules
27
+ from argparse import RawTextHelpFormatter
28
+
29
+ # own modules
30
+ from medpy.core import ArgumentError, Logger
31
+ from medpy.io import load, save
32
+
33
+ # third-party modules
34
+
35
+ # path changes
36
+
37
+
38
+ # information
39
+ __author__ = "Oskar Maier"
40
+ __version__ = "r0.2.1, 2012-05-17"
41
+ __email__ = "oskar.maier@googlemail.com"
42
+ __status__ = "Release"
43
+ __description__ = """
44
+ Takes a medical image of arbitrary dimensions and splits it into a
45
+ number of sub-volumes along the supplied dimensions. The maximum size
46
+ of each such created volume can be supplied.
47
+
48
+ Note to take into account the input images orientation when supplying the cut dimension.
49
+ Note that the image offsets are not preserved.
50
+
51
+ Copyright (C) 2013 Oskar Maier
52
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
53
+ and you are welcome to redistribute it under certain conditions; see
54
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
55
+ """
56
+
57
+
58
+ # code
59
+ def main():
60
+ # parse cmd arguments
61
+ parser = getParser()
62
+ parser.parse_args()
63
+ args = getArguments(parser)
64
+
65
+ # prepare logger
66
+ logger = Logger.getInstance()
67
+ if args.debug:
68
+ logger.setLevel(logging.DEBUG)
69
+ elif args.verbose:
70
+ logger.setLevel(logging.INFO)
71
+
72
+ # load input image
73
+ logger.info("Loading {}...".format(args.image))
74
+ image_data, image_header = load(args.image)
75
+
76
+ # check if supplied cut dimension is inside the input images dimensions
77
+ if args.dimension < 0 or args.dimension >= image_data.ndim:
78
+ logger.critical(
79
+ "The supplied cut-dimensions {} is invalid. The input image has only {} dimensions.".format(
80
+ args.dimension, image_data.ndim
81
+ )
82
+ )
83
+ raise ArgumentError(
84
+ "The supplied cut-dimensions {} is invalid. The input image has only {} dimensions.".format(
85
+ args.dimension, image_data.ndim
86
+ )
87
+ )
88
+
89
+ # prepare output filenames
90
+ name_output = args.output.replace("{}", "{:03d}")
91
+
92
+ # determine cut lines
93
+ no_sub_volumes = (
94
+ image_data.shape[args.dimension] / args.maxsize + 1
95
+ ) # int-division is desired
96
+ slices_per_volume = (
97
+ image_data.shape[args.dimension] / no_sub_volumes
98
+ ) # int-division is desired
99
+
100
+ # construct processing dict for each sub-volume
101
+ processing_array = []
102
+ for i in range(no_sub_volumes):
103
+ processing_array.append(
104
+ {
105
+ "path": name_output.format(i + 1),
106
+ "cut": (i * slices_per_volume, (i + 1) * slices_per_volume),
107
+ }
108
+ )
109
+ if no_sub_volumes - 1 == i: # last volume has to have increased cut end
110
+ processing_array[i]["cut"] = (
111
+ processing_array[i]["cut"][0],
112
+ image_data.shape[args.dimension],
113
+ )
114
+
115
+ # construct base indexing list
116
+ index = [slice(None) for _ in range(image_data.ndim)]
117
+
118
+ # execute extraction of the sub-volumes
119
+ logger.info("Extracting sub-volumes...")
120
+ for dic in processing_array:
121
+ # check if output images exists
122
+ if not args.force:
123
+ if os.path.exists(dic["path"]):
124
+ logger.warning(
125
+ "The output file {} already exists. Skipping this volume.".format(
126
+ dic["path"]
127
+ )
128
+ )
129
+ continue
130
+
131
+ # extracting sub-volume
132
+ index[args.dimension] = slice(dic["cut"][0], dic["cut"][1])
133
+ volume = image_data[tuple(index)]
134
+
135
+ logger.debug("Extracted volume is of shape {}.".format(volume.shape))
136
+
137
+ # saving sub-volume in same format as input image
138
+ logger.info("Saving cut {} as {}...".format(dic["cut"], dic["path"]))
139
+ save(volume, dic["path"], image_header, args.force)
140
+
141
+ logger.info("Successfully terminated.")
142
+
143
+
144
+ def getArguments(parser):
145
+ "Provides additional validation of the arguments collected by argparse."
146
+ return parser.parse_args()
147
+
148
+
149
+ def getParser():
150
+ "Creates and returns the argparse parser object."
151
+ parser = argparse.ArgumentParser(
152
+ description=__description__, formatter_class=RawTextHelpFormatter
153
+ )
154
+
155
+ parser.add_argument(
156
+ "image", help="An image of arbitrary dimensions that should be split."
157
+ )
158
+ parser.add_argument(
159
+ "output",
160
+ help='Output volumes. Has to include the sequence "{}" in the place where the volume number should be placed.',
161
+ )
162
+ parser.add_argument(
163
+ "dimension",
164
+ type=int,
165
+ help="The dimension in which direction to split (starting from 0:x).",
166
+ )
167
+ parser.add_argument(
168
+ "maxsize",
169
+ type=int,
170
+ help="The produced volumes will always be smaller than this size (in terms of slices in the cut-dimension).",
171
+ )
172
+ parser.add_argument(
173
+ "-f",
174
+ dest="force",
175
+ action="store_true",
176
+ help="Set this flag to silently override files that exist.",
177
+ )
178
+ parser.add_argument(
179
+ "-v", dest="verbose", action="store_true", help="Display more information."
180
+ )
181
+ parser.add_argument(
182
+ "-d", dest="debug", action="store_true", help="Display debug information."
183
+ )
184
+
185
+ return parser
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
medpy/source/bin/medpy_extract_sub_volume_by_example.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Extracts a sub-volume from a medical image by an example image.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+ import os
25
+ import sys
26
+
27
+ # build-in modules
28
+ from argparse import RawTextHelpFormatter
29
+
30
+ # third-party modules
31
+ import numpy
32
+
33
+ # own modules
34
+ from medpy.core import ArgumentError, Logger
35
+ from medpy.io import load, save
36
+
37
+ # path changes
38
+
39
+
40
+ # information
41
+ __author__ = "Oskar Maier"
42
+ __version__ = "r0.2.0, 2011-12-11"
43
+ __email__ = "oskar.maier@googlemail.com"
44
+ __status__ = "Release"
45
+ __description__ = """
46
+ Takes a medical image of arbitrary dimensions and a binary mask
47
+ image of the same dimensions. Extract the exact position of the
48
+ binary mask in the binary mask image and uses these dimensions
49
+ for the extraction of a sub-volume that lies inside the dimensions
50
+ of the medical images.
51
+ Extracts the sub-volume from the supplied image and saves it.
52
+
53
+ Note that both images must be of the same dimensionality, otherwise an exception is thrown.
54
+ Note that the input images offset is not taken into account.
55
+ Note to take into account the input images orientation.
56
+
57
+ This is a convenience script, combining the functionalities of
58
+ extract_mask_position and extract_sub_volume.
59
+
60
+ Copyright (C) 2013 Oskar Maier
61
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
62
+ and you are welcome to redistribute it under certain conditions; see
63
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
64
+ """
65
+
66
+
67
+ # code
68
+ def main():
69
+ # parse cmd arguments
70
+ parser = getParser()
71
+ parser.parse_args()
72
+ args = getArguments(parser)
73
+
74
+ # prepare logger
75
+ logger = Logger.getInstance()
76
+ if args.debug:
77
+ logger.setLevel(logging.DEBUG)
78
+ elif args.verbose:
79
+ logger.setLevel(logging.INFO)
80
+
81
+ # load mask
82
+ logger.info("Loading mask {}...".format(args.mask))
83
+ mask_image, _ = load(args.mask)
84
+
85
+ # store mask images shape for later check against the input image
86
+ mask_image_shape = mask_image.shape
87
+
88
+ # extract the position of the foreground object in the mask image
89
+ logger.info("Extract the position of the foreground object...")
90
+ positions = mask_image.nonzero()
91
+ positions = [
92
+ (max(0, positions[i].min() - args.offset), positions[i].max() + 1 + args.offset)
93
+ for i in range(len(positions))
94
+ ] # crop negative values
95
+ logger.debug("Extracted position is {}.".format(positions))
96
+
97
+ # load image
98
+ logger.info("Loading image {}...".format(args.image))
99
+ image_data, image_header = load(args.image)
100
+
101
+ # check if the mask image and the input image are of the same shape
102
+ if mask_image_shape != image_data.shape:
103
+ raise ArgumentError(
104
+ "The two input images are of different shape (mask: {} and image: {}).".format(
105
+ mask_image_shape, image_data.shape
106
+ )
107
+ )
108
+
109
+ # execute extraction of the sub-area
110
+ logger.info("Extracting sub-volume...")
111
+ index = tuple([slice(x[0], x[1]) for x in positions])
112
+ volume = image_data[index]
113
+
114
+ # check if the output image contains data
115
+ if 0 == len(volume):
116
+ logger.exception(
117
+ "The extracted sub-volume is of zero-size. This usual means that the mask image contained no foreground object."
118
+ )
119
+ sys.exit(0)
120
+
121
+ logger.debug("Extracted volume is of shape {}.".format(volume.shape))
122
+
123
+ # get base origin of the image
124
+ origin_base = numpy.array([0] * image_data.ndim) # for backwards compatibility
125
+
126
+ # modify the volume offset to imitate numpy behavior (e.g. wrap negative values)
127
+ offset = numpy.array([x[0] for x in positions])
128
+ for i in range(0, len(offset)):
129
+ if None == offset[i]:
130
+ offset[i] = 0
131
+ offset[offset < 0] += numpy.array(image_data.shape)[offset < 0] # wrap around
132
+ offset[offset < 0] = 0 # set negative to zero
133
+
134
+ # calculate final new origin
135
+ origin = origin_base + offset
136
+
137
+ logger.debug(
138
+ "Final origin created as {} + {} = {}.".format(origin_base, offset, origin)
139
+ )
140
+
141
+ # save results in same format as input image
142
+ logger.info("Saving extracted volume...")
143
+ save(volume, args.output, image_header, args.force)
144
+
145
+ logger.info("Successfully terminated.")
146
+
147
+
148
+ def getArguments(parser):
149
+ "Provides additional validation of the arguments collected by argparse."
150
+ args = parser.parse_args()
151
+ # check output image exists if override not forced
152
+ if not args.force:
153
+ if os.path.exists(args.output + args.image[-4:]):
154
+ raise ArgumentError(
155
+ "The supplied output file {} already exists. Run -f/force flag to override.".format(
156
+ args.output
157
+ )
158
+ )
159
+
160
+ return args
161
+
162
+
163
+ def getParser():
164
+ "Creates and returns the argparse parser object."
165
+ parser = argparse.ArgumentParser(
166
+ description=__description__, formatter_class=RawTextHelpFormatter
167
+ )
168
+
169
+ parser.add_argument("image", help="The input image.")
170
+ parser.add_argument("output", help="The resulting sub-volume.")
171
+ parser.add_argument(
172
+ "mask", help="A mask image containing a single foreground object (non-zero)."
173
+ )
174
+ parser.add_argument(
175
+ "-o",
176
+ "--offset",
177
+ dest="offset",
178
+ default=0,
179
+ type=int,
180
+ help="Set an offset by which the extracted sub-volume size should be increased in all directions.",
181
+ )
182
+ parser.add_argument(
183
+ "-f",
184
+ dest="force",
185
+ action="store_true",
186
+ help="Set this flag to silently override files that exist.",
187
+ )
188
+ parser.add_argument(
189
+ "-v", dest="verbose", action="store_true", help="Display more information."
190
+ )
191
+ parser.add_argument(
192
+ "-d", dest="debug", action="store_true", help="Display debug information."
193
+ )
194
+
195
+ return parser
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()
medpy/source/bin/medpy_fit_into_shape.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Fit an existing image into a new shape.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+
25
+ # build-in modules
26
+ import os
27
+
28
+ # third-party modules
29
+ import numpy
30
+
31
+ # own modules
32
+ from medpy.core import Logger
33
+ from medpy.io import load, save
34
+ from medpy.utilities import argparseu
35
+
36
+ # information
37
+ __author__ = "Oskar Maier"
38
+ __version__ = "r0.1.0, 2014-11-25"
39
+ __email__ = "oskar.maier@googlemail.com"
40
+ __status__ = "Release"
41
+ __description__ = """
42
+ Fit an existing image into a new shape.
43
+
44
+ If larger, the original image is placed centered in all dimensions. If smaller,
45
+ it is cut equally at all sides.
46
+
47
+ Copyright (C) 2013 Oskar Maier
48
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
49
+ and you are welcome to redistribute it under certain conditions; see
50
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
51
+ """
52
+
53
+
54
+ # code
55
+ def main():
56
+ parser = getParser()
57
+ args = getArguments(parser)
58
+
59
+ # prepare logger
60
+ logger = Logger.getInstance()
61
+ if args.debug:
62
+ logger.setLevel(logging.DEBUG)
63
+ elif args.verbose:
64
+ logger.setLevel(logging.INFO)
65
+
66
+ # loading input images
67
+ img, hdr = load(args.input)
68
+
69
+ # check shape dimensionality
70
+ if not len(args.shape) == img.ndim:
71
+ parser.error(
72
+ "The image has {} dimensions, but {} shape parameters have been supplied.".format(
73
+ img.ndim, len(args.shape)
74
+ )
75
+ )
76
+
77
+ # check if output image exists
78
+ if not args.force and os.path.exists(args.output):
79
+ parser.error("The output image {} already exists.".format(args.output))
80
+
81
+ # compute required cropping and extention
82
+ slicers_cut = []
83
+ slicers_extend = []
84
+ for dim in range(len(img.shape)):
85
+ slicers_cut.append(slice(None))
86
+ slicers_extend.append(slice(None))
87
+ if args.shape[dim] != img.shape[dim]:
88
+ difference = abs(img.shape[dim] - args.shape[dim])
89
+ cutoff_left = difference / 2
90
+ cutoff_right = difference / 2 + difference % 2
91
+ if args.shape[dim] > img.shape[dim]:
92
+ slicers_extend[-1] = slice(cutoff_left, -1 * cutoff_right)
93
+ else:
94
+ slicers_cut[-1] = slice(cutoff_left, -1 * cutoff_right)
95
+
96
+ # crop original image
97
+ img = img[tuple(slicers_cut)]
98
+
99
+ # create output image and place input image centered
100
+ out = numpy.zeros(args.shape, img.dtype)
101
+ out[tuple(slicers_extend)] = img
102
+
103
+ # saving the resulting image
104
+ save(out, args.output, hdr, args.force)
105
+
106
+
107
+ def getArguments(parser):
108
+ "Provides additional validation of the arguments collected by argparse."
109
+ return parser.parse_args()
110
+
111
+
112
+ def getParser():
113
+ "Creates and returns the argparse parser object."
114
+ parser = argparse.ArgumentParser(
115
+ formatter_class=argparse.RawDescriptionHelpFormatter,
116
+ description=__description__,
117
+ )
118
+ parser.add_argument("input", help="the input image")
119
+ parser.add_argument("output", help="the output image")
120
+ parser.add_argument(
121
+ "shape",
122
+ type=argparseu.sequenceOfIntegersGt,
123
+ help="the desired shape in colon-separated values, e.g. 255,255,32",
124
+ )
125
+
126
+ parser.add_argument(
127
+ "-v", "--verbose", dest="verbose", action="store_true", help="verbose output"
128
+ )
129
+ parser.add_argument(
130
+ "-d", dest="debug", action="store_true", help="Display debug information."
131
+ )
132
+ parser.add_argument(
133
+ "-f",
134
+ "--force",
135
+ dest="force",
136
+ action="store_true",
137
+ help="overwrite existing files",
138
+ )
139
+ return parser
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
medpy/source/bin/medpy_gradient.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Executes gradient magnitude filter over images.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ # build-in modules
23
+ import argparse
24
+ import logging
25
+
26
+ # third-party modules
27
+ import numpy
28
+ from scipy.ndimage import generic_gradient_magnitude, prewitt
29
+
30
+ from medpy.core import Logger
31
+
32
+ # own modules
33
+ from medpy.io import load, save
34
+
35
+ # path changes
36
+
37
+
38
+ # information
39
+ __author__ = "Oskar Maier"
40
+ __version__ = "r0.2.0, 2011-12-12"
41
+ __email__ = "oskar.maier@googlemail.com"
42
+ __status__ = "Release"
43
+ __description__ = """
44
+ Creates a height map of the input images using the gradient magnitude
45
+ filter.
46
+ The pixel type of the resulting image will be float.
47
+
48
+ Copyright (C) 2013 Oskar Maier
49
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
50
+ and you are welcome to redistribute it under certain conditions; see
51
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
52
+ """
53
+
54
+
55
+ # code
56
+ def main():
57
+ # parse cmd arguments
58
+ parser = getParser()
59
+ parser.parse_args()
60
+ args = getArguments(parser)
61
+
62
+ # prepare logger
63
+ logger = Logger.getInstance()
64
+ if args.debug:
65
+ logger.setLevel(logging.DEBUG)
66
+ elif args.verbose:
67
+ logger.setLevel(logging.INFO)
68
+
69
+ # laod input image
70
+ data_input, header_input = load(args.input)
71
+
72
+ # # check if output image exists
73
+ # if not args.force:
74
+ # if os.path.exists(image_gradient_name):
75
+ # logger.warning('The output image {} already exists. Skipping this step.'.format(image_gradient_name))
76
+ # continue
77
+
78
+ # prepare result image
79
+ data_output = numpy.zeros(data_input.shape, dtype=numpy.float32)
80
+
81
+ # apply the gradient magnitude filter
82
+ logger.info("Computing the gradient magnitude with Prewitt operator...")
83
+ generic_gradient_magnitude(
84
+ data_input, prewitt, output=data_output
85
+ ) # alternative to prewitt is sobel
86
+
87
+ # save resulting mask
88
+ save(data_output, args.output, header_input, args.force)
89
+
90
+ logger.info("Successfully terminated.")
91
+
92
+
93
+ def getArguments(parser):
94
+ "Provides additional validation of the arguments collected by argparse."
95
+ return parser.parse_args()
96
+
97
+
98
+ def getParser():
99
+ "Creates and returns the argparse parser object."
100
+ parser = argparse.ArgumentParser(description=__description__)
101
+ parser.add_argument("input", help="Source volume.")
102
+ parser.add_argument("output", help="Target volume.")
103
+ parser.add_argument(
104
+ "-v", dest="verbose", action="store_true", help="Display more information."
105
+ )
106
+ parser.add_argument(
107
+ "-d", dest="debug", action="store_true", help="Display debug information."
108
+ )
109
+ parser.add_argument(
110
+ "-f",
111
+ dest="force",
112
+ action="store_true",
113
+ help="Silently override existing output images.",
114
+ )
115
+
116
+ return parser
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()
medpy/source/bin/medpy_graphcut_label.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Execute a graph cut on a region image based on some foreground and background markers.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+ import os
25
+
26
+ # build-in modules
27
+ from argparse import RawTextHelpFormatter
28
+
29
+ # third-party modules
30
+ import numpy
31
+
32
+ from medpy import filter, graphcut
33
+
34
+ # own modules
35
+ from medpy.core import ArgumentError, Logger
36
+ from medpy.graphcut.wrapper import split_marker
37
+ from medpy.io import load, save
38
+
39
+ # path changes
40
+
41
+
42
+ # information
43
+ __author__ = "Oskar Maier"
44
+ __version__ = "r0.4.4, 2012-03-16"
45
+ __email__ = "oskar.maier@googlemail.com"
46
+ __status__ = "Release"
47
+ __description__ = """
48
+ Perform a binary graph cut using Boykov's max-flow/min-cut algorithm.
49
+
50
+ This implementation does only compute a boundary term and does not use
51
+ any regional term. The desired boundary term can be selected via the
52
+ --boundary argument. Depending on the selected term, an additional
53
+ image has to be supplied as badditional.
54
+
55
+ In the case of the stawiaski boundary term, this is the gradient image.
56
+ In the case of the difference of means, it is the original image.
57
+
58
+ Furthermore the algorithm requires the region map of the original
59
+ image and an integer image with foreground and background markers.
60
+
61
+ Additionally a filename for the created binary mask marking foreground
62
+ and background has to be supplied.
63
+
64
+ Note that the input images must be of the same dimensionality,
65
+ otherwise an exception is thrown.
66
+ Note to take into account the input images orientation.
67
+ Note that the quality of the resulting segmentations depends also on
68
+ the quality of the supplied markers.
69
+
70
+ Copyright (C) 2013 Oskar Maier
71
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
72
+ and you are welcome to redistribute it under certain conditions; see
73
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
74
+ """
75
+
76
+
77
+ # code
78
+ def main():
79
+ # parse cmd arguments
80
+ parser = getParser()
81
+ parser.parse_args()
82
+ args = getArguments(parser)
83
+
84
+ # prepare logger
85
+ logger = Logger.getInstance()
86
+ if args.debug:
87
+ logger.setLevel(logging.DEBUG)
88
+ elif args.verbose:
89
+ logger.setLevel(logging.INFO)
90
+
91
+ # check if output image exists
92
+ if not args.force:
93
+ if os.path.exists(args.output):
94
+ logger.warning(
95
+ "The output image {} already exists. Exiting.".format(args.output)
96
+ )
97
+ exit(-1)
98
+
99
+ # select boundary term
100
+ if args.boundary == "stawiaski":
101
+ boundary_term = graphcut.energy_label.boundary_stawiaski
102
+ logger.info("Selected boundary term: stawiaski")
103
+ else:
104
+ boundary_term = graphcut.energy_label.boundary_difference_of_means
105
+ logger.info("Selected boundary term: difference of means")
106
+
107
+ # load input images
108
+ region_image_data, reference_header = load(args.region)
109
+ badditional_image_data, _ = load(args.badditional)
110
+ markers_image_data, _ = load(args.markers)
111
+
112
+ # split marker image into fg and bg images
113
+ fgmarkers_image_data, bgmarkers_image_data = split_marker(markers_image_data)
114
+
115
+ # check if all images dimensions are the same
116
+ if not (
117
+ badditional_image_data.shape
118
+ == region_image_data.shape
119
+ == fgmarkers_image_data.shape
120
+ == bgmarkers_image_data.shape
121
+ ):
122
+ logger.critical("Not all of the supplied images are of the same shape.")
123
+ raise ArgumentError("Not all of the supplied images are of the same shape.")
124
+
125
+ # recompute the label ids to start from id = 1
126
+ logger.info("Relabel input image...")
127
+ region_image_data = filter.relabel(region_image_data)
128
+
129
+ # generate graph
130
+ logger.info("Preparing graph...")
131
+ gcgraph = graphcut.graph_from_labels(
132
+ region_image_data,
133
+ fgmarkers_image_data,
134
+ bgmarkers_image_data,
135
+ boundary_term=boundary_term,
136
+ boundary_term_args=(badditional_image_data),
137
+ ) # second is directedness of graph , 0)
138
+
139
+ logger.info("Removing images that are not longer required from memory...")
140
+ del fgmarkers_image_data
141
+ del bgmarkers_image_data
142
+ del badditional_image_data
143
+
144
+ # execute min-cut
145
+ logger.info("Executing min-cut...")
146
+ maxflow = gcgraph.maxflow()
147
+ logger.debug("Maxflow is {}".format(maxflow))
148
+
149
+ # apply results to the region image
150
+ logger.info("Applying results...")
151
+ mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
152
+ mapping.extend(
153
+ [
154
+ 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1
155
+ for x in numpy.unique(region_image_data)
156
+ ]
157
+ )
158
+ region_image_data = filter.relabel_map(region_image_data, mapping)
159
+
160
+ # save resulting mask
161
+ save(
162
+ region_image_data.astype(numpy.bool_), args.output, reference_header, args.force
163
+ )
164
+
165
+ logger.info("Successfully terminated.")
166
+
167
+
168
+ def getArguments(parser):
169
+ "Provides additional validation of the arguments collected by argparse."
170
+ return parser.parse_args()
171
+
172
+
173
+ def getParser():
174
+ "Creates and returns the argparse parser object."
175
+ parser = argparse.ArgumentParser(
176
+ description=__description__, formatter_class=RawTextHelpFormatter
177
+ )
178
+
179
+ parser.add_argument(
180
+ "badditional",
181
+ help="The additional image required by the boundary term. See there for details.",
182
+ )
183
+ parser.add_argument("region", help="The region image of the image to segment.")
184
+ parser.add_argument(
185
+ "markers",
186
+ help="Binary image containing the foreground (=1) and background (=2) markers.",
187
+ )
188
+ parser.add_argument("output", help="The output image containing the segmentation.")
189
+ parser.add_argument(
190
+ "--boundary",
191
+ default="stawiaski",
192
+ help="The boundary term to use. Note that difference of means (means) requires the original image, while stawiaski requires the gradient image of the original image to be passed to badditional.",
193
+ choices=["means", "stawiaski"],
194
+ )
195
+ parser.add_argument(
196
+ "-f",
197
+ dest="force",
198
+ action="store_true",
199
+ help="Set this flag to silently override files that exist.",
200
+ )
201
+ parser.add_argument(
202
+ "-v", dest="verbose", action="store_true", help="Display more information."
203
+ )
204
+ parser.add_argument(
205
+ "-d", dest="debug", action="store_true", help="Display debug information."
206
+ )
207
+
208
+ return parser
209
+
210
+
211
+ if __name__ == "__main__":
212
+ main()
medpy/source/bin/medpy_graphcut_label_bgreduced.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Execute a graph cut on a region image based on some foreground and background markers.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import itertools
24
+ import logging
25
+ import os
26
+
27
+ # build-in modules
28
+ from argparse import RawTextHelpFormatter
29
+
30
+ # third-party modules
31
+ import numpy
32
+ from scipy import ndimage
33
+
34
+ from medpy import filter, graphcut
35
+
36
+ # own modules
37
+ from medpy.core import ArgumentError, Logger
38
+ from medpy.graphcut.wrapper import split_marker
39
+ from medpy.io import load, save
40
+
41
+ # path changes
42
+
43
+
44
+ # information
45
+ __author__ = "Oskar Maier"
46
+ __version__ = "r0.3.4, 2012-03-16"
47
+ __email__ = "oskar.maier@googlemail.com"
48
+ __status__ = "Release"
49
+ __description__ = """
50
+ !Modified version of original GC label, as reduces the volume sizes
51
+ using the background markers.
52
+
53
+ Perform a binary graph cut using Boykov's max-flow/min-cut algorithm.
54
+
55
+ This implementation does only compute a boundary term and does not use
56
+ any regional term. The desired boundary term can be selected via the
57
+ --boundary argument. Depending on the selected term, an additional
58
+ image has to be supplied as badditional.
59
+
60
+ In the case of the stawiaski boundary term, this is the gradient image.
61
+ In the case of the difference of means, it is the original image.
62
+
63
+ Furthermore the algorithm requires the region map of the original
64
+ image, a binary image with foreground markers and a binary
65
+ image with background markers.
66
+
67
+ Additionally a filename for the created binary mask marking foreground
68
+ and background has to be supplied.
69
+
70
+ Note that the input images must be of the same dimensionality,
71
+ otherwise an exception is thrown.
72
+ Note to take into account the input images orientation.
73
+ Note that the quality of the resulting segmentations depends also on
74
+ the quality of the supplied markers.
75
+
76
+ Copyright (C) 2013 Oskar Maier
77
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
78
+ and you are welcome to redistribute it under certain conditions; see
79
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
80
+ """
81
+
82
+
83
+ # code
84
+ def main():
85
+ # parse cmd arguments
86
+ parser = getParser()
87
+ parser.parse_args()
88
+ args = getArguments(parser)
89
+
90
+ # prepare logger
91
+ logger = Logger.getInstance()
92
+ if args.debug:
93
+ logger.setLevel(logging.DEBUG)
94
+ elif args.verbose:
95
+ logger.setLevel(logging.INFO)
96
+
97
+ # check if output image exists
98
+ if not args.force:
99
+ if os.path.exists(args.output):
100
+ logger.warning(
101
+ "The output image {} already exists. Exiting.".format(args.output)
102
+ )
103
+ exit(-1)
104
+
105
+ # load input images
106
+ region_image_data, reference_header = load(args.region)
107
+ markers_image_data, _ = load(args.markers)
108
+ gradient_image_data, _ = load(args.gradient)
109
+
110
+ # split marker image into fg and bg images
111
+ logger.info("Extracting foreground and background markers...")
112
+ fgmarkers_image_data, bgmarkers_image_data = split_marker(markers_image_data)
113
+
114
+ # check if all images dimensions are the same shape
115
+ if not (
116
+ gradient_image_data.shape
117
+ == region_image_data.shape
118
+ == fgmarkers_image_data.shape
119
+ == bgmarkers_image_data.shape
120
+ ):
121
+ logger.critical("Not all of the supplied images are of the same shape.")
122
+ raise ArgumentError("Not all of the supplied images are of the same shape.")
123
+
124
+ # collect cut objects
125
+ cut_xy = __get_bg_bounding_pipe(bgmarkers_image_data)
126
+
127
+ # cut volumes
128
+ old_size = region_image_data.shape
129
+ gradient_image_data = gradient_image_data[cut_xy]
130
+ region_image_data = region_image_data[cut_xy]
131
+ fgmarkers_image_data = fgmarkers_image_data[cut_xy]
132
+ bgmarkers_image_data = bgmarkers_image_data[cut_xy]
133
+
134
+ # recompute the label ids to start from id = 1
135
+ logger.info("Relabel input image...")
136
+ region_image_data = filter.relabel(region_image_data)
137
+
138
+ # generate graph
139
+ logger.info("Preparing graph...")
140
+ gcgraph = graphcut.graph_from_labels(
141
+ region_image_data,
142
+ fgmarkers_image_data,
143
+ bgmarkers_image_data,
144
+ boundary_term=graphcut.energy_label.boundary_stawiaski,
145
+ boundary_term_args=(gradient_image_data),
146
+ ) # second is directedness of graph , 0)
147
+
148
+ logger.info("Removing images that are not longer required from memory...")
149
+ del fgmarkers_image_data
150
+ del bgmarkers_image_data
151
+ del gradient_image_data
152
+
153
+ # execute min-cut
154
+ logger.info("Executing min-cut...")
155
+ maxflow = gcgraph.maxflow()
156
+ logger.debug("Maxflow is {}".format(maxflow))
157
+
158
+ # apply results to the region image
159
+ logger.info("Applying results...")
160
+ mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
161
+ mapping.extend(
162
+ [
163
+ 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1
164
+ for x in numpy.unique(region_image_data)
165
+ ]
166
+ )
167
+ region_image_data = filter.relabel_map(region_image_data, mapping)
168
+
169
+ # generating final image by increasing the size again
170
+ output_image_data = numpy.zeros(old_size, dtype=numpy.bool_)
171
+ output_image_data[cut_xy] = region_image_data
172
+
173
+ # save resulting mask
174
+ save(output_image_data, args.output, reference_header, args.force)
175
+
176
+ logger.info("Successfully terminated.")
177
+
178
+
179
+ def __get_bg_bounding_pipe(bgmarkers):
180
+ # constants
181
+ xdim = 0
182
+ ydim = 1
183
+
184
+ # compute biggest bb in direction
185
+ bb = __xd_iterator_pass_on(bgmarkers, (xdim, ydim), __extract_bbox)
186
+
187
+ slicer = [slice(None)] * bgmarkers.ndim
188
+ slicer[xdim] = bb[0]
189
+ slicer[ydim] = bb[1]
190
+
191
+ return tuple(slicer)
192
+
193
+
194
+ def __xd_iterator_pass_on(arr, view, fun):
195
+ """
196
+ Like xd_iterator, but the fun return values are always passed on to the next and only the last returned.
197
+ """
198
+ # create list of iterations
199
+ iterations = [
200
+ [None] if dim in view else list(range(arr.shape[dim]))
201
+ for dim in range(arr.ndim)
202
+ ]
203
+
204
+ # iterate, create slicer, execute function and collect results
205
+ passon = None
206
+ for indices in itertools.product(*iterations):
207
+ slicer = [
208
+ slice(None) if idx is None else slice(idx, idx + 1) for idx in indices
209
+ ]
210
+ passon = fun(numpy.squeeze(arr[tuple(slicer)]), passon)
211
+
212
+ return passon
213
+
214
+
215
+ def __extract_bbox(arr, bb_old):
216
+ "Extracts the bounding box of an binary objects hole (assuming only one in existence)."
217
+ hole = ndimage.binary_fill_holes(arr) - arr
218
+ bb_list = ndimage.find_objects(ndimage.binary_dilation(hole, iterations=1))
219
+ if 0 == len(bb_list):
220
+ return bb_old
221
+ else:
222
+ bb = bb_list[0]
223
+
224
+ if not bb_old:
225
+ return list(bb)
226
+
227
+ for i in range(len(bb_old)):
228
+ bb_old[i] = slice(
229
+ min(bb_old[i].start, bb[i].start), max(bb_old[i].stop, bb[i].stop)
230
+ )
231
+ return tuple(bb_old)
232
+
233
+
234
+ def getArguments(parser):
235
+ "Provides additional validation of the arguments collected by argparse."
236
+ return parser.parse_args()
237
+
238
+
239
+ def getParser():
240
+ "Creates and returns the argparse parser object."
241
+ parser = argparse.ArgumentParser(
242
+ description=__description__, formatter_class=RawTextHelpFormatter
243
+ )
244
+
245
+ parser.add_argument(
246
+ "gradient", help="The gradient magnitude image of the image to segment."
247
+ )
248
+ parser.add_argument("region", help="The region image of the image to segment.")
249
+ parser.add_argument(
250
+ "markers",
251
+ help="Binary image containing the foreground (=1) and background (=2) markers.",
252
+ )
253
+ parser.add_argument("output", help="The output image containing the segmentation.")
254
+ parser.add_argument(
255
+ "-f",
256
+ dest="force",
257
+ action="store_true",
258
+ help="Set this flag to silently override files that exist.",
259
+ )
260
+ parser.add_argument(
261
+ "-v", dest="verbose", action="store_true", help="Display more information."
262
+ )
263
+ parser.add_argument(
264
+ "-d", dest="debug", action="store_true", help="Display debug information."
265
+ )
266
+
267
+ return parser
268
+
269
+
270
+ if __name__ == "__main__":
271
+ main()
medpy/source/bin/medpy_graphcut_label_w_regional.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Execute a graph cut on a region image based on some foreground and background markers.
5
+
6
+ Copyright (C) 2013 Oskar Maier
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+ import os
25
+
26
+ # build-in modules
27
+ from argparse import RawTextHelpFormatter
28
+
29
+ # third-party modules
30
+ import numpy
31
+
32
+ from medpy import filter, graphcut
33
+
34
+ # own modules
35
+ from medpy.core import ArgumentError, Logger
36
+ from medpy.graphcut.wrapper import split_marker
37
+ from medpy.io import load, save
38
+
39
+ # path changes
40
+
41
+
42
+ # information
43
+ __author__ = "Oskar Maier"
44
+ __version__ = "d0.2.1, 2012-07-31"
45
+ __email__ = "oskar.maier@googlemail.com"
46
+ __status__ = "Development"
47
+ __description__ = """
48
+ Perform a binary graph cut using Boykov's max-flow/min-cut algorithm.
49
+
50
+ This implementation does not only compute a boundary term but also a
51
+ regional term which. The only available implementation up till now is
52
+ the use of an atalas (i.e. a probability image of float values). The
53
+ pixel values have to lie between 0 and 1, whereas 1 denounces a sure
54
+ probability that the object is situated at this position. The desired
55
+ boundary term can be selected via the --boundary argument. Depending on
56
+ the selected term, an additional image has to be supplied as badditional.
57
+
58
+ In the case of the stawiaski boundary term, this is the gradient image.
59
+ In the case of the difference of means, it is the original image.
60
+
61
+ Furthermore the algorithm requires the region map of the original
62
+ image and an integer image with foreground and background markers.
63
+
64
+ Additionally a filename for the created binary mask marking foreground
65
+ and background has to be supplied.
66
+
67
+ Note that the input images must be of the same dimensionality,
68
+ otherwise an exception is thrown.
69
+ Note to take into account the input images orientation.
70
+ Note that the quality of the resulting segmentations depends also on
71
+ the quality of the supplied markers.
72
+
73
+ Copyright (C) 2013 Oskar Maier
74
+ This program comes with ABSOLUTELY NO WARRANTY; This is free software,
75
+ and you are welcome to redistribute it under certain conditions; see
76
+ the LICENSE file or <http://www.gnu.org/licenses/> for details.
77
+ """
78
+
79
+
80
+ # code
81
+ def main():
82
+ # parse cmd arguments
83
+ parser = getParser()
84
+ parser.parse_args()
85
+ args = getArguments(parser)
86
+
87
+ # prepare logger
88
+ logger = Logger.getInstance()
89
+ if args.debug:
90
+ logger.setLevel(logging.DEBUG)
91
+ elif args.verbose:
92
+ logger.setLevel(logging.INFO)
93
+
94
+ # check if output image exists
95
+ if not args.force:
96
+ if os.path.exists(args.output):
97
+ logger.warning(
98
+ "The output image {} already exists. Exiting.".format(args.output)
99
+ )
100
+ exit(-1)
101
+
102
+ # select boundary term
103
+ if args.boundary == "stawiaski":
104
+ boundary_term = graphcut.energy_label.boundary_stawiaski
105
+ logger.info("Selected boundary term: stawiaski")
106
+ else:
107
+ boundary_term = graphcut.energy_label.boundary_difference_of_means
108
+ logger.info("Selected boundary term: difference of means")
109
+
110
+ # select regional term
111
+ if args.regional == "atlas":
112
+ regional_term = graphcut.energy_label.regional_atlas
113
+ else:
114
+ regional_term = None
115
+
116
+ # load input images
117
+ region_image_data, reference_header = load(args.region)
118
+ markers_image_data, _ = load(args.markers)
119
+
120
+ # loading and splitting the marker image
121
+ fgmarkers_image_data, bgmarkers_image_data = split_marker(markers_image_data)
122
+
123
+ badditional_image_data, _ = load(args.badditional)
124
+
125
+ if "radditional" in args:
126
+ radditional_image_data, _ = load(args.radditional)
127
+ else:
128
+ radditional_image_data = False
129
+
130
+ # check if all images dimensions are the same
131
+ if not (
132
+ badditional_image_data.shape
133
+ == region_image_data.shape
134
+ == fgmarkers_image_data.shape
135
+ == bgmarkers_image_data.shape
136
+ ):
137
+ logger.critical("Not all of the supplied images are of the same shape.")
138
+ raise ArgumentError("Not all of the supplied images are of the same shape.")
139
+ if not bool == type(radditional_image_data):
140
+ if not (badditional_image_data.shape == radditional_image_data.shape):
141
+ logger.critical("Not all of the supplied images are of the same shape.")
142
+ raise ArgumentError("Not all of the supplied images are of the same shape.")
143
+
144
+ # recompute the label ids to start from id = 1
145
+ logger.info("Relabel input image...")
146
+ region_image_data = filter.relabel(region_image_data)
147
+
148
+ # generate graph
149
+ logger.info("Preparing graph...")
150
+ gcgraph = graphcut.graph_from_labels(
151
+ region_image_data,
152
+ fgmarkers_image_data,
153
+ bgmarkers_image_data,
154
+ regional_term=regional_term,
155
+ boundary_term=boundary_term,
156
+ regional_term_args=(radditional_image_data, args.alpha),
157
+ boundary_term_args=(badditional_image_data),
158
+ ) # second (optional) parameter is directedness of graph , 0)
159
+
160
+ logger.info("Removing images that are not longer required from memory...")
161
+ del fgmarkers_image_data
162
+ del bgmarkers_image_data
163
+ del radditional_image_data
164
+ del badditional_image_data
165
+
166
+ # execute min-cut
167
+ logger.info("Executing min-cut...")
168
+ maxflow = gcgraph.maxflow()
169
+ logger.debug("Maxflow is {}".format(maxflow))
170
+
171
+ # apply results to the region image
172
+ logger.info("Applying results...")
173
+ mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
174
+ mapping.extend(
175
+ [
176
+ 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1
177
+ for x in numpy.unique(region_image_data)
178
+ ]
179
+ )
180
+ region_image_data = filter.relabel_map(region_image_data, mapping)
181
+
182
+ # save resulting mask
183
+ save(
184
+ region_image_data.astype(numpy.bool_), args.output, reference_header, args.force
185
+ )
186
+
187
+ logger.info("Successfully terminated.")
188
+
189
+
190
+ def getArguments(parser):
191
+ "Provides additional validation of the arguments collected by argparse."
192
+ return parser.parse_args()
193
+
194
+
195
+ def getParser():
196
+ "Creates and returns the argparse parser object."
197
+ parser = argparse.ArgumentParser(
198
+ description=__description__, formatter_class=RawTextHelpFormatter
199
+ )
200
+
201
+ parser.add_argument(
202
+ "badditional",
203
+ help="The additional image required by the boundary term. See there for details.",
204
+ )
205
+ parser.add_argument("region", help="The region image of the image to segment.")
206
+ parser.add_argument(
207
+ "markers",
208
+ help="Binary image containing the foreground (=1) and background (=2) markers.",
209
+ )
210
+ parser.add_argument("output", help="The output image containing the segmentation.")
211
+ parser.add_argument(
212
+ "--boundary",
213
+ default="stawiaski",
214
+ help="The boundary term to use. Note that difference of means (means) requires the original image, while stawiaski requires the gradient image of the original image to be passed to badditional.",
215
+ choices=["means", "stawiaski"],
216
+ )
217
+ parser.add_argument(
218
+ "--regional",
219
+ default="none",
220
+ help="The regional term to use. Note that the atlas requires to provide an atlas image.",
221
+ choices=["none", "atlas"],
222
+ )
223
+ parser.add_argument(
224
+ "--radditional",
225
+ help="The additional image required by the regional term. See there for details.",
226
+ )
227
+ parser.add_argument(
228
+ "--alpha",
229
+ type=float,
230
+ help="The weight of the regional term compared to the boundary term.",
231
+ )
232
+ parser.add_argument(
233
+ "-f",
234
+ dest="force",
235
+ action="store_true",
236
+ help="Set this flag to silently override files that exist.",
237
+ )
238
+ parser.add_argument(
239
+ "-v", dest="verbose", action="store_true", help="Display more information."
240
+ )
241
+ parser.add_argument(
242
+ "-d", dest="debug", action="store_true", help="Display debug information."
243
+ )
244
+
245
+ return parser
246
+
247
+
248
+ if __name__ == "__main__":
249
+ main()