Beispiel #1
0
def test_types(img, n_rays):
    mode = "cpp"
    gt = star_dist(img, n_rays=n_rays, mode=mode)
    for dtype in (np.int8, np.int16, np.int32, np.uint8, np.uint16, np.uint32):
        x = star_dist(img.astype(dtype), n_rays=n_rays, mode=mode)
        print(
            "test_stardist2D (mode {mode}) for shape {img.shape} and type {dtype}"
            .format(mode=mode, img=img, dtype=dtype))
        check_similar(gt, x)
Beispiel #2
0
def test_grid(grid,shape):
    ss_grid = tuple(slice(0, None, g) for g in grid)
    lbl = circle_image(shape=shape, radius=min(shape)//3)

    n_rays = 32
    d1 = star_dist(lbl, n_rays=n_rays)
    d1 = d1[ss_grid]
    d2 = star_dist(lbl, n_rays=n_rays, grid=grid)

    assert np.allclose(d1,d2)
    return lbl, d1, d2
Beispiel #3
0
def test_acc(img, grid):
    prob = edt_prob(img)[::grid[0],::grid[1]]
    dist = star_dist(img, n_rays=32, mode="cpp")[::grid[0],::grid[1]]
    points, probi, disti = non_maximum_suppression(dist, prob, grid = grid, prob_thresh=0.4)
    img2 = polygons_to_label(disti, points, shape=img.shape)
    m = matching(img, img2)
    acc = m.accuracy
    print("accuracy {acc:.2f}".format(acc=acc))
    assert acc > 0.9
Beispiel #4
0
def test_bbox_search(img):
    prob = edt_prob(img)
    dist = star_dist(img, n_rays=32, mode="cpp")
    coord = dist_to_coord(dist)
    nms_a = non_maximum_suppression(
        coord, prob, prob_thresh=0.4, verbose=False, max_bbox_search=False)
    nms_b = non_maximum_suppression(
        coord, prob, prob_thresh=0.4, verbose=False, max_bbox_search=True)
    check_similar(nms_a, nms_b)
Beispiel #5
0
def test_acc(img):
    prob = edt_prob(img)
    dist = star_dist(img, n_rays=32, mode="cpp")
    coord = dist_to_coord(dist)
    points = non_maximum_suppression(coord, prob, prob_thresh=0.4)
    img2 = polygons_to_label(coord, prob, points, shape=img.shape)
    m = matching(img, img2)
    acc = m.accuracy
    print("accuracy {acc:.2f}".format(acc=acc))
    assert acc > 0.9
Beispiel #6
0
    def get_stardistances(self, labels):
        stardistances = np.zeros(
            (self.num_rays, labels.shape[1], labels.shape[2]), dtype="float32")

        for i in range(labels.shape[0]):
            stardistances += star_dist(labels[i],
                                       self.num_rays).transpose(2, 0, 1)

        stardistances[:, labels.sum(axis=0) > 1.5] = -1

        return stardistances
Beispiel #7
0
def test_acc_old(img, grid):
    from stardist.geometry.geom2d import _polygons_to_label_old, _dist_to_coord_old
    from stardist.nms import _non_maximum_suppression_old

    prob = edt_prob(img)[::grid[0],::grid[1]]
    dist = star_dist(img, n_rays=32, mode="cpp")[::grid[0],::grid[1]]
    coord = _dist_to_coord_old(dist, grid = grid)
    points = _non_maximum_suppression_old(coord, prob, prob_thresh=0.4, grid=grid)
    img2 = _polygons_to_label_old(coord, prob, points, shape=img.shape)
    m = matching(img, img2)
    acc = m.accuracy
    print("accuracy {acc:.2f}".format(acc=acc))
    assert acc > 0.9
Beispiel #8
0
def test_bbox_search_old(img):
    from stardist.geometry.geom2d import _polygons_to_label_old, _dist_to_coord_old
    from stardist.nms import _non_maximum_suppression_old

    prob = edt_prob(img)
    dist = star_dist(img, n_rays=32, mode="cpp")
    coord = _dist_to_coord_old(dist)
    points_a = _non_maximum_suppression_old(coord, prob, prob_thresh=0.4, verbose=False, max_bbox_search=False)
    points_b = _non_maximum_suppression_old(coord, prob, prob_thresh=0.4, verbose=False, max_bbox_search=True)
    img2_a = _polygons_to_label_old(coord, prob, points_a, shape=img.shape)
    img2_b = _polygons_to_label_old(coord, prob, points_b, shape=img.shape)
    check_similar(points_a, points_b)
    check_similar(img2_a, img2_b)
Beispiel #9
0
def sdist_volume(vol, n_directions, opencl_available=True):
    """
    returns the n-distances
    :param opencl_available:
    :param n_directions: number of directions
    :param vol: np-like 3d (z,y,x)

    :return: (n_directions, z, y, x)
    """
    directions = np.empty((n_directions, *vol.shape), dtype=np.float32)
    for z in range(vol.shape[0]):
        directions[:, z, :, :] = np.moveaxis(
            star_dist(vol[z], n_directions, opencl=opencl_available), -1, 0)

    return directions
Beispiel #10
0
 def __getitem__(self, idx):
     assert self.raw_files[idx] == self.target_files[idx]
     img_name = os.path.join(self.root_dir, 'images', self.raw_files[idx])
     image = io.imread(img_name)
     image = normalize(image, 1, 99.8, axis=(0, 1))
     image = np.expand_dims(image, 0)
     target_name = os.path.join(self.root_dir, 'masks',
                                self.target_files[idx])
     target = io.imread(target_name)
     distances = star_dist(target, self.n_rays, opencl=False)
     if self.max_dist:
         distances[distances > self.max_dist] = self.max_dist
     distances = np.transpose(distances, (2, 0, 1))
     obj_probabilities = edt_prob(target)
     obj_probabilities = np.expand_dims(obj_probabilities, 0)
     if self.transform:
         image = self.transform(image)
     if self.target_transform:
         distances = self.target_transform(distances)
         obj_probabilities = self.target_transform(obj_probabilities)
     return image, obj_probabilities, distances
Beispiel #11
0
import h5py
import numpy as np
from stardist import star_dist
import matplotlib.pyplot as plt

n_directions = 8

file = h5py.File('gt_cleaned.h5')
data = np.array(file['data'][:, :, :])

distances = np.empty((n_directions, *data.shape), dtype=np.int32)

for z in range(data.shape[0]):
    distances[:, z, :, :] = np.moveaxis(star_dist(data[z], 8), -1, 0)

print(distances.shape)

newfile = h5py.File('stardistance.h5', 'w')
newfile2 = h5py.File('stardistance_val.h5', 'w')

newfile.create_dataset('data', data=distances, dtype=np.float32)
newfile2.create_dataset('data', data=distances, dtype=np.float32)
Beispiel #12
0
def test_cpu_gpu(img, n_rays):
    s_cpp = star_dist(img, n_rays=n_rays, mode="cpp")
    s_ocl = star_dist(img, n_rays=n_rays, mode="opencl")
    check_similar(s_cpp, s_ocl)
 def batch_function(self, tensors):
     prediction, target = tensors
     target = np.moveaxis(star_dist(target[0].numpy(), N_DIRECTIONS, opencl=OPENCL_AVAILABLE), -1, 0)
     return prediction, target
BATCHSIZE = 8
N_DIRECTIONS = 8
OPENCL_AVAILABLE = True

class LabelToTarget(Transform):
    def __init__(self):
        super().__init__()

    def batch_function(self, tensors):
        prediction, target = tensors
        target = np.moveaxis(star_dist(target[0].numpy(), N_DIRECTIONS, opencl=OPENCL_AVAILABLE), -1, 0)
        return prediction, target

tosignedint = transforms.Lambda(lambda x: torch.tensor(np.int32(x), dtype=torch.int32))

sdist = transforms.Lambda(lambda x: np.moveaxis(star_dist(x[0], N_DIRECTIONS, opencl=OPENCL_AVAILABLE), -1, 0))
labeltotarget = transforms.Compose([sdist])

train_images = HDF5VolumeLoader(path='./train-volume.h5', path_in_h5_dataset='data',
                                **yaml2dict('config_train.yml')['slicing_config'])
train_labels = HDF5VolumeLoader(path='labeled_segmentation.h5', path_in_h5_dataset='data',
                                transforms=tosignedint, **yaml2dict('config_train.yml')['slicing_config'])
trainset = Zip(train_images, train_labels)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCHSIZE,
                                          shuffle=True, num_workers=2)


val_images = HDF5VolumeLoader(path='./val-volume.h5', path_in_h5_dataset='data',
                              **yaml2dict('config_val.yml')['slicing_config'])
val_labels = HDF5VolumeLoader(path='labeled_segmentation_validation.h5', path_in_h5_dataset='data',
                              transforms=tosignedint, **yaml2dict('config_val.yml')['slicing_config'])