-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtest_tissuemask.py
487 lines (404 loc) · 14.6 KB
/
test_tissuemask.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
"""Test for code related to tissue mask generation."""
import os
from pathlib import Path
import cv2
import numpy as np
import pytest
from click.testing import CliRunner
from tiatoolbox import cli
from tiatoolbox.tools import tissuemask
from tiatoolbox.utils.env_detection import running_on_ci
from tiatoolbox.wsicore import wsireader
# -------------------------------------------------------------------------------------
# Tests
# -------------------------------------------------------------------------------------
def test_otsu_masker(sample_svs: Path) -> None:
"""Test Otsu's thresholding method."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
mpp = 32
thumb = wsi.slide_thumbnail(mpp, "mpp")
masker = tissuemask.OtsuTissueMasker()
mask_a = masker.fit_transform([thumb])[0]
masker.fit([thumb])
mask_b = masker.transform([thumb])[0]
assert np.array_equal(mask_a, mask_b)
assert masker.threshold is not None
assert len(np.unique(mask_a)) == 2
assert mask_a.shape == thumb.shape[:2]
def test_otsu_greyscale_masker(sample_svs: Path) -> None:
"""Test Otsu's thresholding method with greyscale inputs."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
mpp = 32
thumb = wsi.slide_thumbnail(mpp, "mpp")
thumb = cv2.cvtColor(thumb, cv2.COLOR_RGB2GRAY)
inputs = thumb[np.newaxis, ..., np.newaxis]
masker = tissuemask.OtsuTissueMasker()
mask_a = masker.fit_transform(inputs)[0]
masker.fit(inputs)
mask_b = masker.transform(inputs)[0]
assert np.array_equal(mask_a, mask_b)
assert masker.threshold is not None
assert len(np.unique(mask_a)) == 2
assert mask_a.shape == thumb.shape[:2]
def test_morphological_masker(sample_svs: Path) -> None:
"""Test simple morphological thresholding."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
thumb = wsi.slide_thumbnail()
masker = tissuemask.MorphologicalMasker()
mask_a = masker.fit_transform([thumb])[0]
masker.fit([thumb])
mask_b = masker.transform([thumb])[0]
assert np.array_equal(mask_a, mask_b)
assert masker.threshold is not None
assert len(np.unique(mask_a)) == 2
assert mask_a.shape == thumb.shape[:2]
def test_morphological_greyscale_masker(sample_svs: Path) -> None:
"""Test morphological masker with greyscale inputs."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
mpp = 32
thumb = wsi.slide_thumbnail(mpp, "mpp")
thumb = cv2.cvtColor(thumb, cv2.COLOR_RGB2GRAY)
inputs = thumb[np.newaxis, ..., np.newaxis]
masker = tissuemask.MorphologicalMasker()
mask_a = masker.fit_transform(inputs)[0]
masker.fit(inputs)
mask_b = masker.transform(inputs)[0]
assert np.array_equal(mask_a, mask_b)
assert masker.threshold is not None
assert len(np.unique(mask_a)) == 2
assert mask_a.shape == thumb.shape[:2]
def test_morphological_masker_int_kernel_size(sample_svs: Path) -> None:
"""Test simple morphological thresholding with mpp with int kernel_size."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
mpp = 32
thumb = wsi.slide_thumbnail(mpp, "mpp")
masker = tissuemask.MorphologicalMasker(kernel_size=5)
mask_a = masker.fit_transform([thumb])[0]
masker.fit([thumb])
mask_b = masker.transform([thumb])[0]
assert np.array_equal(mask_a, mask_b)
assert masker.threshold is not None
assert len(np.unique(mask_a)) == 2
assert mask_a.shape == thumb.shape[:2]
def test_morphological_masker_mpp(sample_svs: Path) -> None:
"""Test simple morphological thresholding with mpp."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
mpp = 32
thumb = wsi.slide_thumbnail(mpp, "mpp")
kwarg_sets = [
{"mpp": mpp},
{"mpp": [mpp, mpp]},
]
for kwargs in kwarg_sets:
masker = tissuemask.MorphologicalMasker(**kwargs)
mask_a = masker.fit_transform([thumb])[0]
masker.fit([thumb])
mask_b = masker.transform([thumb])[0]
assert np.array_equal(mask_a, mask_b)
assert masker.threshold is not None
assert len(np.unique(mask_a)) == 2
assert mask_a.shape == thumb.shape[:2]
def test_morphological_masker_power(sample_svs: Path) -> None:
"""Test simple morphological thresholding with objective power."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
power = 1.25
thumb = wsi.slide_thumbnail(power, "power")
masker = tissuemask.MorphologicalMasker(power=power)
mask_a = masker.fit_transform([thumb])[0]
masker.fit([thumb])
mask_b = masker.transform([thumb])[0]
assert np.array_equal(mask_a, mask_b)
assert masker.threshold is not None
assert len(np.unique(mask_a)) == 2
assert mask_a.shape == thumb.shape[:2]
def test_transform_before_fit_otsu() -> None:
"""Test otsu masker error on transform before fit."""
image = np.ones((1, 10, 10))
masker = tissuemask.OtsuTissueMasker()
with pytest.raises(SyntaxError, match="Fit must be called before transform."):
masker.transform([image])[0]
def test_transform_before_fit_morphological() -> None:
"""Test morphological masker error on transform before fit."""
image = np.ones((1, 10, 10))
masker = tissuemask.MorphologicalMasker()
with pytest.raises(SyntaxError, match="Fit must be called before transform."):
masker.transform([image])[0]
def test_transform_fit_otsu_wrong_shape() -> None:
"""Test giving the incorrect input shape to otsu masker."""
image = np.ones((10, 10))
masker = tissuemask.OtsuTissueMasker()
with pytest.raises(ValueError, match="Expected 4 dimensional input shape *"):
masker.fit([image])
def test_transform_morphological_conflicting_args() -> None:
"""Test giving conflicting arguments to morphological masker."""
with pytest.raises(
ValueError,
match="Only one of mpp, power, kernel_size can be given.",
):
tissuemask.MorphologicalMasker(mpp=32, power=1.25)
def test_morphological_kernel_size_none() -> None:
"""Test giveing a None kernel size for morphological masker."""
tissuemask.MorphologicalMasker(kernel_size=None)
def test_morphological_min_region_size() -> None:
"""Test morphological masker with min_region_size set.
Creates a test image (0=foreground, 1=background) and applies the
morphological masker with min_region_size=6. This should output
only the largest square region as foreground in the mask
(0=background, 1=foreground).
"""
# Create a blank image of ones
img = np.ones((10, 10))
# Create a large square region of 9 zeros
img[1:4, 1:4] = 0
# Create a row of 5 zeros
img[1, 5:10] = 0
# Create a single 0
img[8, 8] = 0
masker = tissuemask.MorphologicalMasker(kernel_size=1, min_region_size=6)
output = masker.fit_transform([img[..., np.newaxis]])
assert np.sum(output[0]) == 9
# Create the expected output with just the large square region
# but as ones against zeros (the mask is the inverse of the input).
expected = np.zeros((10, 10))
expected[1:4, 1:4] = 1
assert np.all(output[0] == expected)
@pytest.mark.skipif(running_on_ci(), reason="No display on CI.")
@pytest.mark.skipif(
not os.environ.get("SHOW_TESTS"),
reason="Visual tests disabled, set SHOW_TESTS to enable.",
)
def test_cli_tissue_mask_otsu_show(sample_svs: Path) -> None:
"""Test Otsu tissue masking with default input CLI and showing in a window."""
source_img = Path(sample_svs)
runner = CliRunner()
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Otsu",
"--mode",
"show",
],
)
assert tissue_mask_result.exit_code == 0
def test_cli_tissue_mask_otsu_save(sample_svs: Path) -> None:
"""Test Otsu tissue masking with default input CLI and saving to a file."""
source_img = Path(sample_svs)
runner = CliRunner()
output_path = str(Path(sample_svs.parent, "tissue_mask"))
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Otsu",
"--mode",
"save",
"--output-path",
output_path,
],
)
assert tissue_mask_result.exit_code == 0
assert Path(output_path, source_img.stem + ".png").is_file()
def test_cli_tissue_mask_otsu_dir_save(sample_all_wsis: Path) -> None:
"""Test Otsu tissue masking for multiple files with default input CLI."""
source_img = Path(sample_all_wsis)
runner = CliRunner()
output_path = str(Path(source_img, "tissue_mask"))
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Otsu",
"--mode",
"save",
"--output-path",
output_path,
],
)
assert tissue_mask_result.exit_code == 0
assert Path(output_path, "CMU-1-Small-Region.omnyx.png").is_file()
@pytest.mark.skipif(running_on_ci(), reason="No display on CI.")
@pytest.mark.skipif(
not os.environ.get("SHOW_TESTS"),
reason="Visual tests disabled, set SHOW_TESTS to enable.",
)
def test_cli_tissue_mask_morphological_show(sample_svs: Path) -> None:
"""Test Morphological tissue masking with default input CLI."""
source_img = Path(sample_svs)
runner = CliRunner()
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Morphological",
"--mode",
"show",
],
)
assert tissue_mask_result.exit_code == 0
def test_cli_tissue_mask_morphological_save(sample_svs: Path) -> None:
"""Test Morphological tissue masking with morphological method CLI."""
source_img = Path(sample_svs)
runner = CliRunner()
output_path = str(Path(sample_svs.parent, "tissue_mask"))
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Morphological",
"--mode",
"save",
"--output-path",
output_path,
],
)
assert tissue_mask_result.exit_code == 0
assert Path(output_path, source_img.stem + ".png").is_file()
def test_cli_tissue_mask_morphological_power_resolution_save(sample_svs: Path) -> None:
"""Test Morphological tissue masking with morphological method CLI.
Adds option to specify resolution and units in power (appmag).
"""
source_img = Path(sample_svs)
runner = CliRunner()
output_path = str(Path(sample_svs.parent, "tissue_mask"))
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Morphological",
"--mode",
"save",
"--output-path",
output_path,
"--resolution",
1.25,
"--units",
"power",
],
)
assert tissue_mask_result.exit_code == 0
assert Path(output_path, source_img.stem + ".png").is_file()
def test_cli_tissue_mask_morphological_mpp_resolution_save(sample_svs: Path) -> None:
"""Test Morphological tissue masking with morphological method CLI.
Adds option to specify resolution and units in mpp (micrometers per pixel).
"""
source_img = Path(sample_svs)
runner = CliRunner()
output_path = str(Path(sample_svs.parent, "tissue_mask"))
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Morphological",
"--mode",
"save",
"--output-path",
output_path,
"--resolution",
32,
"--units",
"mpp",
],
)
assert tissue_mask_result.exit_code == 0
assert Path(output_path, source_img.stem + ".png").is_file()
def test_cli_tissue_mask_morphological_kernel_size_save(sample_svs: Path) -> None:
"""Test Morphological tissue masking with morphological method CLI.
Adds option to specify kernel size.
"""
source_img = Path(sample_svs)
runner = CliRunner()
output_path = str(Path(sample_svs.parent, "tissue_mask"))
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Morphological",
"--mode",
"save",
"--output-path",
output_path,
"--kernel-size",
"1",
"1",
],
)
assert tissue_mask_result.exit_code == 0
assert Path(output_path, source_img.stem + ".png").is_file()
def test_cli_tissue_mask_method_not_supported(sample_svs: Path) -> None:
"""Test method not supported for the tissue masking CLI."""
source_img = Path(sample_svs)
runner = CliRunner()
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Test",
"--mode",
"save",
],
)
assert "Invalid value for '--method'" in tissue_mask_result.output
assert tissue_mask_result.exit_code != 0
assert isinstance(tissue_mask_result.exception, SystemExit)
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img),
"--method",
"Morphological",
"--resolution",
32,
"--units",
"level",
],
)
assert "Invalid value for '--units'" in tissue_mask_result.output
assert tissue_mask_result.exit_code != 0
assert isinstance(tissue_mask_result.exception, SystemExit)
def test_cli_tissue_mask_file_not_found_error(source_image: Path) -> None:
"""Test file not found error for the tissue masking CLI."""
source_img = Path(source_image)
runner = CliRunner()
tissue_mask_result = runner.invoke(
cli.main,
[
"tissue-mask",
"--img-input",
str(source_img)[:-1],
"--method",
"Otsu",
],
)
assert tissue_mask_result.output == ""
assert tissue_mask_result.exit_code == 1
assert isinstance(tissue_mask_result.exception, FileNotFoundError)