File size: 1,773 Bytes
5d31c67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
812b6ee
 
 
5d31c67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np

from cellquant.annotations import RasterAnnotation
from cellquant.data import AugConfig, PatchSampler, make_targets


def _raster():
    inst = np.zeros((64, 64), np.int32)
    inst[10:30, 10:30] = 1
    inst[30:50, 30:50] = 2  # touches instance 1 at a corner
    nos = np.zeros((64, 64), np.int32)
    nos[20:23, 20:23] = 1
    nos[5:7, 50:52] = 2
    return RasterAnnotation(inst, ["", "Cell, Nostril, Antibody +", "Cell, Antibody -"], nos,
                            ["", "Nostril in Nucleus", "Nostril External of Nucleus"])


def test_make_targets_layout():
    T = make_targets(_raster())
    assert set(np.unique(T["cell3"])) == {0, 1, 2}
    assert ((T["cell3"] > 0) == (T["cellmask"] > 0)).all()
    # border ring is 3 px wide: a 20x20 square has 20*20 - 14*14 = 204 border px
    assert int((T["cell3"][10:30, 10:30] == 2).sum()) == 204
    assert T["dist"].shape == T["cell3"].shape and T["dist"].dtype == np.float32
    assert T["antibody"][15, 15] == 1 and T["antibody"][40, 40] == 0
    assert T["cellnos"][15, 15] == 1 and T["cellnos"][40, 40] == 0
    assert T["nos3"][21, 21] == 1 and T["nos3"][5, 50] == 2 and T["nos3"][0, 0] == 0


def test_sampler_batch_shapes_and_reproducibility():
    img = (np.random.default_rng(0).random((64, 64, 3)) * 255).astype(np.uint8)
    T = make_targets(_raster())
    cfg = AugConfig(crop=32)
    a = PatchSampler([img], [T], cfg, seed=3).batch(2)
    b = PatchSampler([img], [T], cfg, seed=3).batch(2)
    x, t = a
    assert x.shape == (2, 3, 32, 32) and x.min() >= 0 and x.max() <= 1
    assert t["cell3"].shape == (2, 32, 32) and t["cell3"].dtype.is_floating_point is False
    assert np.allclose(x.numpy(), b[0].numpy())
    assert all(np.array_equal(t[k].numpy(), b[1][k].numpy()) for k in t)