-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtest_utils.py
1850 lines (1501 loc) · 60.3 KB
/
test_utils.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Test for utils."""
from __future__ import annotations
import hashlib
import os
import shutil
from pathlib import Path
from typing import TYPE_CHECKING, NoReturn
import cv2
import joblib
import numpy as np
import pandas as pd
import pytest
import torch
from PIL import Image
from requests import HTTPError
from shapely.geometry import Polygon
from tests.test_annotation_stores import cell_polygon
from tiatoolbox import rcParam, utils
from tiatoolbox.annotation.storage import DictionaryStore, SQLiteStore
from tiatoolbox.models.architecture import fetch_pretrained_weights
from tiatoolbox.models.architecture.utils import compile_model
from tiatoolbox.utils import misc
from tiatoolbox.utils.exceptions import FileNotSupportedError
from tiatoolbox.utils.transforms import locsize2bounds
if TYPE_CHECKING:
from tiatoolbox.type_hints import IntBounds
RNG = np.random.default_rng() # Numpy Random Generator
def sub_pixel_read(
test_image: np.ndarray,
pillow_test_image: Image,
bounds: IntBounds,
ow: int,
oh: int,
) -> None:
"""sub_pixel_read test helper function."""
output = utils.image.sub_pixel_read(
test_image,
bounds,
output_size=(ow, oh),
pad_at_baseline=False,
)
assert (ow, oh) == tuple(output.shape[:2][::-1])
output = utils.image.sub_pixel_read(
pillow_test_image,
bounds,
output_size=(ow, oh),
stride=[1, 1],
pad_at_baseline=False,
)
assert (ow, oh) == tuple(output.shape[:2][::-1])
def test_imresize() -> None:
"""Test for imresize."""
img = np.zeros((2000, 1000, 3))
resized_img = utils.transforms.imresize(img, scale_factor=0.5)
assert resized_img.shape == (1000, 500, 3)
resized_img = utils.transforms.imresize(resized_img, scale_factor=2.0)
assert resized_img.shape == (2000, 1000, 3)
resized_img = utils.transforms.imresize(
img,
scale_factor=0.5,
interpolation=cv2.INTER_CUBIC,
)
assert resized_img.shape == (1000, 500, 3)
# test for dtype conversion, pairs of
# (original type, converted type)
test_dtypes = [
(np.bool_, np.uint8),
(np.int8, np.int16),
(np.int16, np.int16),
(np.int32, np.float32),
(np.uint8, np.uint8),
(np.uint16, np.uint16),
(np.uint32, np.float32),
(np.int64, np.float64),
(np.uint64, np.float64),
(np.float16, np.float32),
(np.float32, np.float32),
(np.float64, np.float64),
]
img = np.zeros((100, 100, 3))
for original_dtype, converted_dtype in test_dtypes:
resized_img = utils.transforms.imresize(
img.astype(original_dtype),
scale_factor=0.5,
interpolation=cv2.INTER_CUBIC,
)
assert resized_img.shape == (50, 50, 3)
assert resized_img.dtype == converted_dtype
# test resizing multiple channels
img = RNG.integers(0, 256, (4, 4, 16))
resized_img = utils.transforms.imresize(
img,
scale_factor=4,
interpolation=cv2.INTER_CUBIC,
)
assert resized_img.shape == (16, 16, 16)
# test for not supporting dtype
img = RNG.integers(0, 256, (4, 4, 16))
with pytest.raises((AttributeError, ValueError), match=r".*float128.*"):
resized_img = utils.transforms.imresize(
img.astype(np.float128),
scale_factor=4,
interpolation=cv2.INTER_CUBIC,
)
def test_imresize_1x1() -> None:
"""Test imresize with 1x1 image."""
img = np.zeros((1, 1, 3))
resized_img = utils.transforms.imresize(img, scale_factor=10)
assert resized_img.shape == (10, 10, 3)
def test_imresize_no_scale_factor() -> None:
"""Test for imresize with no scale_factor given."""
img = np.zeros((2000, 1000, 3))
resized_img = utils.transforms.imresize(img, output_size=(50, 100))
assert resized_img.shape == (100, 50, 3)
resized_img = utils.transforms.imresize(img, output_size=100)
assert resized_img.shape == (100, 100, 3)
def test_imresize_no_scale_factor_or_output_size() -> None:
"""Test imresize with no scale_factor or output_size."""
img = np.zeros((2000, 1000, 3))
with pytest.raises(TypeError, match="One of scale_factor and output_size"):
utils.transforms.imresize(img)
def test_background_composite() -> None:
"""Test for background composite."""
new_im = np.zeros((2000, 2000, 4)).astype("uint8")
new_im[:1000, :, 3] = 255
im = utils.transforms.background_composite(new_im, alpha=False)
assert np.all(im[1000:, :, :] == 255)
assert np.all(im[:1000, :, :] == 0)
im = utils.transforms.background_composite(new_im, alpha=True)
assert np.all(im[:, :, 3] == 255)
new_im = Image.fromarray(new_im)
im = utils.transforms.background_composite(new_im, alpha=True)
assert np.all(im[:, :, 3] == 255)
def test_mpp2common_objective_power() -> None:
"""Test approximate conversion of mpp to objective power."""
mapping = [
(0.05, 100),
(0.07, 100),
(0.10, 100),
(0.12, 90),
(0.15, 60),
(0.29, 40),
(0.30, 40),
(0.49, 20),
(0.60, 20),
(1.00, 10),
(1.20, 10),
(2.00, 5),
(2.40, 4),
(3.00, 4),
(4.0, 2.5),
(4.80, 2),
(8.00, 1.25),
(9.00, 1),
]
for mpp, result in mapping:
assert utils.misc.mpp2common_objective_power(mpp) == result
assert np.array_equal(
utils.misc.mpp2common_objective_power([mpp] * 2),
[result] * 2,
)
def test_ppu2mpp_invalid_units() -> None:
"""Test ppu2mpp with invalid units."""
with pytest.raises(ValueError, match="Invalid units"):
utils.misc.ppu2mpp(1, units="invalid")
def test_ppu2mpp() -> None:
"""Test converting pixels-per-unit to mpp with ppu2mpp."""
assert utils.misc.ppu2mpp(1, units="in") == 25_400
assert utils.misc.ppu2mpp(1, units="inch") == 25_400
assert utils.misc.ppu2mpp(1, units="mm") == 1_000
assert utils.misc.ppu2mpp(1, units="cm") == 10_000
assert utils.misc.ppu2mpp(1, units=2) == 25_400 # inch
assert utils.misc.ppu2mpp(1, units=3) == 10_000 # cm
assert utils.misc.ppu2mpp(72, units="in") == pytest.approx(352.8, abs=0.1)
assert utils.misc.ppu2mpp(50_000, units="in") == pytest.approx(0.508, abs=0.1)
def test_assert_dtype_int() -> None:
"""Test AssertionError for dtype test."""
utils.misc.assert_dtype_int(input_var=np.array([1, 2]))
with pytest.raises(AssertionError):
utils.misc.assert_dtype_int(
input_var=np.array([1.0, 2]),
message="Bounds must be integers.",
)
def test_safe_padded_read_non_int_bounds() -> None:
"""Test safe_padded_read with non-integer bounds."""
data = np.zeros((16, 16))
bounds = (1.5, 1, 5, 5)
with pytest.raises(TypeError, match="integer"):
utils.image.safe_padded_read(data, bounds)
def test_safe_padded_read_negative_padding() -> None:
"""Test safe_padded_read with negative bounds."""
data = np.zeros((16, 16))
bounds = (1, 1, 5, 5)
with pytest.raises(ValueError, match="negative"):
utils.image.safe_padded_read(data, bounds, padding=-1)
def test_safe_padded_read_pad_mode_none() -> None:
"""Test safe_padded_read with pad_mode=None."""
data = np.zeros((16, 16))
bounds = (-5, -5, 5, 5)
region = utils.image.safe_padded_read(data, bounds, pad_mode=None)
assert region.shape == (5, 5)
def test_safe_padded_read_padding_formats() -> None:
"""Test safe_padded_read with different padding argument formats."""
data = np.zeros((16, 16))
bounds = (0, 0, 8, 8)
stride = (1, 1)
for padding in [1, [1], (1,), [1, 1], (1, 1), [1] * 4]:
region = utils.image.safe_padded_read(
data,
bounds,
padding=padding,
stride=stride,
)
assert region.shape == (8 + 2, 8 + 2)
def test_safe_padded_read_pad_kwargs(source_image: Path) -> None:
"""Test passing extra kwargs to safe_padded_read for np.pad."""
data = utils.imread(str(source_image))
bounds = (0, 0, 8, 8)
padding = 2
region = utils.image.safe_padded_read(
data,
bounds,
pad_mode="reflect",
padding=padding,
)
even_region = utils.image.safe_padded_read(
data,
bounds,
pad_mode="reflect",
padding=padding,
pad_kwargs={
"reflect_type": "even",
},
)
assert np.all(region == even_region)
odd_region = utils.image.safe_padded_read(
data,
bounds,
pad_mode="reflect",
padding=padding,
pad_kwargs={
"reflect_type": "odd",
},
)
assert not np.all(region == odd_region)
def test_safe_padded_read_pad_constant_values() -> None:
"""Test safe_padded_read with custom pad constant values.
This test creates an image of zeros and reads the whole image with a
padding of 1 and constant values of 10 for padding. It then checks
for a 1px border of 10s all the way around the zeros.
"""
for side_len in range(1, 5):
data = np.zeros((side_len, side_len))
bounds = (0, 0, side_len, side_len)
padding = 1
region = utils.image.safe_padded_read(
data,
bounds,
padding=padding,
pad_constant_values=10,
)
assert np.sum(region == 10) == (4 * side_len) + 4
def test_fuzz_safe_padded_read_edge_padding() -> None:
"""Fuzz test for padding at edges of an image.
This test creates a 16x16 image with a gradient from 1 to 17 across
it. A region is read using safe_padded_read with a constant padding
of 0 and an offset by some random 'shift' amount between 1 and 16.
The resulting image is checked for the correct number of 0 values.
"""
rng = np.random.default_rng(0)
for _ in range(1000):
data = np.repeat([range(1, 17)], 16, axis=0)
# Create bounds to fit the image and shift off by one
# randomly in x or y
sign = (-1) ** RNG.integers(0, 1)
axis = rng.integers(0, 1)
shift = np.tile([1 - axis, axis], 2)
shift_magnitude = rng.integers(1, 16)
bounds = np.array([0, 0, 16, 16]) + (shift * sign * shift_magnitude)
region = utils.image.safe_padded_read(data, bounds)
assert np.sum(region == 0) == (16 * shift_magnitude)
def test_fuzz_safe_padded_read() -> None:
"""Fuzz test for safe_padded_read."""
rng = np.random.default_rng(0)
for _ in range(1000):
data = rng.integers(0, 255, (16, 16))
loc = rng.integers(0, 16, 2)
size = (16, 16)
bounds = locsize2bounds(loc, size)
padding = RNG.integers(0, 16)
region = utils.image.safe_padded_read(data, bounds, padding=padding)
assert all(np.array(region.shape) == 16 + 2 * padding)
def test_safe_padded_read_padding_shape() -> None:
"""Test safe_padded_read for invalid padding shape."""
data = np.zeros((16, 16))
bounds = (1, 1, 5, 5)
with pytest.raises(ValueError, match="size 3"):
utils.image.safe_padded_read(data, bounds, padding=(1, 1, 1))
def test_safe_padded_read_stride_shape() -> None:
"""Test safe_padded_read for invalid stride size."""
data = np.zeros((16, 16))
bounds = (1, 1, 5, 5)
with pytest.raises(ValueError, match="size 1 or 2"):
utils.image.safe_padded_read(data, bounds, stride=(1, 1, 1))
def test_sub_pixel_read(source_image: Path) -> None:
"""Test sub-pixel numpy image reads with known tricky parameters."""
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
pillow_test_image = Image.fromarray(test_image)
x = 6
y = -4
w = 21.805648705868652
h = 0.9280264518437986
bounds = (x, y, x + w, y + h)
ow = 88
oh = 98
sub_pixel_read(test_image, pillow_test_image, bounds, ow, oh)
x = 13
y = 15
w = 29.46
h = 6.92
bounds = (x, y, x + w, y + h)
ow = 93
oh = 34
sub_pixel_read(test_image, pillow_test_image, bounds, ow, oh)
def test_aligned_padded_sub_pixel_read(source_image: Path) -> None:
"""Test sub-pixel numpy image reads with pixel-aligned bounds."""
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
x = 1
y = 1
w = 5
h = 5
padding = 1
bounds = (x, y, x + w, y + h)
ow = 4
oh = 4
output = utils.image.sub_pixel_read(
test_image,
bounds,
output_size=(ow, oh),
padding=padding,
pad_at_baseline=False,
)
assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1])
def test_sub_pixel_read_with_pad_kwargs(source_image: Path) -> None:
"""Test sub-pixel numpy image reads with pad kwargs."""
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
x = 1
y = 1
w = 5
h = 5
padding = 1
bounds = (x, y, x + w, y + h)
ow = 4
oh = 4
output = utils.image.sub_pixel_read(
test_image,
bounds,
(ow, oh),
padding=padding,
pad_mode="reflect",
pad_kwargs={"reflect_type": "even"},
pad_at_baseline=False,
)
assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1])
def test_non_aligned_padded_sub_pixel_read(source_image: Path) -> None:
"""Test sub-pixel numpy image reads with non-pixel-aligned bounds."""
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
x = 0.5
y = 0.5
w = 4
h = 4
for padding in [1, 2, 3]:
bounds = (x, y, x + w, y + h)
ow = 4
oh = 4
output = utils.image.sub_pixel_read(
test_image,
bounds,
(ow, oh),
padding=padding,
pad_at_baseline=False,
)
assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1])
def test_non_baseline_padded_sub_pixel_read(source_image: Path) -> None:
"""Test sub-pixel numpy image reads with baseline padding."""
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
x = 0.5
y = 0.5
w = 4
h = 4
for padding in [1, 2, 3]:
bounds = (x, y, x + w, y + h)
ow = 8
oh = 8
output = utils.image.sub_pixel_read(
test_image,
bounds,
(ow, oh),
padding=padding,
pad_at_baseline=True,
)
assert (ow + 2 * 2 * padding, oh + 2 * 2 * padding) == tuple(
output.shape[:2][::-1],
)
def test_sub_pixel_read_pad_mode_none() -> None:
"""Test sub_pixel_read with invalid interpolation."""
data = np.ones((16, 16))
bounds = (-1, -1, 5, 5)
region = utils.image.sub_pixel_read(
data,
bounds,
(6, 6),
pad_mode="none",
pad_at_baseline=False,
)
assert region.shape[:2] == (5, 5)
def test_sub_pixel_read_invalid_interpolation() -> None:
"""Test sub_pixel_read with invalid interpolation."""
data = np.zeros((16, 16))
out_size = data.shape
bounds = (1.5, 1, 5, 5)
with pytest.raises(ValueError, match="interpolation"):
utils.image.sub_pixel_read(
data,
bounds,
out_size,
interpolation="fizz",
pad_at_baseline=False,
)
def test_sub_pixel_read_invalid_bounds() -> None:
"""Test sub_pixel_read with invalid bounds."""
data = np.zeros((16, 16))
out_size = data.shape
bounds = (0, 0, 0, 0)
with pytest.raises(ValueError, match="Bounds must have non-zero size"):
utils.image.sub_pixel_read(data, bounds, out_size, pad_at_baseline=False)
bounds = (1.5, 1, 1.5, 0)
with pytest.raises(ValueError, match="Bounds must have non-zero size"):
utils.image.sub_pixel_read(data, bounds, out_size, pad_at_baseline=False)
def test_sub_pixel_read_pad_at_baseline() -> None:
"""Test sub_pixel_read with baseline padding."""
data = np.zeros((16, 16))
out_size = data.shape
bounds = (0, 0, 8, 8)
for padding in range(3):
region = utils.image.sub_pixel_read(
data,
bounds,
output_size=out_size,
padding=padding,
pad_at_baseline=True,
)
assert region.shape == (16 + 4 * padding, 16 + 4 * padding)
region = utils.image.sub_pixel_read(
data,
bounds,
out_size,
pad_at_baseline=True,
read_func=utils.image.safe_padded_read,
)
assert region.shape == (16, 16)
def test_sub_pixel_read_bad_read_func() -> None:
"""Test sub_pixel_read with read_func returning None."""
data = np.zeros((16, 16))
out_size = data.shape
bounds = (0, 0, 8, 8)
def bad_read_func(
img: np.ndarray, # noqa: ARG001
bounds: IntBounds, # noqa: ARG001
*kwargs: dict, # noqa: ARG001
) -> None:
"""Dummy function for a failing test."""
return
with pytest.raises(ValueError, match="None"):
utils.image.sub_pixel_read(
data,
bounds,
out_size,
read_func=bad_read_func,
pad_at_baseline=False,
)
def test_sub_pixel_read_padding_formats() -> None:
"""Test sub_pixel_read with different padding argument formats."""
data = np.zeros((16, 16))
out_size = data.shape
bounds = (0, 0, 8, 8)
for padding in [1, [1], (1,), [1, 1], (1, 1), [1] * 4]:
region = utils.image.sub_pixel_read(
data,
bounds,
out_size,
padding=padding,
pad_at_baseline=True,
)
assert region.shape == (16 + 4, 16 + 4)
region = utils.image.sub_pixel_read(
data,
bounds,
out_size,
padding=padding,
pad_at_baseline=False,
)
assert region.shape == (16 + 2, 16 + 2)
def test_sub_pixel_read_negative_size_bounds(source_image: Path) -> None:
"""Test sub_pixel_read with different padding argument formats."""
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
ow = 25
oh = 25
x = 5
y = 5
w = -4.5
h = -4.5
bounds = locsize2bounds((x, y), (w, h))
output = utils.image.sub_pixel_read(
test_image,
bounds,
(ow, oh),
pad_at_baseline=False,
)
x = 0.5
y = 0.5
w = 4.5
h = 4.5
bounds = locsize2bounds((x, y), (w, h))
print(bounds)
flipped_output = utils.image.sub_pixel_read(
test_image,
bounds,
(ow, oh),
pad_at_baseline=False,
)
assert np.all(np.fliplr(np.flipud(flipped_output)) == output)
def test_fuzz_sub_pixel_read(source_image: Path) -> None:
"""Fuzz test for numpy sub-pixel image reads."""
rng = np.random.default_rng(0)
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
test_size = 10000
all_x = rng.integers(-5, 32 - 5, size=test_size)
all_y = rng.integers(-5, 32 - 5, size=test_size)
all_w = rng.random(size=test_size) * rng.integers(1, 32, size=test_size)
all_h = rng.random(size=test_size) * rng.integers(1, 32, size=test_size)
all_ow = rng.integers(4, 128, size=test_size)
all_oh = rng.integers(4, 128, size=test_size)
for i in range(test_size):
x = all_x[i]
y = all_y[i]
w = all_w[i]
h = all_h[i]
bounds = (x, y, x + w, y + h)
ow = all_ow[i]
oh = all_oh[i]
output = utils.image.sub_pixel_read(
test_image,
bounds,
output_size=(ow, oh),
interpolation="linear",
pad_at_baseline=False,
)
assert (ow, oh) == tuple(output.shape[:2][::-1])
def test_fuzz_padded_sub_pixel_read(source_image: Path) -> None:
"""Fuzz test for numpy sub-pixel image reads with padding."""
rng = np.random.default_rng(0)
image_path = Path(source_image)
assert image_path.exists()
test_image = utils.imread(image_path)
for _ in range(10000):
x = rng.integers(-5, 32 - 5)
y = rng.integers(-5, 32 - 5)
w = 4 + rng.random() * rng.integers(1, 32)
h = 4 + rng.random() * rng.integers(1, 32)
padding = rng.integers(0, 2)
bounds = (x, y, x + w, y + h)
ow = rng.integers(4, 128)
oh = rng.integers(4, 128)
output = utils.image.sub_pixel_read(
test_image,
bounds,
(ow, oh),
interpolation="linear",
padding=padding,
pad_kwargs={"constant_values": 0},
pad_at_baseline=False,
)
assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1])
def test_sub_pixel_read_interpolation_modes() -> None:
"""Test sub_pixel_read with different padding argument formats."""
data = np.mgrid[:16:1, :16:1].sum(0).astype(np.uint8)
out_size = data.shape
bounds = (0, 0, 8, 8)
for mode in ["nearest", "linear", "cubic", "lanczos"]:
output = utils.image.sub_pixel_read(
data,
bounds,
out_size,
interpolation=mode,
pad_at_baseline=False,
)
assert output.shape == out_size
def test_sub_pixel_read_incorrect_read_func_return() -> None:
"""Test for sub pixel reading with incorrect read func return."""
bounds = (0, 0, 8, 8)
image = np.ones((10, 10))
def read_func(*args: tuple, **kwargs: dict) -> np.ndarray: # noqa: ARG001
"""Dummy read function for tests."""
return np.ones((5, 5))
with pytest.raises(ValueError, match="incorrect size"):
utils.image.sub_pixel_read(
image,
bounds=bounds,
output_size=(10, 10),
read_func=read_func,
pad_at_baseline=False,
)
def test_sub_pixel_read_empty_read_func_return() -> None:
"""Test for sub pixel reading with empty read func return."""
bounds = (0, 0, 8, 8)
image = np.ones((10, 10))
def read_func(*args: tuple, **kwargs: dict) -> np.ndarray: # noqa: ARG001
"""Dummy read function for tests."""
return np.ones((0, 0))
with pytest.raises(ValueError, match="is empty"):
utils.image.sub_pixel_read(
image,
bounds=bounds,
output_size=(10, 10),
read_func=read_func,
pad_at_baseline=False,
)
def test_sub_pixel_read_empty_bounds() -> None:
"""Test for sub pixel reading with empty bounds."""
bounds = (0, 0, 2, 2)
image = np.ones((10, 10))
with pytest.raises(ValueError, match="Bounds have zero size after padding."):
utils.image.sub_pixel_read(
image,
bounds=bounds,
output_size=(2, 2),
padding=-1,
pad_at_baseline=False,
)
def test_fuzz_bounds2locsize() -> None:
"""Fuzz test for bounds2size."""
rng = np.random.default_rng(0)
for _ in range(1000):
size = (rng.integers(-1000, 1000), rng.integers(-1000, 1000))
location = (rng.integers(-1000, 1000), rng.integers(-1000, 1000))
bounds = (*location, *(sum(x) for x in zip(size, location)))
assert utils.transforms.bounds2locsize(bounds)[1] == pytest.approx(size)
def test_fuzz_bounds2locsize_lower() -> None:
"""Fuzz test for bounds2size with origin lower."""
rng = np.random.default_rng(0)
for _ in range(1000):
loc = (rng.random(2) - 0.5) * 1000
size = (rng.random(2) - 0.5) * 1000
fuzz_bounds = [0, *size[::-1], 0] # L T R B
bounds = np.tile(loc, 2) + fuzz_bounds # L T R B
_, s = utils.transforms.bounds2locsize(bounds, origin="lower")
assert s == pytest.approx(size)
def test_fuzz_roundtrip_bounds2size() -> None:
"""Fuzz roundtrip bounds2locsize and locsize2bounds."""
rng = np.random.default_rng(0)
for _ in range(1000):
loc = (rng.random(2) - 0.5) * 1000
size = (rng.random(2) - 0.5) * 1000
assert utils.transforms.bounds2locsize(
utils.transforms.locsize2bounds(loc, size),
)
def test_bounds2size_value_error() -> None:
"""Test bounds to size ValueError."""
with pytest.raises(ValueError, match="Invalid origin"):
utils.transforms.bounds2locsize((0, 0, 1, 1), origin="middle")
def test_bounds2slices_invalid_stride() -> None:
"""Test bounds2slices raises ValueError with invalid stride."""
bounds = (0, 0, 10, 10)
with pytest.raises(ValueError, match="Invalid stride"):
utils.transforms.bounds2slices(bounds, stride=(1, 1, 1))
def test_pad_bounds_sample_cases() -> None:
"""Test sample inputs for pad_bounds."""
output = utils.transforms.pad_bounds([0] * 4, 1)
assert np.array_equal(output, (-1, -1, 1, 1))
output = utils.transforms.pad_bounds((0, 0, 10, 10), (1, 2))
assert np.array_equal(output, (-1, -2, 11, 12))
def test_pad_bounds_invalid_inputs() -> None:
"""Test invalid inputs for pad_bounds."""
with pytest.raises(ValueError, match="even"):
utils.transforms.pad_bounds(bounds=(0, 0, 10), padding=1)
with pytest.raises(ValueError, match="Invalid number of padding"):
utils.transforms.pad_bounds(bounds=(0, 0, 10, 10), padding=(1, 1, 1))
# Normal case for control
utils.transforms.pad_bounds(bounds=(0, 0, 10, 10), padding=1)
def test_contrast_enhancer() -> None:
"""Test contrast enhancement functionality."""
# input array to the contrast_enhancer function
input_array = np.array(
[
[[37, 244, 193], [106, 235, 128], [71, 140, 47]],
[[103, 184, 72], [20, 188, 238], [126, 7, 0]],
[[137, 195, 204], [32, 203, 170], [101, 77, 133]],
],
dtype=np.uint8,
)
# expected output of the contrast_enhancer
result_array = np.array(
[
[[35, 255, 203], [110, 248, 133], [72, 146, 46]],
[[106, 193, 73], [17, 198, 251], [131, 3, 0]],
[[143, 205, 215], [30, 214, 178], [104, 78, 139]],
],
dtype=np.uint8,
)
with pytest.raises(AssertionError):
# Contrast_enhancer requires image input to be of dtype uint8
utils.misc.contrast_enhancer(np.float32(input_array), low_p=2, high_p=98)
# Calculating the contrast enhanced version of input_array
output_array = utils.misc.contrast_enhancer(input_array, low_p=2, high_p=98)
# The out_put array should be equal to expected result_array
assert np.all(result_array == output_array)
def test_load_stain_matrix(tmp_path: Path) -> None:
"""Test to load stain matrix."""
with pytest.raises(FileNotSupportedError):
utils.misc.load_stain_matrix("/samplefile.xlsx")
with pytest.raises(TypeError):
# load_stain_matrix requires numpy array as input providing list here
utils.misc.load_stain_matrix([1, 2, 3])
stain_matrix = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11]])
pd.DataFrame(stain_matrix).to_csv(Path(tmp_path).joinpath("sm.csv"), index=False)
out_stain_matrix = utils.misc.load_stain_matrix(Path(tmp_path).joinpath("sm.csv"))
assert np.all(out_stain_matrix == stain_matrix)
np.save(str(Path(tmp_path).joinpath("sm.npy")), stain_matrix)
out_stain_matrix = utils.misc.load_stain_matrix(Path(tmp_path).joinpath("sm.npy"))
assert np.all(out_stain_matrix == stain_matrix)
def test_get_luminosity_tissue_mask() -> None:
"""Test get luminosity tissue mask."""
with pytest.raises(ValueError, match="Empty tissue mask"):
utils.misc.get_luminosity_tissue_mask(img=np.zeros((100, 100, 3)), threshold=0)
def test_read_point_annotations( # noqa: PLR0915
tmp_path: Path,
patch_extr_csv: Path,
patch_extr_csv_noheader: Path,
patch_extr_svs_csv: Path,
patch_extr_svs_header: Path,
patch_extr_npy: Path,
patch_extr_json: Path,
patch_extr_2col_json: Path,
) -> None:
"""Test read point annotations reads csv, ndarray, npy and json correctly."""
labels = Path(patch_extr_csv)
labels_table = pd.read_csv(labels)
# Test csv read with header
out_table = utils.misc.read_locations(labels)
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
# Test csv read without header
labels = Path(patch_extr_csv_noheader)
out_table = utils.misc.read_locations(labels)
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
labels = Path(patch_extr_svs_csv)
out_table = utils.misc.read_locations(labels)
assert out_table.shape[1] == 3
labels = Path(patch_extr_svs_header)
out_table = utils.misc.read_locations(labels)
assert out_table.shape[1] == 3
# Test npy read
labels = Path(patch_extr_npy)
out_table = utils.misc.read_locations(labels)
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
# Test pd dataframe read
out_table = utils.misc.read_locations(labels_table)
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
labels_table_2 = labels_table.drop("class", axis=1)
out_table = utils.misc.read_locations(labels_table_2)
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
# Test json read
labels = Path(patch_extr_json)
out_table = utils.misc.read_locations(labels)
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
# Test json read 2 columns
labels = Path(patch_extr_2col_json)
out_table = utils.misc.read_locations(labels)
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
# Test numpy array
out_table = utils.misc.read_locations(labels_table.to_numpy())
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
out_table = utils.misc.read_locations(labels_table.to_numpy()[:, 0:2])
assert all(labels_table == out_table)
assert out_table.shape[1] == 3
# Test if input array does not have 2 or 3 columns
with pytest.raises(ValueError, match="Numpy table should be of format"):
_ = utils.misc.read_locations(labels_table.to_numpy()[:, 0:1])
# Test if input npy does not have 2 or 3 columns
labels = tmp_path.joinpath("test_gt_3col.npy")
with Path.open(labels, "wb") as f:
np.save(f, np.zeros((3, 4)))
with pytest.raises(ValueError, match="Numpy table should be of format"):
_ = utils.misc.read_locations(labels)