Exemplo n.º 1
0
def test_bbox():
    img = np.zeros((10, 10), np.uint16)

    a0, b0, a1, b1 = bbox(img)
    assert a0 == b0
    assert a1 == b1

    img[4, 2] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 5
    assert a1 == 2
    assert b1 == 3

    img[6, 8] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 7
    assert a1 == 2
    assert b1 == 9

    img[7, 7] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 8
    assert a1 == 2
    assert b1 == 9
Exemplo n.º 2
0
 def nozeros_test(f):
     result = mh.labeled.bbox(f)
     result_as = mh.labeled.bbox(f, as_slice=True)
     assert not np.all(result == 0)
     for ix in range(4):
         assert np.all(result[ix] == mh.bbox(f == ix))
         assert np.all(result_as[ix] == mh.bbox(f == ix, as_slice=True))
Exemplo n.º 3
0
 def nozeros_test(f):
     result = mh.labeled.bbox(f)
     result_as = mh.labeled.bbox(f, as_slice=True)
     assert not np.all(result == 0)
     for ix in range(4):
         assert np.all(result[ix] == mh.bbox(f == ix))
         assert np.all(result_as[ix] == mh.bbox(f == ix, as_slice=True))
Exemplo n.º 4
0
def test_bbox():
    img = np.zeros((10, 10), np.uint16)

    a0, b0, a1, b1 = bbox(img)
    assert a0 == b0
    assert a1 == b1

    img[4, 2] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 5
    assert a1 == 2
    assert b1 == 3

    img[6, 8] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 7
    assert a1 == 2
    assert b1 == 9

    img[7, 7] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 8
    assert a1 == 2
    assert b1 == 9
Exemplo n.º 5
0
def test_labeled_bbox():
    f = np.random.random((128, 128))
    f = f > .8
    f, n = mh.label(f)

    result = mh.labeled.bbox(f)
    result_as = mh.labeled.bbox(f, as_slice=True)
    for _ in range(32):
        ix = np.random.randint(n + 1)
        assert np.all(result[ix] == mh.bbox(f == ix))
        assert np.all(result_as[ix] == mh.bbox(f == ix, as_slice=True))
Exemplo n.º 6
0
def test_labeled_bbox():
    f = np.random.random((128,128))
    f = f > .8
    f,n = mh.label(f)


    result = mh.labeled.bbox(f)
    result_as = mh.labeled.bbox(f, as_slice=True)
    for _ in range(32):
        ix = np.random.randint(n+1)
        assert np.all(result[ix] == mh.bbox(f == ix))
        assert np.all(result_as[ix] == mh.bbox(f == ix, as_slice=True))
Exemplo n.º 7
0
def test_slice_border():
    'Test bbox(slice=True, border=6) in 2D & 3D'
    f = np.zeros((32,32), bool)
    f[8:8] = 1
    m0,M0, m1,M1 = mh.bbox(f, border=6, as_slice=False)
    sl = mh.bbox(f, border=6, as_slice=True)

    assert np.all(f[sl] == f[m0:M0, m1:M1])

    f = np.zeros((32,32, 32), bool)
    f[8:8,12:15] = 1
    m0,M0, m1,M1, m2, M2 = mh.bbox(f, border=6, as_slice=False)
    sl = mh.bbox(f, border=6, as_slice=True)

    assert np.all(f[sl] == f[m0:M0, m1:M1, m2:M2])
Exemplo n.º 8
0
def test_slice_border():
    'Test bbox(slice=True, border=6) in 2D & 3D'
    f = np.zeros((32, 32), bool)
    f[8:8] = 1
    m0, M0, m1, M1 = mh.bbox(f, border=6, as_slice=False)
    sl = mh.bbox(f, border=6, as_slice=True)

    assert np.all(f[sl] == f[m0:M0, m1:M1])

    f = np.zeros((32, 32, 32), bool)
    f[8:8, 12:15] = 1
    m0, M0, m1, M1, m2, M2 = mh.bbox(f, border=6, as_slice=False)
    sl = mh.bbox(f, border=6, as_slice=True)

    assert np.all(f[sl] == f[m0:M0, m1:M1, m2:M2])
Exemplo n.º 9
0
    def __init__(self, length, radius, curvature, pad_width=5, name=None):
        a2 = curvature
        xl = radius + pad_width
        xr = fsolve(calc_length, length, args=(xl, a2, length)).squeeze()
        a1 = -a2 * (xr + xl)
        r = radius
        xm = (xl + xr) / 2
        y_mid = a1*xm + a2*xm**2
        a0 = 4*radius - y_mid + pad_width

        y_max = a0 + a1 * xr + a2 * xr ** 2
        shape = tuple(np.ceil([y_max + 10 + r, xr + 2 * r + 10]).astype(int))
        coords = Coordinates(None, a0=a0, a1=a1, a2=a2, xl=xl, xr=xr, r=r, shape=shape, initialize=False)
        binary = coords.rc < r

        min1, max1, min2, max2 = mh.bbox(binary)
        min1p, max1p, min2p, max2p = min1 - pad_width, max1 + pad_width, min2 - pad_width, max2 + pad_width
        full = np.zeros((np.max([max1p, binary.shape[0]]), np.max([max2p, binary.shape[1]])))
        full[0:binary.shape[0], 0:binary.shape[1]] = binary

        res = full[min1p:max1p, 0:max2p]

        data = Data()
        data.add_data(res.astype(int), 'binary')
        super(SynthCell, self).__init__(data, name=name)
        self.coords.a0 = a0 - min1p
        self.coords.a1 = a1
        self.coords.a2 = a2
        self.coords.xl = xl
        self.coords.xr = xr
        self.coords.r = r
Exemplo n.º 10
0
def test_as_slice():
    YXZ = np.indices((32,32,64), float)
    YXZ -= 8
    Y,X,Z = YXZ
    ball = ((X**2+Y**2+Z**2) < 64).astype(np.uint8)
    s = bbox(ball, as_slice=True)
    assert ball[s].sum() == ball.sum()
Exemplo n.º 11
0
def test_as_slice():
    YXZ = np.indices((32, 32, 64), float)
    YXZ -= 8
    Y, X, Z = YXZ
    ball = ((X**2 + Y**2 + Z**2) < 64).astype(np.uint8)
    s = bbox(ball, as_slice=True)
    assert ball[s].sum() == ball.sum()
Exemplo n.º 12
0
    def split(image, array, label):
        '''
        '''

        large_label = Util.threshold(array, label)

        label_bbox = mh.bbox(large_label)
        label = large_label[label_bbox[0]:label_bbox[1],
                            label_bbox[2]:label_bbox[3]]
        image = image[label_bbox[0]:label_bbox[1], label_bbox[2]:label_bbox[3]]

        #
        # smooth the image
        #
        image = mh.gaussian_filter(image, 3.5)

        grad_x = np.gradient(image)[0]
        grad_y = np.gradient(image)[1]
        grad = np.add(np.abs(grad_x), np.abs(grad_y))
        #grad = np.add(np.abs(grad_x), np.abs(grad_y))
        grad -= grad.min()
        grad /= grad.max()
        grad *= 255
        grad = grad.astype(np.uint8)
        #imshow(grad)

        # we need 4 labels as output
        max_label = 0
        #while max_label!=3:

        coords = zip(*np.where(label == 1))

        seed1 = random.choice(coords)
        seed2 = random.choice(coords)
        seeds = np.zeros(label.shape, dtype=np.uint64)
        seeds[seed1] = 1
        seeds[seed2] = 2
        #         imshow(seeds)
        for i in range(10):
            seeds = mh.dilate(seeds)

        ws = mh.cwatershed(grad, seeds)
        ws[label == 0] = 0

        ws_relabeled = skimage.measure.label(ws.astype(np.uint64))
        max_label = ws_relabeled.max()
        #print max_label

        large_label = np.zeros(large_label.shape, dtype=np.uint64)
        large_label[label_bbox[0]:label_bbox[1],
                    label_bbox[2]:label_bbox[3]] = ws
        return large_label
Exemplo n.º 13
0
def test_bbox_3():
    YXZ = np.indices((32,32,64), float)
    YXZ -= 8
    Y,X,Z = YXZ
    ball = ((X**2+Y**2+Z**2) < 64).astype(np.uint8)
    m0,M0,m1,M1,m2,M2 = mahotas.bbox(ball)

    Y,X,Z = np.where(ball)
    assert np.all(m0 <= Y)
    assert np.all(m1 <= X)
    assert np.all(m2 <= Z)
    assert np.all(M0 > Y)
    assert np.all(M1 > X)
    assert np.all(M2 > Z)
Exemplo n.º 14
0
def test_bbox_3():
    YXZ = np.indices((32, 32, 64), float)
    YXZ -= 8
    Y, X, Z = YXZ
    ball = ((X**2 + Y**2 + Z**2) < 64).astype(np.uint8)
    m0, M0, m1, M1, m2, M2 = mahotas.bbox(ball)

    Y, X, Z = np.where(ball)
    assert np.all(m0 <= Y)
    assert np.all(m1 <= X)
    assert np.all(m2 <= Z)
    assert np.all(M0 > Y)
    assert np.all(M1 > X)
    assert np.all(M2 > Z)
Exemplo n.º 15
0
    def read_dojo_data():
        input_image = np.zeros((10, 1024, 1024))
        input_rhoana = np.zeros((10, 1024, 1024))
        input_gold = np.zeros((10, 1024, 1024))
        input_prob = np.zeros((10, 1024, 1024))
        input_rhoana = tif.imread(
            '/Users/d/Projects/dojo_data_vis2014/labels_after_automatic_segmentation_multi.tif'
        )
        input_gold = tif.imread(
            '/Users/d/Projects/dojo_data_vis2014/groundtruth_multi.tif')
        for i in range(10):
            input_prob[i] = tif.imread(
                '/Users/d/Projects/dojo_data_vis2014/prob/' + str(i) +
                '_syn.tif')
            input_image[i] = tif.imread(
                '/Users/d/Projects/dojo_data_vis2014/images/' + str(i) +
                '.tif')

        bbox = mh.bbox(input_image[0])
        bbox_larger = [bbox[0] - 37, bbox[1] + 37, bbox[2] - 37, bbox[3] + 37]

        prob_new = np.zeros(input_image.shape, dtype=np.uint8)

        input_image = input_image[:, bbox_larger[0]:bbox_larger[1],
                                  bbox_larger[2]:bbox_larger[3]]
        input_rhoana = input_rhoana[:, bbox_larger[0]:bbox_larger[1],
                                    bbox_larger[2]:bbox_larger[3]]
        input_gold = input_gold[:, bbox_larger[0]:bbox_larger[1],
                                bbox_larger[2]:bbox_larger[3]]
        # input_prob = input_prob[:, bbox_larger[0]:bbox_larger[1], bbox_larger[2]:bbox_larger[3]]

        prob_new[:, bbox[0]:bbox[1],
                 bbox[2]:bbox[3]] = input_prob[:, bbox[0]:bbox[1],
                                               bbox[2]:bbox[3]]
        prob_new = prob_new[:, bbox_larger[0]:bbox_larger[1],
                            bbox_larger[2]:bbox_larger[3]]

        for i in range(0, 10):
            zeros_gold = Util.threshold(input_gold[i], 0)
            input_gold[i] = Util.normalize_labels(
                skimage.measure.label(input_gold[i]).astype(np.uint64))[0]
            # restore zeros
            input_gold[i][zeros_gold == 1] = 0
            input_rhoana[i] = Util.normalize_labels(
                skimage.measure.label(input_rhoana[i]).astype(np.uint64))[0]

        return input_image.astype(np.uint8), prob_new.astype(
            np.uint8), input_gold.astype(np.uint32), input_rhoana.astype(
                np.uint32), bbox_larger
Exemplo n.º 16
0
    def read_dojo_section(num, keep_zeros=False, fill_zeros=False, crop=True):

        DATA_PATH = '/Users/d/Projects/dojo_data_vis2014'
        if not os.path.isdir(DATA_PATH):
            DATA_PATH = '/n/regal/pfister_lab/haehn/dojo_data_vis2014/'
        GOLD_PATH = os.path.join(DATA_PATH, 'groundtruth/')
        RHOANA_PATH = os.path.join(DATA_PATH,
                                   'labels_after_automatic_segmentation/')
        IMAGE_PATH = os.path.join(DATA_PATH, 'images/')
        PROB_PATH = os.path.join(DATA_PATH, 'prob/')

        gold = tif.imread(GOLD_PATH + str(num) + '.tif')
        rhoana = tif.imread(RHOANA_PATH + os.sep + str(num) + ".tif")
        image = tif.imread(IMAGE_PATH + str(num) + '.tif')
        prob = tif.imread(PROB_PATH + str(num) + '_syn.tif')

        gold_original = np.array(gold)
        gold = Util.normalize_labels(
            skimage.measure.label(gold).astype(np.uint64))[0]
        gold[gold == 0] = gold.max() + 1

        rhoana = Util.normalize_labels(
            skimage.measure.label(rhoana).astype(np.uint64))[0]

        # do we want to subtract the zeros?
        if keep_zeros:
            gold[gold_original == 0] = 0
            # rhoana[gold_original == 0] = 0

        if fill_zeros:
            gold[gold_original == 0] = 0
            gold_zeros = Util.threshold(gold, 0)
            gold = Util.fill(gold, gold_zeros.astype(np.bool))

        if crop:
            bbox = mh.bbox(image)
            bbox_larger = [
                bbox[0] - 37, bbox[1] + 37, bbox[2] - 37, bbox[3] + 37
            ]
            prob_new = prob
        else:
            bbox = bbox_larger = [0, 1024, 0, 1024]
            prob_new = np.zeros(image.shape, dtype=np.uint8)
            prob_new[bbox[0]:bbox[1], bbox[2]:bbox[3]] = prob[bbox[0]:bbox[1],
                                                              bbox[2]:bbox[3]]

        return Util.crop_by_bbox(image, bbox_larger), Util.crop_by_bbox(
            prob_new, bbox_larger), Util.crop_by_bbox(
                gold, bbox_larger), Util.crop_by_bbox(rhoana, bbox_larger)
Exemplo n.º 17
0
    def merge_label(image,
                    prob,
                    segmentation,
                    label1,
                    label2,
                    crop=True,
                    patch_size=(100, 100)):
        '''
    '''
        copy_segmentation = np.array(segmentation)

        border = mh.labeled.border(segmentation, label1, label2)

        copy_segmentation[copy_segmentation == label2] = label1

        binary = Util.threshold(copy_segmentation, label1)

        if crop:
            bbox = mh.bbox(Util.threshold(copy_segmentation, label1))
            bbox = [
                bbox[0] - patch_size[0], bbox[1] + patch_size[0],
                bbox[2] - patch_size[1], bbox[3] + patch_size[1]
            ]

            cropped_image = Util.crop_by_bbox(image, bbox)
            cropped_binary = Util.crop_by_bbox(binary, bbox)
            cropped_prob = Util.crop_by_bbox(prob, bbox)
            cropped_segmentation = Util.crop_by_bbox(copy_segmentation, bbox)

            return cropped_image, cropped_prob, cropped_segmentation, cropped_binary, bbox, Util.crop_by_bbox(
                border, bbox)

        else:

            return image, prob, copy_segmentation, binary, [
                0, segmentation.shape[0], 0, segmentation.shape[1]
            ]
Exemplo n.º 18
0
def get_bbox_for_object(labeled_mask, object_idx=1, padding=0):
    """
    get the rectangular border of a specific object in a labeled mask.
    :param labeled_mask: a 2D numpy array of type `int` consisting of labeled segmented objects.
    :param object_idx: the label of the object to extract from the mask (default 1).
    :param padding: the amount of padding to add to each side of the box (default 0).
    :return: a tuple (min_x, min_y, max_x, max_y) representing the top left and bottom right corners of the bounding
             box.
    """
    # extract desired object from mask
    obj_msk = (labeled_mask == object_idx).astype(int)

    # find bbox
    min_y, max_y, min_x, max_x = __mh.bbox(obj_msk)

    # add padding
    min_y, max_y, min_x, max_x = min_y - padding, max_y + padding, min_x - padding, max_x + padding

    # assert that the box boundaries are within the mask's boundaries
    rows, cols = labeled_mask.shape
    min_y, max_y = __np.max((0, min_y)), __np.min((rows, max_y))
    min_x, max_x = __np.max((0, min_x)), __np.min((cols, max_x))

    return min_x, min_y, max_x, max_y
Exemplo n.º 19
0
def test_bbox():
    img = np.zeros((10, 10), np.uint16)

    a0, b0, a1, b1 = bbox(img)
    assert a0 == b0
    assert a1 == b1

    img[4, 2] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 5
    assert a1 == 2
    assert b1 == 3

    img[6, 8] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 7
    assert a1 == 2
    assert b1 == 9

    img[7, 7] = 1
    a0, b0, a1, b1 = bbox(img)
    assert a0 == 4
    assert b0 == 8
    assert a1 == 2
    assert b1 == 9

    c0, d0, c1, d1 = bbox(img, 0)
    assert c0 == a0
    assert b0 == d0
    assert c1 == a1
    assert b1 == d1

    c0, d0, c1, d1 = bbox(img, 1)
    assert c0 != a0
    assert b0 != d0
    assert c1 != a1
    assert b1 != d1
Exemplo n.º 20
0
def test_bbox():
    img = np.zeros((10,10), np.uint16)
    
    a0,b0,a1,b1 = bbox(img)
    assert a0 == b0
    assert a1 == b1

    img[4,2]=1
    a0,b0,a1,b1=bbox(img)
    assert a0 == 4
    assert b0 == 5
    assert a1 == 2
    assert b1 == 3

    img[6,8]=1
    a0,b0,a1,b1=bbox(img)
    assert a0 == 4 
    assert b0 == 7 
    assert a1 == 2 
    assert b1 == 9 

    img[7,7]=1
    a0,b0,a1,b1=bbox(img)
    assert a0 == 4
    assert b0 == 8
    assert a1 == 2
    assert b1 == 9

    c0,d0,c1,d1=bbox(img, 0)
    assert c0 == a0
    assert b0 == d0
    assert c1 == a1
    assert b1 == d1

    c0,d0,c1,d1=bbox(img, 1)
    assert c0 != a0
    assert b0 != d0
    assert c1 != a1
    assert b1 != d1
Exemplo n.º 21
0
  def fix_single_merge(cnn, cropped_image, cropped_prob, cropped_binary, N=10, invert=True, dilate=True, 
                       border_seeds=True, erode=False, debug=False, before_merge_error=None,
                       real_border=np.zeros((1,1)), oversampling=False, crop=True):
    '''
    invert: True/False for invert or gradient image
    '''

    bbox = mh.bbox(cropped_binary)

    orig_cropped_image = np.array(cropped_image)
    orig_cropped_prob  = np.array(cropped_prob)
    orig_cropped_binary = np.array(cropped_binary)



    speed_image = None
    if invert:
      speed_image = Legacy.invert(cropped_image, smooth=True, sigma=2.5)
    else:
      speed_image = Legacy.gradient(cropped_image)

    Util.view(speed_image, large=False, color=False)


    dilated_binary = np.array(cropped_binary, dtype=np.bool)
    if dilate:
      for i in range(20):
          dilated_binary = mh.dilate(dilated_binary)      

    Util.view(dilated_binary, large=False, color=False)

    borders = np.zeros(cropped_binary.shape)

    best_border_prediction = np.inf
    best_border_image = np.zeros(cropped_binary.shape)

    original_border = mh.labeled.border(cropped_binary, 1, 0, Bc=mh.disk(3))

    results_no_border = []
    predictions = []
    borders = []
    results = []

    for n in range(N):
        ws = Legacy.random_watershed(dilated_binary, speed_image, border_seeds=border_seeds, erode=erode)
        
        if ws.max() == 0:
          continue

        ws_label1 = ws.max()
        ws_label2 = ws.max()-1
        border = mh.labeled.border(ws, ws_label1, ws_label2)

        # Util.view(ws, large=True)


        # Util.view(border, large=True)

        # print i, len(border[border==True])

        #
        # remove parts of the border which overlap with the original border
        #

        

        ws[cropped_binary == 0] = 0

        # Util.view(ws, large=False, color=False)        

        ws_label1_array = Util.threshold(ws, ws_label1)
        ws_label2_array = Util.threshold(ws, ws_label2)

        eroded_ws1 = np.array(ws_label1_array, dtype=np.bool)
        eroded_ws2 = np.array(ws_label2_array, dtype=np.bool)
        if erode:

          for i in range(5):
            eroded_ws1 = mh.erode(eroded_ws1)

          # Util.view(eroded_ws, large=True, color=False)

          dilated_ws1 = np.array(eroded_ws1)
          for i in range(5):
            dilated_ws1 = mh.dilate(dilated_ws1)


          for i in range(5):
            eroded_ws2 = mh.erode(eroded_ws2)

          # Util.view(eroded_ws, large=True, color=False)

          dilated_ws2 = np.array(eroded_ws2)
          for i in range(5):
            dilated_ws2 = mh.dilate(dilated_ws2)




          new_ws = np.zeros(ws.shape, dtype=np.uint8)
          new_ws[dilated_ws1 == 1] = ws_label1
          new_ws[dilated_ws2 == 1] = ws_label2


          ws = new_ws

          # Util.view(new_ws, large=True, color=True)

        # ws[original_border == 1] = 0
        
        prediction = Patch.grab_group_test_and_unify(cnn, cropped_image, cropped_prob, ws, ws_label1, ws_label2, oversampling=oversampling)
        
        if prediction == -1 or prediction >= .5:
          # invalid
          continue


        # here we have for one border
        # the border
        # the prediction
        # borders.append(border)
        # predictions.append(prediction)
        results.append((prediction, border))



    return results
def grab_patch(image,
               prob,
               segmentation,
               l,
               n,
               patch_size=(75, 75),
               skip_boundaries=False,
               sample_rate=1):

    borders = mh.labeled.border(segmentation, l, n)

    #
    # treat interrupted borders separately
    #
    borders_labeled = skimage.measure.label(borders)

    border_bbox = mh.bbox(borders)

    patch_centers = []
    border_yx = indices = zip(*np.where(borders == 1))

    if len(border_yx) < 2:
        return []

    # always sample the middle point
    border_center = (border_yx[len(border_yx) / (2)][0],
                     border_yx[len(border_yx) / (2)][1])
    patch_centers.append(border_center)

    if sample_rate > 1 or sample_rate == -1:
        if sample_rate > len(border_yx) or sample_rate == -1:
            samples = 1
        else:
            samples = len(border_yx) / sample_rate

        for i, s in enumerate(border_yx):

            if i % samples == 0:

                sample_point = s

                if distance.euclidean(patch_centers[-1],
                                      sample_point) < patch_size[0]:
                    # sample to close
                    # print 'sample to close', patch_centers[-1], sample_point
                    continue

                patch_centers.append(sample_point)

    borders_w_center = np.array(borders.astype(np.uint8))

    for i, c in enumerate(patch_centers):

        borders_w_center[c[0], c[1]] = 10 * (i + 1)
        # print 'marking', c, borders_w_center.shape

    # if debug:
    #     fig = plt.figure(figsize=(5,5))
    #     fig.text(0,1,'\n\n\n\n\nAll borders '+str(l)+','+str(n))#+'\n\n'+str(np.round(_matrices[u], 2)))
    #     plt.imshow(borders_labeled[border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]], interpolation='nearest')
    #     fig = plt.figure(figsize=(5,5))
    #     fig.text(0,1,'\n\n\n\n\nWith center(s) '+str(l)+','+str(n))#+'\n\n'+str(np.round(_matrices[u], 2)))
    #     plt.imshow(borders_w_center[border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]], interpolation='nearest')#, cmap='ocean')

    patches = []

    for i, c in enumerate(patch_centers):

        #         for border_center in patch_centers:

        # check if border_center is too close to the 4 edges
        new_border_center = [c[0], c[1]]

        if new_border_center[0] < patch_size[0] / 2:
            # print 'oob1', new_border_center
            # return None
            continue
        if new_border_center[0] + patch_size[0] / 2 >= segmentation.shape[0]:
            # print 'oob2', new_border_center
            # return None
            continue
        if new_border_center[1] < patch_size[1] / 2:
            # print 'oob3', new_border_center
            # return None
            continue
        if new_border_center[1] + patch_size[1] / 2 >= segmentation.shape[1]:
            # print 'oob4', new_border_center
            # return None
            continue
        # print new_border_center, patch_size[0]/2, border_center[0] < patch_size[0]/2

        # continue

        bbox = [
            new_border_center[0] - patch_size[0] / 2,
            new_border_center[0] + patch_size[0] / 2,
            new_border_center[1] - patch_size[1] / 2,
            new_border_center[1] + patch_size[1] / 2
        ]

        ### workaround to not sample white border of probability map
        if skip_boundaries:
            if bbox[0] <= 33:

                continue
            if bbox[1] >= segmentation.shape[0] - 33:

                continue
            if bbox[2] <= 33:

                continue
            if bbox[3] >= segmentation.shape[1] - 33:

                continue

        # threshold for label1
        array1 = _metrics.Util.threshold(segmentation, l).astype(np.uint8)
        # threshold for label2
        array2 = _metrics.Util.threshold(segmentation, n).astype(np.uint8)
        merged_array = array1 + array2

        # dilate for overlap
        dilated_array1 = np.array(array1)
        dilated_array2 = np.array(array2)
        for o in range(10):
            dilated_array1 = mh.dilate(dilated_array1.astype(np.uint64))
            dilated_array2 = mh.dilate(dilated_array2.astype(np.uint64))
        overlap = np.logical_and(dilated_array1, dilated_array2)
        overlap[merged_array == 0] = 0

        output = {}
        output['id'] = str(uuid.uuid4())
        output['image'] = image[bbox[0]:bbox[1] + 1, bbox[2]:bbox[3] + 1]

        output['prob'] = prob[bbox[0]:bbox[1] + 1, bbox[2]:bbox[3] + 1]

        output['l'] = l
        output['n'] = n
        output['bbox'] = bbox
        output['border'] = border_yx
        output['border_center'] = new_border_center
        output['binary1'] = array1[bbox[0]:bbox[1] + 1,
                                   bbox[2]:bbox[3] + 1].astype(np.bool)
        # output['binary2'] = array2[bbox[0]:bbox[1] + 1, bbox[2]:bbox[3] + 1].astype(np.bool)
        output['overlap'] = overlap[bbox[0]:bbox[1] + 1,
                                    bbox[2]:bbox[3] + 1].astype(np.bool)
        output['borders_labeled'] = borders_labeled[
            border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]]
        output['borders_w_center'] = borders_w_center[
            border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]]

        patches.append(output)

    return patches
Exemplo n.º 23
0
    def fix_single_merge(cnn,
                         cropped_image,
                         cropped_prob,
                         cropped_binary,
                         N=10,
                         invert=True,
                         dilate=True,
                         border_seeds=True,
                         erode=False,
                         debug=False,
                         before_merge_error=None,
                         real_border=np.zeros((1, 1)),
                         oversampling=False,
                         crop=True):
        '''
    invert: True/False for invert or gradient image
    '''

        bbox = mh.bbox(cropped_binary)

        orig_cropped_image = np.array(cropped_image)
        orig_cropped_prob = np.array(cropped_prob)
        orig_cropped_binary = np.array(cropped_binary)

        speed_image = None
        if invert:
            speed_image = Util.invert(cropped_image, smooth=True, sigma=2.5)
        else:
            speed_image = Util.gradient(cropped_image)

        dilated_binary = np.array(cropped_binary, dtype=np.bool)
        if dilate:
            for i in range(20):
                dilated_binary = mh.dilate(dilated_binary)

        # Util.view(dilated_binary, large=True)

        borders = np.zeros(cropped_binary.shape)

        best_border_prediction = np.inf
        best_border_image = np.zeros(cropped_binary.shape)

        original_border = mh.labeled.border(cropped_binary,
                                            1,
                                            0,
                                            Bc=mh.disk(3))

        results_no_border = []
        predictions = []

        for n in range(N):
            ws = Util.random_watershed(dilated_binary,
                                       speed_image,
                                       border_seeds=border_seeds,
                                       erode=erode)

            if ws.max() == 0:
                continue

            ws_label1 = ws.max()
            ws_label2 = ws.max() - 1
            border = mh.labeled.border(ws, ws_label1, ws_label2)

            # Util.view(ws, large=True)

            # Util.view(border, large=True)

            # print i, len(border[border==True])

            #
            # remove parts of the border which overlap with the original border
            #

            ws[cropped_binary == 0] = 0

            # Util.view(ws, large=False, color=False)

            ws_label1_array = Util.threshold(ws, ws_label1)
            ws_label2_array = Util.threshold(ws, ws_label2)

            eroded_ws1 = np.array(ws_label1_array, dtype=np.bool)
            eroded_ws2 = np.array(ws_label2_array, dtype=np.bool)
            if erode:

                for i in range(5):
                    eroded_ws1 = mh.erode(eroded_ws1)

                # Util.view(eroded_ws, large=True, color=False)

                dilated_ws1 = np.array(eroded_ws1)
                for i in range(5):
                    dilated_ws1 = mh.dilate(dilated_ws1)

                for i in range(5):
                    eroded_ws2 = mh.erode(eroded_ws2)

                # Util.view(eroded_ws, large=True, color=False)

                dilated_ws2 = np.array(eroded_ws2)
                for i in range(5):
                    dilated_ws2 = mh.dilate(dilated_ws2)

                new_ws = np.zeros(ws.shape, dtype=np.uint8)
                new_ws[dilated_ws1 == 1] = ws_label1
                new_ws[dilated_ws2 == 1] = ws_label2

                ws = new_ws

                # Util.view(new_ws, large=True, color=True)

            # ws[original_border == 1] = 0

            prediction = Patch.grab_group_test_and_unify(
                cnn,
                cropped_image,
                cropped_prob,
                ws,
                ws_label1,
                ws_label2,
                oversampling=oversampling)

            if prediction == -1:
                # invalid
                continue

            # if (prediction < best_border_prediction):
            #   best_border_prediction = prediction
            #   best_border_image = border
            #   print 'new best', n, prediction

            best_border_image = border

            borders += (border * prediction)

            result = np.array(cropped_binary)
            best_border_image[result == 0] = 0
            result[best_border_image == 1] = 2

            result = skimage.measure.label(result)

            result_no_border = np.array(result)
            result_no_border[best_border_image == 1] = 0

            predictions.append(prediction)
            results_no_border.append(result_no_border)

        # result = np.array(cropped_binary)
        # best_border_image[result==0] = 0
        # result[best_border_image==1] = 2

        # result = skimage.measure.label(result)

        # result_no_border = np.array(result)
        # result_no_border[best_border_image==1] = 0
        # result_no_border = mh.croptobbox(result_no_border)

        # if before_merge_error == None:
        #   continue

        # print result_no_border.shape, before_merge_error.shape

        # if before_merge_error.shape[0] != result_no_border.shape[0] or before_merge_error.shape[1] != result_no_border.shape[1]:
        #   result_no_border = np.resize(result_no_border, before_merge_error.shape)

        # print 'vi', Util.vi(before_merge_error.astype(np.uint8), result_no_border.astype(np.uint8))

        #     if debug:
        #       Util.view(ws, text=str(i) + ' ' + str(prediction))

        result = np.array(cropped_binary)
        best_border_image[result == 0] = 0
        result[best_border_image == 1] = 2

        result = skimage.measure.label(result)

        result_no_border = np.array(result)
        result_no_border[best_border_image == 1] = 0

        return borders, best_border_image, result, result_no_border, results_no_border, predictions
Exemplo n.º 24
0
    def analyze_border(image,
                       prob,
                       segmentation,
                       l,
                       n,
                       patch_size=(75, 75),
                       sample_rate=10):

        borders = mh.labeled.border(segmentation, l, n)

        #
        # treat interrupted borders separately
        #
        borders_labeled = skimage.measure.label(borders)

        border_bbox = mh.bbox(borders)

        patches = []

        patch_centers = []
        border_yx = indices = zip(*np.where(borders == 1))

        if len(border_yx) < 2:
            # somehow border detection did not work
            return patches

        # always sample the middle point
        border_center = (border_yx[len(border_yx) / (2)][0],
                         border_yx[len(border_yx) / (2)][1])
        patch_centers.append(border_center)

        if sample_rate > 1 or sample_rate == -1:
            if sample_rate > len(border_yx) or sample_rate == -1:
                samples = 1
            else:
                samples = len(border_yx) / sample_rate

            for i, s in enumerate(border_yx):

                if i % samples == 0:

                    sample_point = s

                    if distance.euclidean(patch_centers[-1],
                                          sample_point) < patch_size[0]:
                        # sample to close
                        # print 'sample to close', patch_centers[-1], sample_point
                        continue

                    patch_centers.append(sample_point)

        borders_w_center = np.array(borders.astype(np.uint8))

        for i, c in enumerate(patch_centers):

            borders_w_center[c[0], c[1]] = 10 * (i + 1)
            # print 'marking', c, borders_w_center.shape

        # if len(patch_centers) > 1:
        #   print 'PC', patch_centers

        for i, c in enumerate(patch_centers):

            # print 'pc',c

            #         for border_center in patch_centers:

            # check if border_center is too close to the 4 edges
            new_border_center = [c[0], c[1]]

            if new_border_center[0] < patch_size[0] / 2:
                # print 'oob1', new_border_center
                # return None
                continue
            if new_border_center[0] + patch_size[0] / 2 >= segmentation.shape[
                    0]:
                # print 'oob2', new_border_center
                # return None
                continue
            if new_border_center[1] < patch_size[1] / 2:
                # print 'oob3', new_border_center
                # return None
                continue
            if new_border_center[1] + patch_size[1] / 2 >= segmentation.shape[
                    1]:
                # print 'oob4', new_border_center
                # return None
                continue
            # print new_border_center, patch_size[0]/2, border_center[0] < patch_size[0]/2

            # continue

            bbox = [
                new_border_center[0] - patch_size[0] / 2,
                new_border_center[0] + patch_size[0] / 2,
                new_border_center[1] - patch_size[1] / 2,
                new_border_center[1] + patch_size[1] / 2
            ]

            ### workaround to not sample white border of probability map
            # if skip_boundaries:
            if bbox[0] <= 33:
                # return None
                # print 'ppb'
                continue
            if bbox[1] >= segmentation.shape[0] - 33:
                # return None
                # print 'ppb'
                continue
            if bbox[2] <= 33:
                # return None
                # print 'ppb'
                continue
            if bbox[3] >= segmentation.shape[1] - 33:
                # return None
                # print 'ppb'
                continue

            # threshold for label1
            array1 = Util.threshold(segmentation, l).astype(np.uint8)
            # threshold for label2
            array2 = Util.threshold(segmentation, n).astype(np.uint8)
            merged_array = array1 + array2

            # dilate for overlap
            dilated_array1 = np.array(array1)
            dilated_array2 = np.array(array2)
            for o in range(10):
                dilated_array1 = mh.dilate(dilated_array1.astype(np.uint64))
                dilated_array2 = mh.dilate(dilated_array2.astype(np.uint64))
            overlap = np.logical_and(dilated_array1, dilated_array2)
            overlap[merged_array == 0] = 0

            # overlap_labeled = skimage.measure.label(overlap)
            # overlap_value = overlap_labeled[37,37]
            # print overlap_value
            # overlap_thresholded = np.zeros(overlap.shape)
            # overlap_thresholded[overlap_labeled == overlap_value] = 1
            # overlap = overlap_thresholded

            output = {}
            output['id'] = str(uuid.uuid4())
            output['image'] = image[bbox[0]:bbox[1] + 1, bbox[2]:bbox[3] + 1]

            output['prob'] = prob[bbox[0]:bbox[1] + 1, bbox[2]:bbox[3] + 1]

            output['l'] = l
            output['n'] = n
            output['bbox'] = bbox
            output['border'] = border_yx
            output['border_center'] = new_border_center
            output['binary1'] = array1[bbox[0]:bbox[1] + 1,
                                       bbox[2]:bbox[3] + 1].astype(np.bool)
            output['binary2'] = array2[bbox[0]:bbox[1] + 1,
                                       bbox[2]:bbox[3] + 1].astype(np.bool)
            output['overlap'] = overlap[bbox[0]:bbox[1] + 1,
                                        bbox[2]:bbox[3] + 1].astype(np.bool)
            output['borders_labeled'] = borders_labeled[
                border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]]
            output['borders_w_center'] = borders_w_center[
                border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]]

            patches.append(output)

        return patches
Exemplo n.º 25
0
def process_image(im, d, test=False, remove_bordering=False):
    plt.figure(1, frameon=False)
    sigma = 75
    blurred = mh.gaussian_filter(im.astype(float), sigma)
    T_mean = blurred.mean()
    bin_image = im > T_mean

    maxima = mh.regmax(mh.stretch(blurred))
    maxima, _ = mh.label(maxima)

    dist = mh.distance(bin_image)

    dist = 255 - mh.stretch(dist)
    watershed = mh.cwatershed(dist, maxima)

    _, old_nr_objects = mh.labeled.relabel(watershed)

    sizes = mh.labeled.labeled_size(watershed)
    min_size = 100000
    filtered = mh.labeled.remove_regions_where(
        watershed * bin_image, sizes < min_size)

    _, nr_objects = mh.labeled.relabel(filtered)
    print('Removed', old_nr_objects - nr_objects, 'small regions')
    old_nr_objects = nr_objects

    if (remove_bordering):
        filtered = mh.labeled.remove_bordering(filtered)
    labeled, nr_objects = mh.labeled.relabel(filtered)

    print('Removed', old_nr_objects - nr_objects, 'bordering cells')

    print("Number of cells: {}".format(nr_objects))
    fin_weights = mh.labeled_sum(im.astype(np.uint32), labeled)
    fin_sizes = mh.labeled.labeled_size(labeled)
    fin_result = fin_weights / fin_sizes
    if (test):
        f, axarr = plt.subplots(2, 2)
        for i in range(2):
            for j in range(2):
                axarr[i][j].axis('off')
        axarr[0, 0].imshow(im)
        axarr[0, 0].set_title('Source')
        axarr[0, 1].imshow(labeled)
        axarr[0, 1].set_title('Labeled')
        axarr[1, 0].imshow(watershed)
        axarr[1, 0].set_title('Watershed')
        axarr[1, 1].imshow(blurred)
        axarr[1, 1].set_title('Blurred')
        for i in range(1, nr_objects + 1):
            print("Cell {} average luminescence is {}".format(
                i, fin_result[i]))
            bbox = mh.bbox((labeled == i))
            plt.text((bbox[2] + bbox[3]) / 2, (bbox[0] + bbox[1]
                                               ) / 2, str(i), fontsize=20, color='black')
        # plt.show()
        plt.savefig("test" + str(nr_objects) + ".svg",
                    format='svg', bbox_inches='tight', dpi=1200)
    else:
        for i in range(1, nr_objects + 1):
            bbox = mh.bbox((labeled == i))
            cell = (im * (labeled == i))[bbox[0]:bbox[1], bbox[2]:bbox[3]]
            hashed = hashlib.sha1(im).hexdigest()
            imsave(d + data_dir + hashed + '-' + str(i) +
                   '.png', imresize(cell, (img_rows, img_cols)))
Exemplo n.º 26
0
def test_bbox_empty():
    assert mahotas.bbox(np.zeros((), np.bool)).shape == (0, )
Exemplo n.º 27
0
  def split_new(image, binary):
    '''
    '''

    bbox = mh.bbox(binary)
    
    sub_image = np.array(image[bbox[0]:bbox[1], bbox[2]:bbox[3]])
    sub_binary = np.array(binary[bbox[0]:bbox[1], bbox[2]:bbox[3]])

    sub_binary_border = mh.labeled.borders(sub_binary, Bc=mh.disk(3))    
    
    sub_binary = mh.erode(sub_binary.astype(np.bool))
    for e in range(5):
      sub_binary = mh.erode(sub_binary)
    # sub_binary = mh.erode(sub_binary)    
    

    if sub_image.shape[0] < 2 or sub_image.shape[1] < 2:
      return np.zeros(binary.shape, dtype=np.bool), np.zeros(binary.shape, dtype=np.bool)

    #
    # smooth the image
    #
    sub_image = mh.gaussian_filter(sub_image, 3.5)

    grad_x = np.gradient(sub_image)[0]
    grad_y = np.gradient(sub_image)[1]
    grad = np.add(np.abs(grad_x), np.abs(grad_y))

    grad -= grad.min()
    grad /= grad.max()
    grad *= 255
    grad = grad.astype(np.uint8)
    
    coords = zip(*np.where(sub_binary==1))

    if len(coords) < 2:
      print 'STRAAAAANGE'
      return np.zeros(binary.shape, dtype=np.bool), np.zeros(binary.shape, dtype=np.bool)

    seed1 = random.choice(coords)
    seed2 = random.choice(coords)
    seeds = np.zeros(sub_binary.shape, dtype=np.uint64)
    seeds[seed1] = 1
    seeds[seed2] = 2

    for i in range(10):
      seeds = mh.dilate(seeds)

    ws = mh.cwatershed(grad, seeds)
    ws[sub_binary==0] = 0

#     ws_relabeled = skimage.measure.label(ws.astype(np.uint8))
#     ws_relabeled[sub_binary==0] = 0
#     max_label = ws_relabeled.max()
#     plt.figure()
#     imshow(ws)

    binary_mask = Util.threshold(ws, ws.max())
    border = mh.labeled.border(ws, ws.max(), ws.max()-1, Bc=mh.disk(2))
#     border[sub_binary_border == 1] = 0 # remove any "real" border pixels
    
#     plt.figure()
#     imshow(binary_mask)

#     plt.figure()
#     imshow(border)

    
    large_label = np.zeros(binary.shape, dtype=np.bool)
    large_border = np.zeros(binary.shape, dtype=np.bool)
    large_label[bbox[0]:bbox[1], bbox[2]:bbox[3]] = binary_mask
    large_border[bbox[0]:bbox[1], bbox[2]:bbox[3]] = border
    
    return large_label, large_border
Exemplo n.º 28
0
print len(small_labels)

results = []

for count, l in enumerate(small_labels[0:30]):

    labelA, labelB, merged, new_seg, n = create_merge_error(gold_normalized, l)

    if labelA == None:
        # didnt find a small pair of label neighbors
        continue

    print 'Introduced error between', l, n

    BBOX = mh.bbox(_metrics.Util.threshold(new_seg, l))

    patches = create_patches_from_label_id(image, prob, new_seg, l)

    print '-' * 80
    print 'Working on', l
    print 'Generated', len(patches), 'patches'
    print 'Testing them now...'

    smallest_prediction = np.inf
    detected = []

    for i, p in enumerate(patches):
        split_patches = create_merge_splits(p)

        for j, p in enumerate(split_patches):
Exemplo n.º 29
0
def test_bbox_empty():
    assert mahotas.bbox(np.zeros((), np.bool)).shape == (0,)
Exemplo n.º 30
0
def grab_patch(image,
               prob,
               segmentation,
               l,
               n,
               patch_size=(75, 75),
               skip_boundaries=False,
               sample_rate=1,
               debug=False):

    borders = mh.labeled.border(segmentation, l, n)

    #
    # treat interrupted borders separately
    #
    borders_labeled = skimage.measure.label(borders)

    # print borders_labeled.max()
    # for b in range(1,borders_labeled.max()+1):
    # borders = _metrics.Util.threshold(borders_labeled, b)

    border_bbox = mh.bbox(borders)

    patch_centers = []
    border_yx = indices = zip(*np.where(borders == 1))

    # always sample the middle point
    border_center = (border_yx[len(border_yx) / (2)][0],
                     border_yx[len(border_yx) / (2)][1])
    patch_centers.append(border_center)

    if sample_rate > 1 or sample_rate == -1:
        if sample_rate > len(border_yx) or sample_rate == -1:
            samples = 1
        else:
            samples = len(border_yx) / sample_rate

        for i, s in enumerate(border_yx):

            if i % samples == 0:

                sample_point = s
                # print border_center[0]-border_bbox[0], border_center[1]-border_bbox[2]
                patch_centers.append(sample_point)

        # sample_count = 0
        # while sample_rate>sample_count:

        #     sample_count += 1

        #     borders_labeled = skimage.measure.label(borders)

        #     border_centers = []

        #     for b in range(1,borders_labeled.max()+1):
        #         border = _metrics.Util.threshold(borders_labeled, b)

        #         border_yx = indices = zip(*np.where(border==1))

        #         # border_center = get_border_center(border, border_yx)
        #         #print border_yx
        #         border_center = (border_yx[len(border_yx)/2][0], border_yx[len(border_yx)/2][1])
        #         print border_center[0]-border_bbox[0], border_center[1]-border_bbox[2]
        #         border_centers.append(border_center)

        #     # split the borders into two
        #     for c in border_centers:

        #         if c[0]-1 > 0:
        #             borders[c[0]-1, c[1]] = 0
        #         if c[0]+1 < borders.shape[0]:
        #             borders[c[0]+1, c[1]] = 0
        #         borders[c[0], c[1]] = 0
        #         if c[1]-1 > 0:
        #             borders[c[0], c[1]-1] = 0
        #         if c[1]+1 < borders.shape[1]:
        #             borders[c[0], c[1]+1] = 0

        #     # recalculate the labeled borders
        #     borders_labeled = skimage.measure.label(borders)

    borders_w_center = np.array(borders.astype(np.uint8))

    for i, c in enumerate(patch_centers):

        borders_w_center[c[0], c[1]] = 10 * (i + 1)
        # print 'marking', c, borders_w_center.shape

    if debug:
        fig = plt.figure(figsize=(5, 5))
        fig.text(0, 1, '\n\n\n\n\nAll borders ' + str(l) + ',' +
                 str(n))  #+'\n\n'+str(np.round(_matrices[u], 2)))
        plt.imshow(borders_labeled[border_bbox[0]:border_bbox[1],
                                   border_bbox[2]:border_bbox[3]],
                   interpolation='nearest')
        fig = plt.figure(figsize=(5, 5))
        fig.text(0, 1, '\n\n\n\n\nWith center(s) ' + str(l) + ',' +
                 str(n))  #+'\n\n'+str(np.round(_matrices[u], 2)))
        plt.imshow(borders_w_center[border_bbox[0]:border_bbox[1],
                                    border_bbox[2]:border_bbox[3]],
                   interpolation='nearest')  #, cmap='ocean')

    patches = []
    #     # print 'bmax',borders_labeled.max()

    #     # check if we need multiple patches because of multiple borders
    #     for b in range(1,borders_labeled.max()+1):
    # #         print 'patch for border', b

    #         border = _metrics.Util.threshold(borders_labeled, b)

    #         border_yx = indices = zip(*np.where(border==1))

    #         # fault check if no border is found
    #         if len(border_yx) == 0:
    #             print 'no border', l, n, 'border', b
    #             continue

    #         #
    #         # calculate border center properly
    #         #
    #         border_center = get_border_center(border, border_yx)

    # #         # now we have the border center, this will be our first patch
    # #         patch_centers = []
    # #         patch_centers.append(border_center)

    # #         # we also want to have to more patches
    # #         border[border_center[0]-1, border_center[1]] = 0
    # #         border[border_center[0]+1, border_center[1]] = 0
    # #         border[border_center[0], border_center[1]] = 0
    # #         border[border_center[0], border_center[1]-1] = 0
    # #         border[border_center[0], border_center[1]+1] = 0
    # #         borders_labeled2 = skimage.measure.label(border)

    # #         other_center1 = _metrics.Util.threshold(borders_labeled2, 1)
    # #         other_border_yx1 = zip(*np.where(other_center1==1))
    # #         other_center1 = get_border_center(other_center1, other_border_yx1)
    # #         other_center2 = _metrics.Util.threshold(borders_labeled2, 2)
    # #         other_border_yx2 = zip(*np.where(other_center2==1))
    # #         other_center2 = get_border_center(other_center2, other_border_yx2)

    # #         patch_centers.append(other_center1)
    # #         patch_centers.append(other_center2)

    for i, c in enumerate(patch_centers):

        #         for border_center in patch_centers:

        # check if border_center is too close to the 4 edges
        new_border_center = [c[0], c[1]]

        if new_border_center[0] < patch_size[0] / 2:
            # print 'oob1', new_border_center
            # return None
            continue
        if new_border_center[0] + patch_size[0] / 2 >= segmentation.shape[0]:
            # print 'oob2', new_border_center
            # return None
            continue
        if new_border_center[1] < patch_size[1] / 2:
            # print 'oob3', new_border_center
            # return None
            continue
        if new_border_center[1] + patch_size[1] / 2 >= segmentation.shape[1]:
            # print 'oob4', new_border_center
            # return None
            continue
        # print new_border_center, patch_size[0]/2, border_center[0] < patch_size[0]/2

        # continue

        bbox = [
            new_border_center[0] - patch_size[0] / 2,
            new_border_center[0] + patch_size[0] / 2,
            new_border_center[1] - patch_size[1] / 2,
            new_border_center[1] + patch_size[1] / 2
        ]

        ### workaround to not sample white border of probability map
        if skip_boundaries:
            if bbox[0] <= 33:
                # return None
                # print 'ppb'
                continue
            if bbox[1] >= segmentation.shape[0] - 33:
                # return None
                # print 'ppb'
                continue
            if bbox[2] <= 33:
                # return None
                # print 'ppb'
                continue
            if bbox[3] >= segmentation.shape[1] - 33:
                # return None
                # print 'ppb'
                continue

        # threshold for label1
        array1 = _metrics.Util.threshold(segmentation, l).astype(np.uint8)
        # threshold for label2
        array2 = _metrics.Util.threshold(segmentation, n).astype(np.uint8)
        merged_array = array1 + array2

        # dilate for overlap
        dilated_array1 = np.array(array1)
        dilated_array2 = np.array(array2)
        for o in range(10):
            dilated_array1 = mh.dilate(dilated_array1.astype(np.uint64))
            dilated_array2 = mh.dilate(dilated_array2.astype(np.uint64))
        overlap = np.logical_and(dilated_array1, dilated_array2)
        overlap[merged_array == 0] = 0

        output = {}
        output['id'] = str(uuid.uuid4())
        output['image'] = image[bbox[0]:bbox[1] + 1, bbox[2]:bbox[3] + 1]

        output['prob'] = prob[bbox[0]:bbox[1] + 1, bbox[2]:bbox[3] + 1]

        output['l'] = l
        output['n'] = n
        output['bbox'] = bbox
        output['border'] = border_yx
        output['border_center'] = new_border_center
        output['binary1'] = array1[bbox[0]:bbox[1] + 1,
                                   bbox[2]:bbox[3] + 1].astype(np.bool)
        output['binary2'] = array2[bbox[0]:bbox[1] + 1,
                                   bbox[2]:bbox[3] + 1].astype(np.bool)
        output['overlap'] = overlap[bbox[0]:bbox[1] + 1,
                                    bbox[2]:bbox[3] + 1].astype(np.bool)
        output['borders_labeled'] = borders_labeled[
            border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]]
        output['borders_w_center'] = borders_w_center[
            border_bbox[0]:border_bbox[1], border_bbox[2]:border_bbox[3]]

        patches.append(output)

    return patches
Exemplo n.º 31
0
    def split_label(image, binary):

        bbox = mh.bbox(binary)

        sub_image = np.array(image[bbox[0]:bbox[1], bbox[2]:bbox[3]])
        sub_binary = np.array(binary[bbox[0]:bbox[1], bbox[2]:bbox[3]])

        sub_binary_border = mh.labeled.borders(sub_binary, Bc=mh.disk(3))

        sub_binary = mh.erode(sub_binary.astype(np.bool))
        for e in range(15):
            sub_binary = mh.erode(sub_binary)
        # # sub_binary = mh.erode(sub_binary)

        if sub_binary.shape[0] < 2 or sub_binary.shape[1] < 2:
            return np.zeros(binary.shape,
                            dtype=np.bool), np.zeros(binary.shape,
                                                     dtype=np.bool)

        #
        # smooth the image
        #
        sub_image = mh.gaussian_filter(sub_image, 3.5)

        grad_x = np.gradient(sub_image)[0]
        grad_y = np.gradient(sub_image)[1]
        grad = np.add(np.abs(grad_x), np.abs(grad_y))

        grad -= grad.min()
        grad /= grad.max()
        grad *= 255
        grad = grad.astype(np.uint8)

        coords = zip(*np.where(sub_binary == 1))

        if len(coords) < 2:
            # print 'STRAAAAANGE'
            return np.zeros(binary.shape,
                            dtype=np.bool), np.zeros(binary.shape,
                                                     dtype=np.bool)

        seed1 = random.choice(coords)
        seed2 = random.choice(coords)
        seeds = np.zeros(sub_binary.shape, dtype=np.uint64)
        seeds[seed1] = 1
        seeds[seed2] = 2

        for i in range(10):
            seeds = mh.dilate(seeds)

        ws = mh.cwatershed(grad, seeds)
        ws[sub_binary == 0] = 0

        #     ws_relabeled = skimage.measure.label(ws.astype(np.uint8))
        #     ws_relabeled[sub_binary==0] = 0
        #     max_label = ws_relabeled.max()
        #     plt.figure()
        #     imshow(ws)

        binary_mask = Util.threshold(ws, ws.max())
        border = mh.labeled.border(ws, ws.max(), ws.max() - 1, Bc=mh.disk(2))
        border[sub_binary_border == 1] = 0  # remove any "real" border pixels

        #     plt.figure()
        #     imshow(binary_mask)

        #     plt.figure()
        #     imshow(border)

        # at this point, there can be multiple borders and labels
        labeled_border = skimage.measure.label(border)
        labeled_binary_mask = skimage.measure.label(binary_mask)
        # .. and we are going to select only the largest
        largest_border_label = Util.get_largest_label(
            labeled_border.astype(np.uint16), True)
        largest_binary_mask_label = Util.get_largest_label(
            labeled_binary_mask.astype(np.uint16), True)
        # .. filter out everything else
        border[labeled_border != largest_border_label] = 0
        binary_mask[labeled_binary_mask != largest_binary_mask_label] = 0

        large_label = np.zeros(binary.shape, dtype=np.bool)
        large_border = np.zeros(binary.shape, dtype=np.bool)
        large_label[bbox[0]:bbox[1], bbox[2]:bbox[3]] = binary_mask
        large_border[bbox[0]:bbox[1], bbox[2]:bbox[3]] = border

        return large_label, large_border
Exemplo n.º 32
0
def attributes(img_path):
    r = mh.bbox(mh.imread(img_path))[1]/2
    return zernike(img_path,r).tolist() + haralick(img_path).flatten('K').tolist()
Exemplo n.º 33
0
  def get_merge_error_image(input_image, input_rhoana, label, border):

    binary = Util.threshold(input_rhoana, label)
    binary_dilated = mh.dilate(binary.astype(np.bool))
    for dilate in range(30):
      binary_dilated = mh.dilate(binary_dilated)


    binary_bbox = mh.bbox(binary_dilated)
    binary_border = mh.labeled.borders(binary)

    b = np.zeros((input_image.shape[0],input_image.shape[1],4), dtype=np.uint8)
    b[:,:,0] = input_image[:]
    b[:,:,1] = input_image[:]
    b[:,:,2] = input_image[:]
    b[:,:,3] = 255

    c = np.zeros((input_image.shape[0],input_image.shape[1],4), dtype=np.uint8)
    c[:,:,0] = input_image[:]
    c[:,:,1] = input_image[:]
    c[:,:,2] = input_image[:]
    c[:,:,3] = 255        
    c[binary_border == 1] = (0,255,0,255)

    e = np.zeros((input_image.shape[0],input_image.shape[1],4), dtype=np.uint8)
    e[:,:,0] = input_image[:]
    e[:,:,1] = input_image[:]
    e[:,:,2] = input_image[:]
    e[:,:,3] = 255        

    f = np.zeros((input_image.shape[0],input_image.shape[1],4), dtype=np.uint8)
    f[:,:,0] = input_image[:]
    f[:,:,1] = input_image[:]
    f[:,:,2] = input_image[:]
    f[:,:,3] = 255  
    f[binary == 1] = (0,255,0,255)

    g = np.zeros((input_image.shape[0],input_image.shape[1],4), dtype=np.uint8)
    g[:,:,0] = input_image[:]
    g[:,:,1] = input_image[:]
    g[:,:,2] = input_image[:]
    g[:,:,3] = 255  

    border[binary==0] = 0

    b[border == 1] = (255,0,0,255)
    b[binary_border == 1] = (0,255,0,255)

    cropped_image = Util.crop_by_bbox(input_image, binary_bbox)
    cropped_binary_border = Util.crop_by_bbox(c, binary_bbox)
    cropped_combined_border = Util.crop_by_bbox(b, binary_bbox)
    cropped_border_only = Util.crop_by_bbox(border, binary_bbox)

    corrected_binary = Legacy.correct_merge(input_rhoana, label, border)
    corrected_binary_original = np.array(corrected_binary)
    result = np.array(input_rhoana)
    corrected_binary += result.max()
    corrected_binary[corrected_binary_original == 0] = 0

    result[corrected_binary != 0] = 0
    result += corrected_binary.astype(np.uint64)
    cropped_result = Util.crop_by_bbox(corrected_binary, binary_bbox)

    g[corrected_binary_original==2] = (255,0,0,255)
    g[corrected_binary_original==1] = (0,255,0,255)
    cropped_fusion = Util.crop_by_bbox(g, binary_bbox)

    e[binary_bbox[0]:binary_bbox[1], binary_bbox[2]] = (255,255,0,255)
    e[binary_bbox[0]:binary_bbox[1], binary_bbox[3]] = (255,255,0,255)
    e[binary_bbox[0], binary_bbox[2]:binary_bbox[3]] = (255,255,0,255)
    e[binary_bbox[1], binary_bbox[2]:binary_bbox[3]] = (255,255,0,255)  

    sliceoverview = e

    cropped_binary = Util.crop_by_bbox(f, binary_bbox)

    return cropped_image, cropped_binary_border, cropped_combined_border, cropped_border_only, cropped_result, result, sliceoverview, cropped_binary, cropped_fusion