コード例 #1
0
def compute_mws_segmentation(input_, offsets, n_attractive_channels, strides,
                             randomize_strides):
    vol_shape = input_.shape[1:]
    mst = mws.MutexWatershed(np.array(vol_shape), offsets,
                             n_attractive_channels, strides)
    if randomize_strides:
        mst.compute_randomized_bounds()
    sorted_edges = np.argsort(input_.ravel())
    mst.repulsive_mst_cut(sorted_edges)
    segmentation = mst.get_flat_label_image().reshape(vol_shape)
    return segmentation
コード例 #2
0
ファイル: isbi_2d.py プロジェクト: constantinpape/affogato
def mws_segmentation_old(affs, stride=np.array([1, 1]),
                         randomize_bounds=False):
    t0 = time.time()
    vol_shape = affs.shape[1:]
    sorted_edges = np.argsort(affs.ravel())
    # run the mst watershed
    seperating_channel = 2
    mst = mws.MutexWatershed(np.array(vol_shape), OFFSETS,
                             seperating_channel, stride)
    if randomize_bounds:
        mst.compute_randomized_bounds()
    mst.repulsive_mst_cut(sorted_edges)
    segmentation = mst.get_flat_label_image().reshape(vol_shape)
    return segmentation, time.time() - t0
コード例 #3
0
def run_mws(affinities,
            offsets, stride,
            seperating_channel=2,
            invert_dam_channels=True,
            bias_cut=0.,
            randomize_bounds=True):
    assert len(affinities) == len(offsets), "%s, %i" % (str(affinities.shape), len(offsets))
    affinities_ = np.require(affinities.copy(), requirements='C')
    if invert_dam_channels:
        affinities_[seperating_channel:] *= -1
        affinities_[seperating_channel:] += 1
    affinities_[:seperating_channel] += bias_cut
    sorted_edges = np.argsort(affinities_.ravel())
    # run the mst watershed
    vol_shape = affinities_.shape[1:]
    mst = mws.MutexWatershed(np.array(vol_shape),
                             offsets,
                             seperating_channel,
                             stride)
    if randomize_bounds:
        mst.compute_randomized_bounds()
    mst.repulsive_ucc_mst_cut(sorted_edges, 0)
    segmentation = mst.get_flat_label_image().reshape(vol_shape)
    return segmentation
コード例 #4
0
def run_mws(affinities, offsets, stride, var=None, cons_aff=False):
    assert len(affinities) == len(offsets), "%s, %i" % (str(
        affinities.shape), len(offsets))
    affinities_ = np.require(affinities.copy(), requirements='C')

    vol_shape = affinities_.shape[2:]
    print(vol_shape)

    affinities_ = affinities_.ravel()

    if var is not None:
        var_ = var.ravel()
        # get ids and values, sorted by value
        tmp = np.array(
            list(zip(var_, affinities_, list(range(len(affinities_))))))
        tmp5 = tmp[tmp[:, 0].argsort()[::-1]].transpose()
        _, sorted_edgesAff, sorted_edgesAffIds = tmp5
    elif cons_aff:
        affs = []
        reps = []
        print("splitting affs,reps")
        # for idx, a in enumerate(affinities_):
        #     if a < 0:
        #         reps.append((a, idx))
        #     elif a > 0:
        #         affs.append((a, idx))
        affs = zip(affinities_[affinities_ > 0], np.where(affinities_ > 0)[0])
        affs = np.array(list(affs))
        print(affs.shape)
        print("got affs")
        reps = zip(-affinities_[affinities_ < 0], np.where(affinities_ < 0)[0])
        # reps = zip(-affinities_[affinities_<=0], np.where(affinities_<=0)[0])
        reps = np.array(list(reps))
        print(reps.shape)
        print("done")
        print(len(reps), len(affs))
        print("sorting")
        affs_t = affs[affs[:, 0].argsort()[::-1]].transpose()
        sorted_edgesAff, sorted_edgesAffIds = affs_t
        reps_t = reps[reps[:, 0].argsort()[::-1]].transpose()
        sorted_edgesRep, sorted_edgesRepIds = reps_t
        print("done")
    else:
        print("getting reps")
        repulsions_ = 1.0 - affinities_
        repulsions_ = repulsions_.ravel()
        print("sorting affs")
        tmp = np.array(list(zip(affinities_, list(range(len(affinities_))))))
        tmp5 = tmp[tmp[:, 0].argsort()[::-1]].transpose()
        sorted_edgesAff, sorted_edgesAffIds = tmp5
        print("sorting reps")
        tmp = np.array(list(zip(repulsions_, list(range(len(repulsions_))))))
        tmp5 = tmp[tmp[:, 0].argsort()[::-1]].transpose()
        sorted_edgesRep, sorted_edgesRepIds = tmp5
    print(sorted_edgesAff.shape, sorted_edgesRep.shape)
    var = None

    # run the mst watershed
    print("starting mws")
    seperating_channel = 3  # ignored
    mst = mws.MutexWatershed(np.array(vol_shape), offsets, seperating_channel,
                             stride)
    mst.repulsive_ucc_mst_cut(sorted_edgesAff, sorted_edgesAffIds,
                              sorted_edgesRep, sorted_edgesRepIds,
                              len(sorted_edgesAff), len(sorted_edgesRep), 0,
                              var is not None)
    segmentation = mst.get_flat_label_image().reshape(vol_shape)
    return segmentation
コード例 #5
0
def test_cuf():

    C_ATTRACTIVE = 4
    EDGE_LEN = 512

    out_label = np.empty((30, EDGE_LEN, EDGE_LEN), dtype=np.int64)

    if C_ATTRACTIVE == 2:
        offsets = np.array([[-1, 0], [0, -1], [-27, 0], [0, -27]],
                           dtype=np.int)
    elif C_ATTRACTIVE == 3:
        offsets = np.array(
            [[-1, 0], [0, -1], [-1, -1], [-27, 0], [0, -27], [-27, -27]],
            dtype=np.int)
    else:
        offsets = np.array([[-1, 0], [0, -1], [-1, -1], [+1, -1], [-27, 0],
                            [0, -27], [-27, -27], [27, -27]],
                           dtype=np.int)

    for z_slice in [15]:

        with h5py.File(
                "/mnt/localdata01/swolf/ws/isbi/isbi_for_steffen/isbi_test_100k.h5",
                "r") as aff:
            if C_ATTRACTIVE == 2:
                affinities = aff["data"][:, z_slice, :EDGE_LEN, :EDGE_LEN][[
                    0, 1, 12, 13
                ]]
            elif C_ATTRACTIVE == 3:
                affinities = aff["data"][:, z_slice, :EDGE_LEN, :EDGE_LEN][[
                    0, 1, 2, 12, 13, 14
                ]]
            else:
                affinities = aff["data"][:, z_slice, :EDGE_LEN, :EDGE_LEN][[
                    0, 1, 2, 3, 12, 13, 14, 15
                ]]

        affinities[C_ATTRACTIVE:] *= -1
        affinities[C_ATTRACTIVE:] += 1.

        weight_shape = affinities.shape
        image_shape = weight_shape[1:]

        label_image = np.zeros(image_shape, dtype=np.int)
        label_image[:EDGE_LEN // 2] = 1
        label_image[:, :EDGE_LEN // 2] += 2
        label_image += 10

        # affinities[:, :, C_ATTRACTIVE:] += affinities[:, :, :C_ATTRACTIVE]
        # affinities[:, :, C_ATTRACTIVE:] /= 5

        # affinities[:, :, C_ATTRACTIVE:] += 10.
        # affinities[::4 ,::4, C_ATTRACTIVE:] -= 10.
        # for k in range(affinities.shape[0]):
        #     bound = np.array([MST_calculator._check_bounds(i, k) for i in range(label_image.flatten().size)])
        #     plt.imshow(bound.reshape(image_shape), interpolation=None)
        #     plt.savefig('bound_{}.png'.format(k), dpi=500)
        #     plt.close()
        f_affinities = affinities.flatten()

        for epoch in range(1):
            sorted_edges = np.argsort(f_affinities)
            MST_calculator = mws.MutexWatershed(np.array(image_shape), offsets,
                                                C_ATTRACTIVE,
                                                np.array([1, 1, 1]))
            # MST_calculator.clear_all()
            MST_calculator.set_gt_labels(label_image.flatten())

            start = time.time()
            gradients = MST_calculator.get_gradients(sorted_edges,
                                                     f_affinities, 0)
            # MST_calculator.repulsive_ucc_mst_cut(sorted_edges, 0)#[:int(EDGE_LEN*EDGE_LEN*C_ATTRACTIVE*0.5)])
            end = time.time()

            print("time ", end - start)
            # # sorted_edges = np.argsort(f_affinities)
            # MST_calculator.clear_all()
            # MST_calculator.set_gt_labels(label_image.flatten())

            # start = time.time()
            # # MST_calculator.get_gradients(sorted_edges, f_affinities, 0)
            # MST_calculator.repulsive_ucc_mst_cut(sorted_edges, 0)#[:int(EDGE_LEN*EDGE_LEN*C_ATTRACTIVE*0.5)])
            # end = time.time()

            # # errors_edges = MST_calculator.get_smoothmax_gradients2(f_affinities, -1)
            # print("time ", end - start)

            # # error_image = np.zeros(sorted_edges.shape)
            # # for k, e in errors_edges.items():
            # #     for x in e:
            # #         error_image[x] = k[2]

            # # error_image = error_image.reshape(affinities.shape)

            # # f_affinities -= 1000 *(errors_edges)
            # # f_affinities = np.clip(f_affinities,0,1)

            for k in range(affinities.shape[0]):
                plt.imshow(np.sign(gradients).reshape(affinities.shape)[k],
                           interpolation=None)
                plt.savefig('new_grads_{}_{}.png'.format(epoch, k), dpi=500)
                plt.close()

            # for k in range(affinities.shape[0]):
            #     plt.imshow(errors_edges.reshape(affinities.shape)[k], interpolation=None)
            #     plt.savefig('error_edges_{}_{}.png'.format(epoch, k), dpi=500)
            #     plt.close()

        #     fin_labels = MST_calculator.get_flat_label_image().reshape(image_shape)
        #     fin_labels += ((fin_labels.max()) * (fin_labels % 10))

        #     out_label[z_slice] = MST_calculator.get_flat_label_image().reshape(image_shape)
        #     plt.imshow(regionImageToCrackEdgeImage(fin_labels.astype(np.uint32)), interpolation=None)
        #     plt.savefig('seg_{}.png'.format(epoch), dpi=500)
        #     plt.close()

        # for k in range(affinities.shape[0]):
        #     plti.mshow(f_affinities.reshape(affinities.shape)[k], interpolation=None)
        #     plt.savefig('aff_{}_{}.png'.format(epoch, k), dpi=500)
        #     plt.close()

        exit()

        plt.imshow(regionImageToCrackEdgeImage(label_image.astype(np.uint32)),
                   interpolation=None)
        plt.savefig('gt_seg.png', dpi=500)
        plt.close()

        # out_label[z_slice] = MST_calculator.get_flat_label_image().reshape(image_shape)
        plt.imshow(regionImageToCrackEdgeImage(
            MST_calculator.get_flat_c_label_image().reshape(
                image_shape).astype(np.uint32)),
                   interpolation=None)
        plt.savefig('c_seg.png', dpi=500)
        plt.close()

        acts = MST_calculator.get_flat_applied_uc_actions().reshape(
            (-1, EDGE_LEN, EDGE_LEN))
        for k in range(acts.shape[0]):
            plt.imshow(acts[k], interpolation=None)
            plt.savefig('a_{}.png'.format(k), dpi=500)
            plt.close()

        acts = MST_calculator.get_flat_applied_c_actions().reshape(
            (-1, EDGE_LEN, EDGE_LEN))
        for k in range(acts.shape[0]):
            plt.imshow(acts[k], interpolation=None)
            plt.savefig('ca_{}.png'.format(k), dpi=500)
            plt.close()

        for k in range(affinities.shape[0]):
            plt.imshow(affinities[k], interpolation=None)
            plt.savefig('aff_{}.png'.format(k), dpi=500)
            plt.close()

    with h5py.File("out.h5", "w") as out:
        out.create_dataset("data", data=out_label, compression='gzip')
コード例 #6
0
def test_cuf():

    C_ATTRACTIVE = 3
    EDGE_LEN = 128
    Z_EDGE_LEN = 4

    offsets = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, -1],
            [-1, -1, 0], [-1, 0, -1], [-1, -1, -1], [-1, -1, 1],
            [0, -9, 0], [0, 0, -9], [0, -9, -9], [0, 9, -9],
            [0, -9, 4], [0, -4, -9], [0, 4, -9], [0, 9, -4],
            [-2, 0, 0], [-2, 0, -9], [-2, -9, 0], [-2, 9, -9],
            [-2, -9, -9], [-3, 0, 0], [0, -27, 0], [0, 0, -27]], dtype=np.int)


    with h5py.File("/export/home/swolf/local//src/data/experiments/isbi_3d/struct_05/isbi_test_3d.h5", "r") as aff:
        affinities = aff["data"][:, :Z_EDGE_LEN, :EDGE_LEN, :EDGE_LEN]

    affinities[C_ATTRACTIVE:] *= -1
    affinities[C_ATTRACTIVE:] += 1.

    weight_shape = affinities.shape
    image_shape = weight_shape[1:]

    label_image = np.zeros(image_shape, dtype=np.int)
    label_image[:15] = 1
    label_image[:, :EDGE_LEN//2] += 2
    label_image[:, :, :EDGE_LEN//2] += 2
    label_image += 10

    # affinities[:, :, C_ATTRACTIVE:] += affinities[:, :, :C_ATTRACTIVE]
    # affinities[:, :, C_ATTRACTIVE:] /= 5

    # affinities[:, :, C_ATTRACTIVE:] += 10.
    # affinities[::4 ,::4, C_ATTRACTIVE:] -= 10.
    # for k in range(affinities.shape[0]):
    #     bound = np.array([MST_calculator._check_bounds(i, k) for i in range(label_image.flatten().size)])
    #     plt.imshow(bound.reshape(image_shape), interpolation=None)
    #     plt.savefig('bound_{}.png'.format(k), dpi=500)
    #     plt.close()
    f_affinities = affinities.flatten()

    sorted_edges = np.argsort(f_affinities)
    MST_calculator = mws.MutexWatershed(np.array(image_shape), offsets, C_ATTRACTIVE, np.array([1,2,2]))
    # MST_calculator.clear_all()
    MST_calculator.set_gt_labels(label_image.flatten())



    start = time.time()
    gradients = MST_calculator.get_gradients(sorted_edges, f_affinities, 0)
    # MST_calculator.repulsive_ucc_mst_cut(sorted_edges, 0)#[:int(EDGE_LEN*EDGE_LEN*C_ATTRACTIVE*0.5)])
    end = time.time()

    print("time ", end - start)


        # # sorted_edges = np.argsort(f_affinities)
            # MST_calculator.clear_all()
            # MST_calculator.set_gt_labels(label_image.flatten())

            # start = time.time()
            # # MST_calculator.get_gradients(sorted_edges, f_affinities, 0)
            # MST_calculator.repulsive_ucc_mst_cut(sorted_edges, 0)#[:int(EDGE_LEN*EDGE_LEN*C_ATTRACTIVE*0.5)])
            # end = time.time()


            # # errors_edges = MST_calculator.get_smoothmax_gradients2(f_affinities, -1)
            # print("time ", end - start)

            # # error_image = np.zeros(sorted_edges.shape)
            # # for k, e in errors_edges.items():
            # #     for x in e:
            # #         error_image[x] = k[2]

            # # error_image = error_image.reshape(affinities.shape)


            # # f_affinities -= 1000 *(errors_edges)
            # # f_affinities = np.clip(f_affinities,0,1)


            # for k in range(affinities.shape[0]):
            #     plt.imshow(np.sign(gradients).reshape(affinities.shape)[k], interpolation=None)
            #     plt.savefig('new_grads_{}_{}.png'.format(epoch, k), dpi=500)
            #     plt.close()

            # for k in range(affinities.shape[0]):
            #     plt.imshow(errors_edges.reshape(affinities.shape)[k], interpolation=None)
            #     plt.savefig('error_edges_{}_{}.png'.format(epoch, k), dpi=500)
            #     plt.close()


        #     fin_labels = MST_calculator.get_flat_label_image().reshape(image_shape)
        #     fin_labels += ((fin_labels.max()) * (fin_labels % 10))

        #     out_label[z_slice] = MST_calculator.get_flat_label_image().reshape(image_shape)
        #     plt.imshow(regionImageToCrackEdgeImage(fin_labels.astype(np.uint32)), interpolation=None)
        #     plt.savefig('seg_{}.png'.format(epoch), dpi=500)
        #     plt.close()

        # for k in range(affinities.shape[0]):
        #     plti.mshow(f_affinities.reshape(affinities.shape)[k], interpolation=None)
        #     plt.savefig('aff_{}_{}.png'.format(epoch, k), dpi=500)
        #     plt.close()

    exit()
コード例 #7
0
import mutex_watershed as mws
import numpy as np

height = 4

ws = mws.MutexWatershed(np.array([height,10]), np.array([[-1,0],[0,-1], [-3,0],[0,-3]]), 2, 1)
labels = np.ones((height,10))
labels[:, :5] = 2

ws.set_gt_labels(labels)
mask = np.zeros(labels.shape, dtype=np.bool)
mask[:, 4:6] = 1
ws.set_masked_gt_image(mask)

sorted_w = np.argsort(np.random.rand(height*10*4))

s = 1
while not ws.is_finised():
    ws.repulsive_ucc_mst_cut(sorted_w, s)
    print(ws.get_flat_c_label_image().reshape((height, 10)), ws.get_flat_region_gt_label_image().reshape((height, 10)))
    # print(ws.get_flat_applied_c_actions().reshape((4, height, 10))[[1,3]])
    print("")
    s += 1