def test_2d_bf():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels_bf = random_walker(data, labels, beta=90, mode="bf")
    assert (labels_bf[25:45, 40:60] == 2).all()
    full_prob_bf = random_walker(data, labels, beta=90, mode="bf", return_full_prob=True)
    assert (full_prob_bf[1, 25:45, 40:60] >= full_prob_bf[0, 25:45, 40:60]).all()
    return data, labels_bf, full_prob_bf
def test_length2_spacing():
    # If this passes without raising an exception (warnings OK), the new
    #   spacing code is working properly.
    np.random.seed(42)
    img = np.ones((10, 10)) + 0.2 * np.random.normal(size=(10, 10))
    labels = np.zeros((10, 10), dtype=np.uint8)
    labels[2, 4] = 1
    labels[6, 8] = 4
    random_walker(img, labels, spacing=(1., 2.))
def test_2d_cg_mg():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels_cg_mg = random_walker(data, labels, beta=90, mode="cg_mg")
    assert (labels_cg_mg[25:45, 40:60] == 2).all()
    full_prob = random_walker(data, labels, beta=90, mode="cg_mg", return_full_prob=True)
    assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all()
    return data, labels_cg_mg
def test_multispectral_2d():
    lx, ly = 70, 100
    data, labels = make_2d_syntheticdata(lx, ly)
    data2 = data.copy()
    data.shape += (1,)
    data = data.repeat(2, axis=2)   # Result should be identical
    multi_labels = random_walker(data, labels, mode='cg', multichannel=True)
    single_labels = random_walker(data2, labels, mode='cg')
    assert (multi_labels.reshape(labels.shape)[25:45, 40:60] == 2).all()
    return data, multi_labels, single_labels, labels
def test_multispectral_2d():
    lx, ly = 70, 100
    data, labels = make_2d_syntheticdata(lx, ly)
    data = data[..., np.newaxis].repeat(2, axis=-1)  # Expect identical output
    multi_labels = random_walker(data, labels, mode='cg', multichannel=True)
    assert data[..., 0].shape == labels.shape
    single_labels = random_walker(data[..., 0], labels, mode='cg')
    assert (multi_labels.reshape(labels.shape)[25:45, 40:60] == 2).all()
    assert data[..., 0].shape == labels.shape
    return data, multi_labels, single_labels, labels
def test_multispectral_3d():
    n = 30
    lx, ly, lz = n, n, n
    data, labels = make_3d_syntheticdata(lx, ly, lz)
    data.shape += (1,)
    data = data.repeat(2, axis=3)   # Result should be identical
    multi_labels = random_walker(data, labels, mode='cg', multichannel=True)
    single_labels = random_walker(data[..., 0], labels, mode='cg')
    assert (multi_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all()
    assert (single_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all()
    return data, multi_labels, single_labels, labels
def test_multispectral_3d():
    n = 30
    lx, ly, lz = n, n, n
    data, labels = make_3d_syntheticdata(lx, ly, lz)
    data = data[..., np.newaxis].repeat(2, axis=-1)  # Expect identical output
    multi_labels = random_walker(data, labels, mode='cg', multichannel=True)
    assert data[..., 0].shape == labels.shape
    single_labels = random_walker(data[..., 0], labels, mode='cg')
    assert (multi_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all()
    assert (single_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all()
    assert data[..., 0].shape == labels.shape
    return data, multi_labels, single_labels, labels
Esempio n. 8
0
def test_spacing_1():
    n = 30
    lx, ly, lz = n, n, n
    data, _ = make_3d_syntheticdata(lx, ly, lz)

    # Rescale `data` along Y axis
    # `resize` is not yet 3D capable, so this must be done by looping in 2D.
    data_aniso = np.zeros((n, n * 2, n))
    for i, yz in enumerate(data):
        data_aniso[i, :, :] = resize(yz, (n * 2, n),
                                     mode='constant',
                                     anti_aliasing=False)

    # Generate new labels
    small_l = int(lx // 5)
    labels_aniso = np.zeros_like(data_aniso)
    labels_aniso[lx // 5, ly // 5, lz // 5] = 1
    labels_aniso[lx // 2 + small_l // 4,
                 ly - small_l // 2,
                 lz // 2 - small_l // 4] = 2

    # Test with `spacing` kwarg
    # First, anisotropic along Y
    with expected_warnings(['"cg" mode' + '|' + SCIPY_RANK_WARNING,
                            NUMPY_MATRIX_WARNING]):
        labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg',
                                     spacing=(1., 2., 1.))
    assert (labels_aniso[13:17, 26:34, 13:17] == 2).all()

    # Rescale `data` along X axis
    # `resize` is not yet 3D capable, so this must be done by looping in 2D.
    data_aniso = np.zeros((n, n * 2, n))
    for i in range(data.shape[1]):
        data_aniso[i, :, :] = resize(data[:, 1, :], (n * 2, n),
                                     mode='constant',
                                     anti_aliasing=False)

    # Generate new labels
    small_l = int(lx // 5)
    labels_aniso2 = np.zeros_like(data_aniso)
    labels_aniso2[lx // 5, ly // 5, lz // 5] = 1
    labels_aniso2[lx - small_l // 2,
                  ly // 2 + small_l // 4,
                  lz // 2 - small_l // 4] = 2

    # Anisotropic along X
    with expected_warnings(['"cg" mode' + '|' + SCIPY_RANK_WARNING,
                            NUMPY_MATRIX_WARNING]):
        labels_aniso2 = random_walker(data_aniso,
                                      labels_aniso2,
                                      mode='cg', spacing=(2., 1., 1.))
    assert (labels_aniso2[26:34, 13:17, 13:17] == 2).all()
def test_2d_cg():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels_cg = random_walker(data, labels, beta=90, mode='cg')
    assert (labels_cg[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    full_prob = random_walker(data, labels, beta=90, mode='cg',
                              return_full_prob=True)
    assert (full_prob[1, 25:45, 40:60] >=
            full_prob[0, 25:45, 40:60]).all()
    assert data.shape == labels.shape
    return data, labels_cg
Esempio n. 10
0
def test_trivial_cases():
    # When all voxels are labeled
    img = np.ones((10, 10))
    labels = np.ones((10, 10))
    pass_through = random_walker(img, labels)
    np.testing.assert_array_equal(pass_through, labels)

    # When all voxels are labeled AND return_full_prob is True
    labels[:, :5] = 3
    expected = np.concatenate(((labels == 1)[..., np.newaxis],
                               (labels == 3)[..., np.newaxis]), axis=2)
    test = random_walker(img, labels, return_full_prob=True)
    np.testing.assert_array_equal(test, expected)
Esempio n. 11
0
def test_2d_cg():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    with expected_warnings(['"cg" mode' + '|' + SCIPY_EXPECTED]):
        labels_cg = random_walker(data, labels, beta=90, mode='cg')
    assert (labels_cg[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    with expected_warnings(['"cg" mode' + '|' + SCIPY_EXPECTED]):
        full_prob = random_walker(data, labels, beta=90, mode='cg',
                                  return_full_prob=True)
    assert (full_prob[1, 25:45, 40:60] >=
            full_prob[0, 25:45, 40:60]).all()
    assert data.shape == labels.shape
    return data, labels_cg
Esempio n. 12
0
def test_multispectral_2d():
    lx, ly = 70, 100
    data, labels = make_2d_syntheticdata(lx, ly)
    data = data[..., np.newaxis].repeat(2, axis=-1)  # Expect identical output
    with expected_warnings(['"cg" mode' + '|' + SCIPY_RANK_WARNING,
                            NUMPY_MATRIX_WARNING]):
        multi_labels = random_walker(data, labels, mode='cg',
                                     multichannel=True)
    assert data[..., 0].shape == labels.shape
    with expected_warnings(['"cg" mode' + '|' + SCIPY_RANK_WARNING,
                            NUMPY_MATRIX_WARNING]):
        single_labels = random_walker(data[..., 0], labels, mode='cg')
    assert (multi_labels.reshape(labels.shape)[25:45, 40:60] == 2).all()
    assert data[..., 0].shape == labels.shape
    return data, multi_labels, single_labels, labels
Esempio n. 13
0
def cluster_by_diffusion(data):
    markers = np.zeros(data.shape, dtype=np.uint)
    markers[data < -0.00] = 1
    markers[data > 0.03] = 2
    labels2 = random_walker(data, markers, beta=10, mode='bf')

    return labels2
Esempio n. 14
0
def start():
    # Generate noisy synthetic data
    data = microstructure(l=128)
    data += 0.35 * np.random.randn(*data.shape)
    markers = np.zeros(data.shape, dtype=np.uint)
    markers[data < -0.3] = 1
    markers[data > 1.3] = 2

    # Run random walker algorithm
    labels = random_walker(data, markers, beta=10, mode='bf')

    # Plot results
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 3.2))
    ax1.imshow(data, cmap='gray', interpolation='nearest')
    ax1.axis('off')
    ax1.set_title('Noisy data')
    ax2.imshow(markers, cmap='hot', interpolation='nearest')
    ax2.axis('off')
    ax2.set_title('Markers')
    ax3.imshow(labels, cmap='gray', interpolation='nearest')
    ax3.axis('off')
    ax3.set_title('Segmentation')

    fig.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0,
                        right=1)
    plt.show()
Esempio n. 15
0
def test_2d_bf():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels_bf = random_walker(data, labels, beta=90, mode="bf")
    assert (labels_bf[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    full_prob_bf = random_walker(data, labels, beta=90, mode="bf", return_full_prob=True)
    assert (full_prob_bf[1, 25:45, 40:60] >= full_prob_bf[0, 25:45, 40:60]).all()
    assert data.shape == labels.shape
    # Now test with more than two labels
    labels[55, 80] = 3
    full_prob_bf = random_walker(data, labels, beta=90, mode="bf", return_full_prob=True)
    assert (full_prob_bf[1, 25:45, 40:60] >= full_prob_bf[0, 25:45, 40:60]).all()
    assert len(full_prob_bf) == 3
    assert data.shape == labels.shape
def test_2d_cg_mg():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg')
    assert (labels_cg_mg[25:45, 40:60] == 2).all()
    return data, labels_cg_mg
def segment_out_cells(base):
    # TODO: try using OTSU for GFP thresholding

    sel_elem = disk(2)
    gfp_collector = np.sum(base, axis=0)
    gfp_clustering_markers = np.zeros(gfp_collector.shape, dtype=np.uint8)
    # random walker segment
    gfp_clustering_markers[gfp_collector > np.mean(gfp_collector) * 2] = 2
    gfp_clustering_markers[gfp_collector < np.mean(gfp_collector) * 0.20] = 1
    labels = random_walker(gfp_collector, gfp_clustering_markers, beta=10, mode='bf')
    # round up the labels and set the background to 0 from 1
    labels = closing(labels, sel_elem)
    labels -= 1
    # prepare distances for the watershed
    distance = ndi.distance_transform_edt(labels)
    local_maxi = peak_local_max(distance,
                                indices=False,  # we want the image mask, not peak position
                                min_distance=10,  # about half of a bud with our size
                                threshold_abs=10,  # allows to clear the noise
                                labels=labels)
    # we fuse the labels that are close together that escaped the min distance in local_maxi
    local_maxi = ndi.convolve(local_maxi, np.ones((5, 5)), mode='constant', cval=0.0)
    # finish the watershed
    expanded_maxi_markers = ndi.label(local_maxi, structure=np.ones((3, 3)))[0]
    segmented_cells_labels = watershed(-distance, expanded_maxi_markers, mask=labels)

    # log debugging data
    running_debug_frame.gfp_collector = gfp_collector
    running_debug_frame.gfp_clustering_markers = gfp_clustering_markers
    running_debug_frame.labels = labels
    running_debug_frame.segmented_cells_labels = segmented_cells_labels

    return gfp_collector, segmented_cells_labels
Esempio n. 18
0
    def _automatic_localization(self):
        """
        Automatic localization made by Tomas Ryba.
        """

        # seeds = self.get_seeds_using_class_1(class1)
        liver = self.data3d * (self.segmentation != 0)
        print('analyzing histogram...')
        class1 = tools.analyse_histogram(self.data3d,
                                         roi=self.segmentation != 0)
        # sed3.sed3(self.data3d, seeds=class1).show()
        print('getting seeds...')
        seeds = self.get_seeds_using_prob_class1(
            liver,
            class1,
            thresholdType='percOfMaxDist',
            percT=0.3)

        # sed3.sed3(self.data3d, seeds=seeds).show()

        print('Starting random walker...')
        rw = random_walker(liver, seeds, mode='cg_mg')
        print('...finished.')

        label_l = self.data['slab']['lesions']

        lessions = rw == 2
        sed3.sed3(self.data3d, contour=lessions).show()
        lessions = self.filter_objects(lessions)

        self.segmentation = np.where(lessions, label_l, self.segmentation)
def test_3d():
    n = 30
    lx, ly, lz = n, n, n
    data, labels = make_3d_syntheticdata(lx, ly, lz)
    labels = random_walker(data, labels, mode='cg')
    assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all()
    return data, labels
Esempio n. 20
0
def test_2d_cg_mg():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    expected = 'scipy.sparse.sparsetools|%s' % PYAMG_SCIPY_EXPECTED
    with expected_warnings([expected]):
        labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg')
    assert (labels_cg_mg[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    with expected_warnings([expected]):
        full_prob = random_walker(data, labels, beta=90, mode='cg_mg',
                              return_full_prob=True)
    assert (full_prob[1, 25:45, 40:60] >=
            full_prob[0, 25:45, 40:60]).all()
    assert data.shape == labels.shape
    return data, labels_cg_mg
Esempio n. 21
0
def test_spacing_0():
    n = 30
    lx, ly, lz = n, n, n
    data, _ = make_3d_syntheticdata(lx, ly, lz)

    # Rescale `data` along Z axis
    data_aniso = np.zeros((n, n, n // 2))
    for i, yz in enumerate(data):
        data_aniso[i, :, :] = resize(yz, (n, n // 2),
                                     mode='constant',
                                     anti_aliasing=False)

    # Generate new labels
    small_l = int(lx // 5)
    labels_aniso = np.zeros_like(data_aniso)
    labels_aniso[lx // 5, ly // 5, lz // 5] = 1
    labels_aniso[lx // 2 + small_l // 4,
                 ly // 2 - small_l // 4,
                 lz // 4 - small_l // 8] = 2

    # Test with `spacing` kwarg
    with expected_warnings(['"cg" mode' + '|' + SCIPY_RANK_WARNING,
                            NUMPY_MATRIX_WARNING]):
        labels_aniso = random_walker(data_aniso, labels_aniso, mode='cg',
                                     spacing=(1., 1., 0.5))

    assert (labels_aniso[13:17, 13:17, 7:9] == 2).all()
def test_reorder_labels():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels[labels == 2] = 4
    labels_bf = random_walker(data, labels, beta=90, mode='bf')
    assert (labels_bf[25:45, 40:60] == 2).all()
    return data, labels_bf
def test_types():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    data = 255 * (data - data.min()) / (data.max() - data.min())
    data = data.astype(np.uint8)
    labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg')
    assert (labels_cg_mg[25:45, 40:60] == 2).all()
    return data, labels_cg_mg
def test_2d_inactive():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels[10:20, 10:20] = -1
    labels[46:50, 33:38] = -2
    labels = random_walker(data, labels, beta=90)
    assert (labels.reshape((lx, ly))[25:45, 40:60] == 2).all()
    return data, labels
Esempio n. 25
0
def test_3d():
    n = 30
    lx, ly, lz = n, n, n
    data, labels = make_3d_syntheticdata(lx, ly, lz)
    with expected_warnings(['"cg" mode' + '|' + SCIPY_EXPECTED]):
        labels = random_walker(data, labels, mode='cg')
    assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all()
    assert data.shape == labels.shape
    return data, labels
def test_isolated_seeds():
    np.random.seed(0)
    a = np.random.random((7, 7))
    mask = - np.ones(a.shape)
    # This pixel is an isolated seed
    mask[1, 1] = 1
    # Unlabeled pixels
    mask[3:, 3:] = 0
    # Seeds connected to unlabeled pixels
    mask[4, 4] = 2
    mask[6, 6] = 1

    # Test that no error is raised, and that labels of isolated seeds are OK
    res = random_walker(a, mask)
    assert res[1, 1] == 1
    res = random_walker(a, mask, return_full_prob=True)
    assert res[0, 1, 1] == 1
    assert res[1, 1, 1] == 0
Esempio n. 27
0
def test_2d_cg_mg():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    anticipated_warnings = [
        'scipy.sparse.sparsetools|%s' % PYAMG_OR_SCIPY_WARNING,
        NUMPY_MATRIX_WARNING]
    with expected_warnings(anticipated_warnings):
        labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg')
    assert (labels_cg_mg[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    with expected_warnings(anticipated_warnings):
        full_prob = random_walker(data, labels, beta=90, mode='cg_mg',
                                  return_full_prob=True)
    assert (full_prob[1, 25:45, 40:60] >=
            full_prob[0, 25:45, 40:60]).all()
    assert data.shape == labels.shape
    return data, labels_cg_mg
def test_3d_inactive():
    n = 30
    lx, ly, lz = n, n, n
    data, labels = make_3d_syntheticdata(lx, ly, lz)
    old_labels = np.copy(labels)
    labels[5:25, 26:29, 26:29] = -1
    after_labels = np.copy(labels)
    labels = random_walker(data, labels, mode='cg')
    assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all()
    return data, labels, old_labels, after_labels
Esempio n. 29
0
def test_reorder_labels():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels[labels == 2] = 4
    with expected_warnings([NUMPY_MATRIX_WARNING]):
        labels_bf = random_walker(data, labels, beta=90, mode='bf')
    assert (labels_bf[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    return data, labels_bf
Esempio n. 30
0
def test_types():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    data = 255 * (data - data.min()) // (data.max() - data.min())
    data = data.astype(np.uint8)
    with expected_warnings([PYAMG_SCIPY_EXPECTED]):
        labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg')
    assert (labels_cg_mg[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    return data, labels_cg_mg
Esempio n. 31
0
def binarize_img(im, thrs1, thrs2, max_iter):
    start_time = time.time()
    markers = np.zeros_like(im)
    markers[im > thrs1] = 1
    markers[im < thrs2] = 2
    t = random_walker(im, markers, beta=100)
    global count
    print("count", count, " of ", max_iter, f" %: {count/max_iter:.2f}",
          "| time (min): ", (time.time() - start_time) / 60)
    count += 1

    return t < 2
Esempio n. 32
0
def test_multispectral_3d(dtype):
    n = 30
    lx, ly, lz = n, n, n
    data, labels = make_3d_syntheticdata(lx, ly, lz)
    data = data.astype(dtype, copy=False)
    data = data[..., np.newaxis].repeat(2, axis=-1)  # Expect identical output
    with expected_warnings(
        ['"cg" mode' + '|' + SCIPY_RANK_WARNING, NUMPY_MATRIX_WARNING]):
        multi_labels = random_walker(data,
                                     labels,
                                     mode='cg',
                                     multichannel=True)
    assert data[..., 0].shape == labels.shape
    with expected_warnings(
        ['"cg" mode' + '|' + SCIPY_RANK_WARNING, NUMPY_MATRIX_WARNING]):
        single_labels = random_walker(data[..., 0], labels, mode='cg')
    assert (multi_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all()
    assert (single_labels.reshape(labels.shape)[13:17, 13:17,
                                                13:17] == 2).all()
    assert data[..., 0].shape == labels.shape
    return data, multi_labels, single_labels, labels
Esempio n. 33
0
def test_2d_cg_mg():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    anticipated_warnings = [
        'scipy.sparse.sparsetools|%s' % PYAMG_OR_SCIPY_WARNING,
        NUMPY_MATRIX_WARNING
    ]
    with expected_warnings(anticipated_warnings):
        labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg')
    assert (labels_cg_mg[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    with expected_warnings(anticipated_warnings):
        full_prob = random_walker(data,
                                  labels,
                                  beta=90,
                                  mode='cg_mg',
                                  return_full_prob=True)
    assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all()
    assert data.shape == labels.shape
    return data, labels_cg_mg
Esempio n. 34
0
 def run(self, ips, snap, img, para=None):
     msk = np.zeros_like(img)
     msk[img > para['thr2']] = 1
     msk[img < para['thr1']] = 2
     msk = random_walker(snap,
                         msk,
                         beta=para['beta'],
                         mode=para['mode'],
                         tol=para['tol']) == 1
     ips.lut = self.buflut
     if para['out'] == 'mask': img[~msk], img[msk] = ips.range
     else: img[binary_dilation(msk) ^ msk] = ips.range[1]
def RandomWalker(data, marker_mask):
    data = rescale_intensity(data.astype('float'), in_range=(0,255), out_range=(0,1))
    data = rescale_intensity(data, in_range=(-0.35, 1 + 0.35), out_range=(-1, 1))

    # The range of the binary image spans over (-1, 1).
    # We choose the hottest and the coldest pixels as markers.
    markers = np.zeros(data.shape, dtype=np.uint)
    markers[data < -0.95] = 1;
    markers[data > 0.95] = 2

    # Run random walker algorithm
    labels = random_walker(data, markers, beta=10, mode='bf')
def compute_cell_bmap(cell_probs):
    output = cell_probs
    output2 = output[::2, ::2]
    local_maxi = peak_local_max(output2, indices=False, min_distance=5)
    markers = ndi.label(local_maxi)[0]
    markers[output2 < 0.01] = -1
    segments = random_walker(output2, markers, tol=0.01)
    segments = resize(segments, output.shape, order=0, preserve_range=True)
    #segments = watershed(-output, markers)
    gx = convolve2d(segments, np.array([[1, 0, -1]]), mode='same')
    gx[0, :] = 0
    gx[-1, :] = 0
    gx[:, 0] = 0
    gx[:, -1] = 0
    gy = convolve2d(segments, np.array([[1, 0, -1]]).T, mode='same')
    gy[0, :] = 0
    gy[-1, :] = 0
    gy[:, 0] = 0
    gy[:, -1] = 0

    gmag = np.sqrt(gx**2 + gy**2)
    gmag = gmag > 0
    D = {}
    P = {}
    y, x = np.where(gmag)
    for i in range(y.size):
        nearby_labels = np.unique(segments[y[i] - 1:y[i] + 2,
                                           x[i] - 1:x[i] + 2])
        t = tuple(nearby_labels)
        if t in D.keys():
            D[t].append([y[i], x[i]])
            P[t].append(
                np.min(cell_probs[y[i] - 1:y[i] + 2, x[i] - 1:x[i] + 2]))
        else:
            D[t] = [[y[i], x[i]]]
            P[t] = [np.min(cell_probs[y[i] - 1:y[i] + 2, x[i] - 1:x[i] + 2])]
    bmap = np.zeros(cell_probs.shape)
    for t in D.keys():
        coords = np.array(D[t])

        #if 2-way boundary:
        if len(t) < 3:
            score = np.mean(np.array(P[t]))
        else:
            perms = permutations(t, 2)
            perms = [np.mean(P[t]) for t in perms if t in P.keys()]
            score = np.min(perms)
        bmap[coords[:, 0], coords[:, 1]] = 1 - score
    bmap[0, :] = 1
    bmap[-1, :] = 1
    bmap[:, 0] = 1
    bmap[:, -1] = 1
    return bmap
def test_3d_inactive():
    n = 30
    lx, ly, lz = n, n, n
    data, labels = make_3d_syntheticdata(lx, ly, lz)
    old_labels = np.copy(labels)
    labels[5:25, 26:29, 26:29] = -1
    after_labels = np.copy(labels)
    with expected_warnings(['"cg" mode|CObject type' + '|' + SCIPY_EXPECTED]):
        labels = random_walker(data, labels, mode='cg')
    assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all()
    assert data.shape == labels.shape
    return data, labels, old_labels, after_labels
Esempio n. 38
0
def test_isolated_area():
    np.random.seed(0)
    a = np.random.random((7, 7))
    mask = -np.ones(a.shape)
    # This pixel is an isolated seed
    mask[1, 1] = 0
    # Unlabeled pixels
    mask[3:, 3:] = 0
    # Seeds connected to unlabeled pixels
    mask[4, 4] = 2
    mask[6, 6] = 1

    # Test that no error is raised, and that labels of isolated seeds are OK
    with expected_warnings(
        [NUMPY_MATRIX_WARNING, 'The probability range is outside']):
        res = random_walker(a, mask)
    assert res[1, 1] == 0
    with expected_warnings(
        [NUMPY_MATRIX_WARNING, 'The probability range is outside']):
        res = random_walker(a, mask, return_full_prob=True)
    assert res[0, 1, 1] == 0
    assert res[1, 1, 1] == 0
Esempio n. 39
0
def segment(img, markers):
    """Segment image."""
    logging.info('Segmenting: %s', array_info(img))
    logging.info('...with markers: %s', array_info(markers))
    d = dict(
        # beta=10,  # Default is 130.
        mode='cg_mg',
        # mode=None,
        multichannel=True,
        spacing=img.spacing,
        )
    labels = segmentation.random_walker(img, markers, **d)
    return labels
Esempio n. 40
0
def robust_binarize(base_image,
                    _dilation=0,
                    heterogeity_size=10,
                    feature_size=50):
    """
    Robust binarization algorithm based off random walker clustering

    :param base_image:
    :param _dilation: if set to anything other than 0, would perform a morphological dilation using this parameter value as size
    :param heterogeity_size: size of the feature (px) that the method will try to eliminate by smoothing
    :param feature_size: size of the feature (px) that the method will try to segment out
    :return: binary_labels
    """
    if np.percentile(base_image, 99) < 0.20:
        if np.percentile(base_image, 99) > 0:
            mult = 0.20 / np.percentile(
                base_image, 99)  # poissonean background assumptions
        else:
            mult = 1000. / np.sum(base_image)
        base_image = base_image * mult
        base_image[base_image > 1] = 1

    clustering_markers = np.zeros(base_image.shape, dtype=np.uint8)

    selem = disk(heterogeity_size)
    smooth = gaussian_filter(base_image, heterogeity_size, mode='constant')
    smooth_median = median(smooth, selem)
    uniform_median = median(base_image, selem)

    selem2 = disk(feature_size)
    local_otsu = rank.otsu(smooth_median, selem2)
    uniform_median_otsu = rank.otsu(uniform_median, selem2)

    clustering_markers[smooth_median < local_otsu * 0.9] = 1
    clustering_markers[smooth_median > local_otsu * 1.1] = 2

    # dbg.random_walker_debug(smooth_median, clustering_markers)
    # dbg.robust_binarize_debug(base_image, smooth_median, smooth_median, local_otsu, clustering_markers,
    #                           0, uniform_median, uniform_median_otsu)

    binary_labels = random_walker(
        smooth_median, clustering_markers, beta=10, mode='bf') - 1

    if _dilation:
        selem = disk(_dilation)
        binary_labels = dilation(binary_labels, selem)

    # dbg.robust_binarize_debug(binary_labels, base_image)
    # dbg.voronoi_debug(binary_labels, local_maxi, dist, segmented_cells_labels)
    # dbg.Kristen_robust_binarize(binary_labels, base_image)
    return binary_labels
Esempio n. 41
0
def test_trivial_cases():
    # When all voxels are labeled
    img = np.ones((10, 10))
    labels = np.ones((10, 10))

    with expected_warnings(["Returning provided labels"]):
        pass_through = random_walker(img, labels)
    np.testing.assert_array_equal(pass_through, labels)

    # When all voxels are labeled AND return_full_prob is True
    labels[:, :5] = 3
    expected = np.concatenate(
        ((labels == 1)[..., np.newaxis], (labels == 3)[..., np.newaxis]),
        axis=2)
    with expected_warnings(["Returning provided labels"]):
        test = random_walker(img, labels, return_full_prob=True)
    np.testing.assert_array_equal(test, expected)

    # Unlabeled voxels not connected to seed, so nothing can be done
    img = np.full((10, 10), False)
    object_A = np.array([(6, 7), (6, 8), (7, 7), (7, 8)])
    object_B = np.array([(3, 1), (4, 1), (2, 2), (3, 2), (4, 2), (2, 3),
                         (3, 3)])
    for x, y in np.vstack((object_A, object_B)):
        img[y][x] = True

    markers = np.zeros((10, 10), dtype=np.int8)
    for x, y in object_B:
        markers[y][x] = 1

    markers[img == 0] = -1
    with expected_warnings(["All unlabeled pixels are isolated"]):
        output_labels = random_walker(img, markers)
    assert np.all(output_labels[markers == 1] == 1)
    # Here 0-labeled pixels could not be determined (no connexion to seed)
    assert np.all(output_labels[markers == 0] == -1)
    with expected_warnings(["All unlabeled pixels are isolated"]):
        test = random_walker(img, markers, return_full_prob=True)
Esempio n. 42
0
def randomwalk_seg(rgb_img, mask, safe_zone_len, beta, num_points):
    start = time.time()
    se = np.ones((safe_zone_len, safe_zone_len))

    rand_fore_points = morphology.binary_erosion(mask, se)
    rand_back_points = morphology.binary_erosion(mask == 0, se)

    if num_points < 0:
        labels = rand_fore_points * 1.0 + 2.0 * rand_back_points
        random_walker_mask = random_walker(rgb_img,
                                           labels,
                                           beta=beta,
                                           multichannel=True) == 1

    else:

        #sampling point
        fore_points = segh.get_sample_point(rgb_img, num_points,
                                            grow_fore_points)
        back_points = segh.get_sample_point(rgb_img, num_points,
                                            grow_back_points)
        labels = np.zeros((m, n))

        for p in fore_points:
            i, j = p[-2], p[-1]
            labels[i, j] = 1
        for p in back_points:
            i, j = p[-2], p[-1]
            labels[i, j] = 2

        random_walker_mask = random_walker(rgb_img,
                                           labels,
                                           beta=beta,
                                           multichannel=True) == 1

    print('size ', random_walker_mask.shape, ' Random Walk processing time ',
          time.time() - start)
    return random_walker_mask
def test_2d_bf():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    with expected_warnings([NUMPY_MATRIX_WARNING]):
        labels_bf = random_walker(data, labels, beta=90, mode='bf')
    assert (labels_bf[25:45, 40:60] == 2).all()
    assert data.shape == labels.shape
    with expected_warnings([NUMPY_MATRIX_WARNING]):
        full_prob_bf = random_walker(data, labels, beta=90, mode='bf',
                                 return_full_prob=True)
    assert (full_prob_bf[1, 25:45, 40:60] >=
            full_prob_bf[0, 25:45, 40:60]).all()
    assert data.shape == labels.shape
    # Now test with more than two labels
    labels[55, 80] = 3
    with expected_warnings([NUMPY_MATRIX_WARNING]):
        full_prob_bf = random_walker(data, labels, beta=90, mode='bf',
                                 return_full_prob=True)
    assert (full_prob_bf[1, 25:45, 40:60] >=
            full_prob_bf[0, 25:45, 40:60]).all()
    assert len(full_prob_bf) == 3
    assert data.shape == labels.shape
Esempio n. 44
0
def test_2d_bf():
    lx = 70
    ly = 100
    data, labels = make_2d_syntheticdata(lx, ly)
    labels_bf = random_walker(data, labels, beta=90, mode='bf')
    assert (labels_bf[25:45, 40:60] == 2).all()
    full_prob_bf = random_walker(data,
                                 labels,
                                 beta=90,
                                 mode='bf',
                                 return_full_prob=True)
    assert (full_prob_bf[1, 25:45, 40:60] >= full_prob_bf[0, 25:45,
                                                          40:60]).all()
    # Now test with more than two labels
    labels[55, 80] = 3
    full_prob_bf = random_walker(data,
                                 labels,
                                 beta=90,
                                 mode='bf',
                                 return_full_prob=True)
    assert (full_prob_bf[1, 25:45, 40:60] >= full_prob_bf[0, 25:45,
                                                          40:60]).all()
    assert len(full_prob_bf) == 3
Esempio n. 45
0
def apply_random_walker(image):
    upper_bound = np.max(image)
    img_as_float = image / upper_bound
    img_as_float *= 2
    img_as_float -= 1

    # print(img_as_float.max(), img_as_float.min())
    # print(image.min(), image.max())

    markers = np.zeros(img_as_float.shape, dtype=np.uint)
    markers[img_as_float < -0.90] = 1
    markers[img_as_float > 0.90] = 2

    return random_walker(img_as_float, markers, beta=10, mode='bf')
Esempio n. 46
0
def seg(img):
    # xg = img[:,:,1]

    xg = np.copy(img)
    cv2.imshow('img', xg)
    cv2.waitKey()
    cv2.destroyAllWindows()

    a, b = np.histogram(img.flatten(), bins=30, range=[15, 255])
    idx = a.argmax()
    range_S = b[idx]
    range_B = b[-1]

    # range_S_2 = b[-5]
    # range_B_2 = b[-1]

    tmp = np.zeros_like(img)
    tmp[(img >= range_S) * (img <= range_B)] = 255
    # tmp[(img >= range_S_2) *(img <= range_B_2)] = 255

    cv2.imshow('test', tmp)
    cv2.waitKey()
    cv2.destroyAllWindows()

    m1 = xg.mean()
    mask = np.zeros_like(xg)
    mask[xg > m1] = 1  #
    cv2.imshow('img', mask)
    cv2.waitKey()
    cv2.destroyAllWindows()

    canny = cv2.Canny(img, 20, 60) * mask
    cv2.imshow('canny', canny)
    cv2.waitKey()
    cv2.destroyAllWindows()
    closed = np.zeros_like(canny)
    closed[canny > 0] = 1
    closed[mask == 0] = 2
    closed[(img >= range_S) * (img <= range_B)] = 2

    image_segmented = random_walker(xg, closed, beta=20, mode='bf')  #, beta=1
    image_segmented[image_segmented == 2] = 0
    image_segmented = image_segmented.astype(np.uint8) * 255
    # closed = cv2.erode(image_segmented, None, iterations=2)
    cv2.imshow('img res', image_segmented)
    cv2.waitKey()

    cv2.destroyAllWindows()
    return image_segmented
Esempio n. 47
0
def test_multispectral_2d(dtype, channel_axis):
    lx, ly = 70, 100
    data, labels = make_2d_syntheticdata(lx, ly)
    data = data.astype(dtype, copy=False)
    data = data[..., np.newaxis].repeat(2, axis=-1)  # Expect identical output

    data = np.moveaxis(data, -1, channel_axis)
    with expected_warnings([
            '"cg" mode' + '|' + SCIPY_RANK_WARNING, NUMPY_MATRIX_WARNING,
            'The probability range is outside'
    ]):
        multi_labels = random_walker(data,
                                     labels,
                                     mode='cg',
                                     channel_axis=channel_axis)
    data = np.moveaxis(data, channel_axis, -1)

    assert data[..., 0].shape == labels.shape
    with expected_warnings(
        ['"cg" mode' + '|' + SCIPY_RANK_WARNING, NUMPY_MATRIX_WARNING]):
        single_labels = random_walker(data[..., 0], labels, mode='cg')
    assert (multi_labels.reshape(labels.shape)[25:45, 40:60] == 2).all()
    assert data[..., 0].shape == labels.shape
    return data, multi_labels, single_labels, labels
Esempio n. 48
0
  def draw(self, event):
    x, y = event.xdata, event.ydata
    x, y = int(x), int(y)
    # print('x=%1.2f, y=%1.2f' % (x, y))
    imd = np.sqrt((self.xx-y)**2 + (self.yy-x)**2) <= self.r

    if event.button == 1:
      self.im_markers[imd] = 1
    elif event.button == 3:
      self.im_markers[imd] = 2
    elif event.button == 2:
      self.im_labels = random_walker(self.im, self.im_markers, beta=10, mode='cg_mg') # 'bf'
      self.ax3.imshow(self.im_labels, cmap='gray', interpolation='nearest')
    self.ax2.imshow(self.im_markers, cmap='magma', interpolation='nearest')
    plt.draw()
Esempio n. 49
0
def test_walker_binary():
    unet, mrcnn, annot = get_images()
    annot_mask = np.where(annot > 0, 1, 0)
    unet_mask = np.where(unet > 0, 1, 0)
    mrcnn_mask = np.where(mrcnn > 0, 1, 0)
    unet_seed, mrcnn_seed = erode_images(unet, mrcnn, 6, 6)
    labels = np.where(unet_seed + mrcnn_seed > 0, 1, 0)
    labels[unet_mask + mrcnn_mask == 0] = 2
    data = np.dstack((unet, mrcnn))
    final = random_walker(data, labels, beta=30, mode='bf')
    final[final == 2] = 0
    imwrite('unet.png', unet_mask * 255)
    imwrite('mrcnn.png', mrcnn_mask * 255)
    imwrite('final_.png', final * 255)
    imwrite('annot.png', annot_mask * 255)
Esempio n. 50
0
def produceRandomWalkerSegmentationNoContrast(filename):
    image = utils.readImageGrayscaled(filename)
    utils.saveImageSegment(filename, 'original_gs', image)

    markers = np.zeros(image.shape, dtype=np.uint8)
    markers[image < 0.25] = 2
    markers[image > 0.5] = 1

    image_segmented = seg.random_walker(image, markers)
    utils.saveImageSegment(filename, 'rand_walk_unsupervised', image_segmented)

    merged = image + image_segmented

    utils.saveImageSegment(filename, 'merge_rand_walk_unsupervised', merged)
    utils.saveImageSegmentResult(filename, 'rand_walk_unsupervised', merged)
Esempio n. 51
0
def get_labels(prediction):
    def _get_reduced_maxima(pred):
        markers = []
        distance = ndi.distance_transform_edt(pred)
        distance_ordinal = distance - np.min(distance)
        distance_ordinal = distance_ordinal / np.max(distance_ordinal)
        markers.append(ndi.label(distance_ordinal)[0])
        markers.append(
            ndi.label(
                ndi.distance_transform_edt(distance_ordinal >= 0.1 * 1.0))[0])
        # markers.append(ndi.label(ndi.distance_transform_edt(distance_ordinal >= 0.5 * 1.0))[0])
        # markers.append(ndi.label(ndi.distance_transform_edt(distance_ordinal >= 0.75 * 1.0))[0])
        final_markers = ndi.label(
            ndi.distance_transform_edt(distance_ordinal >= 0.5 * 1.0))[0]

        # # Calculate mean cell size
        cell_sums = []
        for c_id in np.unique(final_markers)[1:]:
            cell_sums.append(np.sum(c_id == final_markers * 1.0))
        mean_sum = np.mean(cell_sums)

        # Reduce centroid size
        for marker in markers[::-1]:
            transition_markers = marker * (final_markers > 0)
            for c_id in np.unique(marker)[1:]:
                cell_seg = (marker == c_id) * 1.0
                if np.sum(cell_seg *
                          (transition_markers > 0 * 1.0)) <= mean_sum * 0.3:
                    final_markers = ndi.label((final_markers > 0) * 1.0 +
                                              (marker == c_id) * 1.0)[0]

        return final_markers, mean_sum

    pred, ind = get_expanded_boundary(prediction)
    markers, mean_sum = _get_reduced_maxima(pred)

    markers = get_normal_boundary(markers, ind)
    markers = markers * (prediction > 0 * 1.0) - 1 * (prediction == 0 * 1.0)
    wa = random_walker(prediction, markers)
    wa = wa * (wa != -1)

    # Remove small cell artifacts
    wa_2 = np.zeros(np.shape(wa))
    for c_id in np.unique(wa)[1:]:
        if np.sum((c_id == wa) * 1.0) >= mean_sum * 0.1:
            wa_2 += (c_id == wa) * c_id
    wa = wa_2
    return wa
Esempio n. 52
0
def get_regions(img):
    denoised=restoration.denoise_bilateral(img.astype('uint16'), 
#                                            sigma_range=0.01, 
                                           sigma_spatial=15,
                                          multichannel=False)
    smoothened = filters.median(denoised,np.ones((4,4)))
    markers = np.zeros(smoothened.shape, dtype=np.uint)
# otsu works only for only for multi-channel images     
#     markers[smoothened < filters.threshold_otsu(smoothened)] = 1
#     markers[smoothened > filters.threshold_otsu(smoothened)] = 2
    markers[smoothened < filters.median(smoothened)] = 1
    markers[smoothened > filters.median(smoothened)] = 2

    labels = random_walker(smoothened, markers, beta=10, mode='bf')
    regions= measure.label(labels)
    return regions, denoised, smoothened,markers
Esempio n. 53
0
def random_walker_binarize(base_image, _dilation=0):
    gfp_clustering_markers = np.zeros(base_image.shape, dtype=np.uint8)

    # To try: add a grey area around the boundary between black and white

    gfp_clustering_markers[base_image > np.mean(base_image) * 2] = 2
    gfp_clustering_markers[base_image < np.mean(base_image) * 0.20] = 1

    binary_labels = random_walker(
        base_image, gfp_clustering_markers, beta=10, mode='bf') - 1

    if _dilation:
        selem = disk(_dilation)
        binary_labels = dilation(binary_labels, selem)

    return binary_labels
Esempio n. 54
0
def label_particles_walker(im, min_thresh=0.3, max_thresh=0.5, sigma=3):
    """ label_particles_walker(image, min_thresh=0.3, max_thresh=0.5)
        Returns the labels for an image.
        Segments using random_walker method.

        keyword arguments:
        image        -- The image in which to find particles
        min_thresh   -- The lower limit for binary threshold
        max_thresh   -- The upper limit for binary threshold
    """
    if sigma > 0:
        im = gaussian_filter(im, sigma)
    labels = np.zeros_like(im)
    labels[im < min_thresh * im.max()] = 1
    labels[im > max_thresh * im.max()] = 2
    return segmentation.random_walker(im, labels)
Esempio n. 55
0
def background_generator():

    size_x = 50
    size_y = 50

    n_labels = 2

    image_rgb = np.random.uniform(0.9, 1, (size_x, size_y, 3))
    labels = np.random.randint(n_labels + 1, size=(
        size_x, size_y)) * np.random.randint(0, 2, size=(size_x, size_y))

    # segment random image
    segments = random_walker(image_rgb,
                             labels,
                             multichannel=True,
                             beta=250,
                             copy=False,
                             spacing=[50, 10])
    for color_index in np.unique(segments):
        image_rgb[segments == color_index] = np.random.uniform(0, 1, 3)

    # transform segmented image so it is large, preserving blobs, and blurry
    image_rgb = rescale(image_rgb, 2, anti_aliasing=False, multichannel=True)
    image_rgb = gaussian(image_rgb, sigma=2, multichannel=True)
    image_hsv = color.rgb2hsv(image_rgb)
    buffer = 0.05
    hsv_index = 1
    for _ in range(10000):
        rand_x, rand_y = np.random.choice(
            image_hsv.shape[0]), np.random.choice(image_hsv.shape[1])
        orig_rgb = image_rgb[rand_x, rand_y]
        rand_value = image_hsv[rand_x, rand_y, hsv_index]

        x, y = np.where((rand_value *
                         (1 + buffer) >= image_hsv[:, :, hsv_index])
                        & (rand_value *
                           (1 - buffer) < image_hsv[:, :, hsv_index]))
        if len(x) == 0:
            continue
        idx = np.random.choice(len(x))
        update_rgb = image_rgb[x[idx], y[idx]]

        image_rgb[x[idx], y[idx]] = orig_rgb
        image_rgb[rand_x, rand_y] = update_rgb

    return image_rgb
Esempio n. 56
0
def watershedPower(input_file, output_file, seeds_file, algo, mult, geod):
    image_name = "figure_1.png"

    seeds_name = seeds_file
    sigma = 0.35

    fimage_read = open(image_name, 'rb')
    fimage_seeds = open(seeds_name, 'rb')

    image_read = read_pgm(fimage_read)
    seeds = read_pgm(fimage_seeds)

    rs = rowsize(fimage_read)
    cs = colsize(fimage_read)

    N = rs * cs
    M = rs * (cs - 1) + (rs - 1) * cs  #number of edges

    nblabels = 2
    j = 0
    for i in range(0, rs * cs):
        if seeds[i] > 155:
            index_seeds[j] = i
            index_labels[j] = 1
            j += 1
        if seeds[i] < 100:
            index_seeds[j] = i
            index_labels[j] = 2
            j += 1

    size_seeds = j
    markers = np.zeros(image.shape, dtype=np.uint)
    markers[image < -0.95] = 1
    markers[image > 0.95] = 2
    matrixedges = [[0 for col in range(2)]
                   for row in range((cs - 1) * rs + (rs - 1) * cs)]
    edges = compute_edges(matrixedges, rs, cs)
    weights = []
    normal_weights = grey_weights_PW(image_name, edges, index_seeds,
                                     size_seeds, weights, quicksort)

    output = PowerWatershed_q2(edges, weights, normal_weights, max_weight,
                               index_seeds, index_labels, size_seeds, rs, cs,
                               ds, nblabels, quicksort, img_proba)
    labels = random_walker(image, markers, beta=10, mode='bf')
Esempio n. 57
0
def test_walker_label():
    unet, mrcnn, annot = get_images()
    unet_seed, mrcnn_seed = erode_images(unet, mrcnn, 6, 6)
    annot_mask = np.where(annot > 0, 1, 0)
    unet_mask = np.where(unet > 0, 1, 0)
    mrcnn_mask = np.where(mrcnn > 0, 1, 0)
    labels = np.where(unet_seed + mrcnn_seed > 0, 1, 0)
    labels = label(labels)
    labels, _, _ = relabel_sequential(labels, offset=2)
    labels[unet_mask + mrcnn_mask == 0] = 1
    data = np.dstack((unet, mrcnn))
    final = random_walker(data, labels, beta=50, mode='bf')
    final[final == 1] = 0
    imwrite('unet.png', unet_mask*255)
    imwrite('mrcnn.png', mrcnn_mask*255)
    imwrite('final_.png', final*255)
    imwrite('annot.png', annot_mask * 255)
    return final
Esempio n. 58
0
def add_missed_blobs(full_mask, labeled_mask, edges):
    missed_mask = full_mask & ~(labeled_mask > 0)
    missed_mask = drop_small_blobs(missed_mask,
                                   2)  # bodies must be larger than 1-pixel
    if edges is not None:
        missed_markers = label(missed_mask & ~edges)
    else:
        missed_markers = label(missed_mask)
    if missed_markers.max() > 0:
        missed_markers[missed_mask == 0] = -1
        missed_labels = random_walker(missed_mask, missed_markers)
        missed_labels[missed_labels <= 0] = 0
        missed_labels = np.where(missed_labels > 0,
                                 missed_labels + labeled_mask.max(), 0)
        final_labels = np.add(labeled_mask, missed_labels)
    else:
        final_labels = labeled_mask
    return final_labels
Esempio n. 59
0
def rondomwalker_seg(distance, threshold=2.0):
    if isinstance(distance, Variable):
        distance = distance.data
    if isinstance(distance, torch.FloatTensor) or isinstance(
            distance, torch.cuda.FloatTensor):
        distance = distance.cpu().numpy()
    #print(type(distance))
    distance = np.squeeze(distance)

    distance = gaussian(distance / np.max(distance), sigma=0.6, mode='reflect')
    markers = distance > 0.039
    markers = skimage.morphology.label(markers)
    seg_labels = random_walker(-distance, markers,\
                                       beta=25000, mode='cg_mg')
    #seg_labels = watershed(-distance, markers)

    #axes[1].plot(coordinates[:, 1], coordinates[:, 0], 'r.')
    return seg_labels
Esempio n. 60
0
def img_random_walker(data,
                      lower_q=0.9,
                      upper_q=0.98,
                      val_beta=10,
                      val_mode='bf'):
    labels = []
    if not isinstance(data, list):
        raise Exception('Argument data must be a list type')
    for x in data:
        ones = np.ones(x.shape)
        markers = np.zeros(x.shape)
        markers[x < np.quantile(x, lower_q)] = 1
        markers[x > np.quantile(x, upper_q)] = 2

        labels.append(
            random_walker(x, markers, beta=val_beta, mode=val_mode) - ones)

    return labels