示例#1
0
def test_init_level_sets():

    image = np.zeros((6, 6))
    checkerboard_ls = morphological_chan_vese(image, 0, 'checkerboard')
    checkerboard_ref = np.array([[0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [1, 1, 1, 1, 1, 0]], dtype=np.int8)

    circle_ls = morphological_geodesic_active_contour(image, 0, 'circle')
    circle_ref = np.array([[0, 0, 0, 0, 0, 0],
                           [0, 0, 1, 1, 1, 0],
                           [0, 1, 1, 1, 1, 1],
                           [0, 1, 1, 1, 1, 1],
                           [0, 1, 1, 1, 1, 1],
                           [0, 0, 1, 1, 1, 0]], dtype=np.int8)

    ellipsoid_ls = morphological_chan_vese(np.zeros((7, 9)), 0, 'ellipsoid')
    ellipsoid_ref = np.array(
        [[0, 0, 1, 1, 1, 1, 1, 0, 0],
         [0, 1, 1, 1, 1, 1, 1, 1, 0],
         [1, 1, 1, 1, 1, 1, 1, 1, 1],
         [1, 1, 1, 1, 1, 1, 1, 1, 1],
         [1, 1, 1, 1, 1, 1, 1, 1, 1],
         [0, 1, 1, 1, 1, 1, 1, 1, 0],
         [0, 0, 1, 1, 1, 1, 1, 0, 0]],
        dtype=np.uint8
    )

    assert_array_equal(checkerboard_ls, checkerboard_ref)
    assert_array_equal(circle_ls, circle_ref)
    assert_array_equal(ellipsoid_ls, ellipsoid_ref)
示例#2
0
def manImage(image):
    iterCallback = plot_2d(image)
    morphsnakes.morphological_chan_vese(image,
                                        iterations=35,
                                        smoothing=30,
                                        lambda1=1,
                                        lambda2=1,
                                        iter_callback=iterCallback)
def test_morphsnakes_incorrect_image_shape():
    img = np.zeros((10, 10, 3))
    ls = np.zeros((10, 9))

    with pytest.raises(ValueError):
        morphological_chan_vese(img, iterations=1, init_level_set=ls)
    with pytest.raises(ValueError):
        morphological_geodesic_active_contour(img, iterations=1,
                                              init_level_set=ls)
示例#4
0
def img3dImage(image):
    initLevelSet = morphsnakes.circle_level_set(image.shape,
                                                center=(30, 50, 80),
                                                radius=25)
    morphsnakes.morphological_chan_vese(image,
                                        iterations=200,
                                        init_level_set=initLevelSet,
                                        smoothing=30,
                                        lambda1=1,
                                        lambda2=2,
                                        iter_callback=plot_3d(plot_each=20))
示例#5
0
def mapImage(image, imageRgp):
    initLevelSet = morphsnakes.circle_level_set(image.shape,
                                                center=(80, 170),
                                                radius=25)
    morphsnakes.morphological_chan_vese(image,
                                        iterations=250,
                                        init_level_set=initLevelSet,
                                        smoothing=30,
                                        lambda1=1,
                                        lambda2=1,
                                        iter_callback=plot_2d(imageRgp))
def test_morphsnakes_simple_shape_chan_vese():

    img = gaussian_blob()
    ls1 = circle_level_set(img.shape, (5, 5), 3)
    ls2 = circle_level_set(img.shape, (5, 5), 6)

    acwe_ls1 = morphological_chan_vese(img, iterations=10, init_level_set=ls1)
    acwe_ls2 = morphological_chan_vese(img, iterations=10, init_level_set=ls2)

    assert_array_equal(acwe_ls1, acwe_ls2)

    assert acwe_ls1.dtype == acwe_ls2.dtype == np.int8
示例#7
0
 def process_frames(self, data):
     # run MorphSnakes here:
     if (np.sum(data[1]) > 0):
         segment_result = morphological_chan_vese(data[0], iterations=self.iterations, lambda1=self.lambda1, lambda2=self.lambda2, init_level_set=data[1])
     else:
         segment_result = np.uint8(np.zeros(np.shape(data[0])))
     return [segment_result]
示例#8
0
def example_confocal3d():
    logging.info('Running: example_confocal3d (MorphACWE)...')

    # Load the image.
    img = np.load(PATH_ARRAY_CONFOCAL)

    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (30, 50, 80), 25)

    # Callback for visual plotting
    callback = visual_callback_3d(plot_each=20)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img, iterations=150,
                               init_level_set=init_ls,
                               smoothing=1, lambda1=1, lambda2=2,
                               iter_callback=callback)
示例#9
0
def example_confocal3d():
    logging.info('Running: example_confocal3d (MorphACWE)...')
    
    # Load the image.
    img = np.load(PATH_ARRAY_CONFOCAL)
    
    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (30, 50, 80), 25)

    # Callback for visual plotting
    callback = visual_callback_3d(plot_each=20)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img, iterations=150,
                               init_level_set=init_ls,
                               smoothing=1, lambda1=1, lambda2=2,
                               iter_callback=callback)
示例#10
0
def example_camera():
    """
    Example with `morphological_chan_vese` with using the default
    initialization of the level-set.
    """

    logging.info('Running: example_camera (MorphACWE)...')

    # Load the image.
    img = imread(PATH_IMG_CAMERA)/255.0

    # Callback for visual plotting
    callback = visual_callback_2d(img)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img, 35,
                               smoothing=3, lambda1=1, lambda2=1,
                               iter_callback=callback)
示例#11
0
def example_camera():
    """
    Example with `morphological_chan_vese` with using the default
    initialization of the level-set.
    """
    
    logging.info('Running: example_camera (MorphACWE)...')

    # Load the image.
    img = imread(PATH_IMG_CAMERA)/255.0

    # Callback for visual plotting
    callback = visual_callback_2d(img)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img, 35,
                               smoothing=3, lambda1=1, lambda2=1,
                               iter_callback=callback)
示例#12
0
def example_lakes():
    logging.info('Running: example_lakes (MorphACWE)...')

    # Load the image.
    imgcolor = imread(PATH_IMG_LAKES)/255.0
    img = rgb2gray(imgcolor)

    # MorphACWE does not need g(I)

    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (80, 170), 25)

    # Callback for visual plotting
    callback = visual_callback_2d(imgcolor)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img, iterations=200,
                               init_level_set=init_ls,
                               smoothing=3, lambda1=1, lambda2=1,
                               iter_callback=callback)
示例#13
0
def sharpShape(image, calback):
  
    # Callback for visual plotting
    callback = visual_callback_2d(image)

    # Morphological Chan-Vese 
    ima=ms.morphological_chan_vese(image, 35,
                               smoothing=3, lambda1=1, lambda2=1,
                               iter_callback=callback)

    return ima
示例#14
0
def example_lakes():
    logging.info('Running: example_lakes (MorphACWE)...')
    
    # Load the image.
    imgcolor = imread(PATH_IMG_LAKES)/255.0
    img = rgb2gray(imgcolor)
    
    # MorphACWE does not need g(I)
    
    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (80, 170), 25)
    
    # Callback for visual plotting
    callback = visual_callback_2d(imgcolor)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img, iterations=200,
                               init_level_set=init_ls,
                               smoothing=3, lambda1=1, lambda2=1,
                               iter_callback=callback)
示例#15
0
def acwe3d(img, coord, iterations, smoothing):
    print('Running: snake_3d (MorphACWE)...')

    init_ls = ms.circle_level_set(img.shape, (coord[2], coord[1], coord[0]), 5)

    ls = ms.morphological_chan_vese(img,
                                    iterations=iterations,
                                    init_level_set=init_ls,
                                    smoothing=smoothing,
                                    lambda1=2,
                                    lambda2=1)
    return ls
示例#16
0
def acwe2d(img, coord, iterations, smoothing):
    print('Running: snake_2d (MorphACWE)...')

    range_img = img[:, :, coord[0]]
    range_init_ls = ms.circle_level_set(range_img.shape, (coord[2], coord[1]),
                                        5)
    range_ls = ms.morphological_chan_vese(range_img,
                                          iterations=iterations,
                                          init_level_set=range_init_ls,
                                          smoothing=smoothing,
                                          lambda1=2,
                                          lambda2=1)
    # save_img(range_img, range_ls, "acwe_2d_y_slice")

    slices = []
    i = 0
    for row in range_ls:
        for x in row:
            if x == 1:
                slices.append([i, middle_of_line(row)])
                break
        i += 1

    middle = int((slices[-1][0] + slices[0][0]) / 2)
    result = np.zeros(img.shape, dtype=np.uint8)

    for line in slices:
        image_part = img[line[0]]
        init_ls = ms.circle_level_set(image_part.shape, (line[1], coord[0]), 5)
        ls = ms.morphological_chan_vese(image_part,
                                        iterations=iterations,
                                        init_level_set=init_ls,
                                        smoothing=smoothing,
                                        lambda1=2,
                                        lambda2=1)
        result[line[0]] = ls
        # if i == middle:
        #     save_img(image_part, ls, "acwe_2d_slice")

    return result
示例#17
0
    def example_lakes(self):
        logging.info('Running: example_lakes (MorphACWE)...')

        # Load the image.
        img = self.maskPred

        # MorphACWE does not need g(I)

        # Initialization of the level-set.
        init_ls = ms.circle_level_set(img.shape,
                                      (self.center[0], self.center[1]),
                                      (self.dia) / 2)

        # Callback for visual plotting
        callback = self.visual_callback_2d(img)

        # Morphological Chan-Vese (or ACWE)
        ms.morphological_chan_vese(img,
                                   iterations=self.iterations,
                                   init_level_set=init_ls,
                                   smoothing=3,
                                   lambda1=1,
                                   lambda2=1,
                                   iter_callback=callback)
示例#18
0
def example_tumor2():
    logging.info('Running: example_tumor2 (MorphACWE)...')

    # Load the image.
    imgcolor = imread('images/project_2乳腺肿瘤视频.avi_000000.000.png') / 255.0
    #imgcolor = imread('images/project_2乳腺肿瘤视频.avi_000004.850.png')/255.0
    img = rgb2gray(imgcolor)

    # MorphACWE does not need g(I)

    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (274, 501), 20)

    # Callback for visual plotting
    callback = visual_callback_2d(imgcolor)

    # Morphological Chan-Vese (or ACWE)
    ms.morphological_chan_vese(img,
                               iterations=200,
                               init_level_set=init_ls,
                               smoothing=1,
                               lambda1=1,
                               lambda2=1,
                               iter_callback=callback)
示例#19
0
def sharpShape(image, calback):
    """
     `morphological_chan_vese` with using the default
    initialization of the level-set.
    """

    # Callback for visual plotting
    callback = visual_callback_2d(image)

    # Morphological Chan-Vese
    ima = ms.morphological_chan_vese(image,
                                     35,
                                     smoothing=3,
                                     lambda1=1,
                                     lambda2=1,
                                     iter_callback=callback)
    return ima
示例#20
0
def test_init_level_sets():

    image = np.zeros((6, 6))
    checkerboard_ls = morphological_chan_vese(image, 0, 'checkerboard')
    checkerboard_ref = np.array([[0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [0, 0, 0, 0, 0, 1],
                                 [1, 1, 1, 1, 1, 0]], dtype=np.int8)

    circle_ls = morphological_geodesic_active_contour(image, 0, 'circle')
    circle_ref = np.array([[0, 0, 0, 0, 0, 0],
                           [0, 0, 1, 1, 1, 0],
                           [0, 1, 1, 1, 1, 1],
                           [0, 1, 1, 1, 1, 1],
                           [0, 1, 1, 1, 1, 1],
                           [0, 0, 1, 1, 1, 0]], dtype=np.int8)

    assert_array_equal(checkerboard_ls, checkerboard_ref)
    assert_array_equal(circle_ls, circle_ref)
def test_morphsnakes_3d():

    image = np.zeros((7, 7, 7))

    evolution = []

    def callback(x):
        evolution.append(x.sum())

    ls = morphological_chan_vese(image, 5, 'circle',
                                 iter_callback=callback)

    # Check that the initial circle level set is correct
    assert evolution[0] == 81

    # Check that the final level set is correct
    assert ls.sum() == 0

    # Check that the contour is shrinking at every iteration
    for v1, v2 in zip(evolution[:-1], evolution[1:]):
        assert v1 >= v2
示例#22
0
def segment(image,
            lambda2,
            iterations,
            smoothing=1,
            threshold=None,
            init=None):
    """
    """

    if threshold is not None:
        image[image < threshold] = 0
    if init is None:
        init = np.zeros_like(image, dtype=np.uint8)
        bounds = np.ceil(np.array(image.shape) * 0.1).astype(int)
        init[tuple(slice(b, -b) for b in bounds)] = 1
    return morphsnakes.morphological_chan_vese(
        image,
        iterations,
        init_level_set=init,
        smoothing=smoothing,
        lambda2=lambda2,
    ).astype(np.uint8)
def test_morphsnakes_black():

    img = np.zeros((11, 11))
    ls = circle_level_set(img.shape, (5, 5), 3)

    ref_zeros = np.zeros(img.shape, dtype=np.int8)
    ref_ones = np.ones(img.shape, dtype=np.int8)

    acwe_ls = morphological_chan_vese(img, iterations=6, init_level_set=ls)
    assert_array_equal(acwe_ls, ref_zeros)

    gac_ls = morphological_geodesic_active_contour(img, iterations=6,
                                                   init_level_set=ls)
    assert_array_equal(gac_ls, ref_zeros)

    gac_ls2 = morphological_geodesic_active_contour(img, iterations=6,
                                                    init_level_set=ls,
                                                    balloon=1, threshold=-1,
                                                    smoothing=0)
    assert_array_equal(gac_ls2, ref_ones)

    assert acwe_ls.dtype == gac_ls.dtype == gac_ls2.dtype == np.int8
示例#24
0
def check_image(path):
    image = cv.imread(path)
    image_channel = get_image_channel(image, cfg.NUCLEUS_BG_CHANNEL)

    # =============== get nucleus =============
    image_init_nucleus = image_channel.copy()
    thresh = get_thresh_by_proportion(image_init_nucleus)
    image_init_nucleus[image_init_nucleus > thresh] = 0
    cv.imshow("init_nucleus", image_init_nucleus)
    cv.imwrite("handled_data/init_nucleus.jpg", image_init_nucleus)

    # ============== set as level-set =============
    ls_init_nucleus = image_init_nucleus.copy()
    ls_init_nucleus[ls_init_nucleus > 0] = 1

    # ============== find (cell) boundary with snake ============
    ls_init_cell = snakes.morphological_chan_vese(
        image_channel,
        iterations=cfg.SUB_ITERATION,
        init_level_set=ls_init_nucleus,
        smoothing=cfg.SMOOTH,
        lambda1=cfg.LAMBDA_1,
        lambda2=cfg.LAMBDA_2)
    # ls_init_cell = snakes.morphological_geodesic_active_contour(image_channel, iterations=cfg.SUB_ITERATION,smoothing=0,
    #                                               init_level_set=ls_init_nucleus, iter_callback=visual_callback_2d(image_channel))
    image_init_cell = image_channel.copy()
    image_init_cell[ls_init_cell == 0] = 0
    # cv.imshow("init_cell", image_init_cell)
    cv.imwrite("handled_data/init_cell.jpg", image_init_cell)

    # ===================== iterations =========================
    ls_cell = ls_init_cell
    ls_nucleus = ls_init_nucleus
    image_nucleus = image_channel.copy()
    image_cell = image_channel.copy()
    for i in range(cfg.ITERATION):
        # ========== get more precise nucleus ===================
        mask = ls_cell.copy()
        ls_nucleus = snakes.morphological_chan_vese_mask(
            image_channel,
            mask=mask,
            iterations=cfg.SUB_ITERATION,
            smoothing=cfg.SMOOTH,
            init_level_set=ls_nucleus)
        # ls_nucleus = snakes.morphological_geodesic_active_contour(image_channel, iterations=cfg.SUB_ITERATION,
        #                                                     init_level_set=ls_nucleus)
        image_nucleus[ls_nucleus == 0] = 0
        # cv.imshow("image_nucleus_{}".format(i), image_nucleus)
        cv.imwrite("handled_data/image_nucleus_{}.jpg".format(i),
                   image_nucleus)

        # =============== get more precise cell ==================
        mask = 1 - ls_nucleus
        ls_cell = snakes.morphological_chan_vese_mask(
            image_channel,
            mask=mask,
            iterations=cfg.SUB_ITERATION,
            smoothing=cfg.SMOOTH,
            init_level_set=ls_cell)
        # ls_cell = snakes.morphological_geodesic_active_contour(image_channel,  iterations=cfg.SUB_ITERATION,
        #                                               init_level_set=ls_cell)
        ls_cell[ls_nucleus > 0] = 1
        image_cell[ls_cell == 0] = 0
        # cv.imshow("image_cell_{}".format(i), image_cell)
        cv.imwrite("handled_data/image_cell_{}.jpg".format(i), image_cell)

    # =================== ready for find contours ==========================
    image_cell = dilate_erode_image(image_cell, 0)
    cv.imshow("erode_dilate", image_cell)

    # =================== find contours and divide ===========================
    image_cell = divide_with_hull(image_cell)
    cv.imshow("divided", image_cell)
    # =================== calculate result ===============================
    image_cell = sift_cell(image_cell, image_nucleus)
    cv.imshow("result", image_cell)
    cv.imwrite("handled_data/result.jpg", image_cell)

    level = image_cell.copy()
    level[level > 0] = 1
    _, contours, _ = cv.findContours(level, cv.RETR_EXTERNAL,
                                     cv.CHAIN_APPROX_NONE)
    image = cv.drawContours(image, contours, -1, (255, 0, 0), 1)
    print("cell area:{}".format(level.sum()))
    level[ls_nucleus == 0] = 0
    _, contours, _ = cv.findContours(level, cv.RETR_EXTERNAL,
                                     cv.CHAIN_APPROX_NONE)
    image = cv.drawContours(image, contours, -1, (255, 255, 255), 1)
    cv.imshow("final_result", image)
    cv.imwrite("handled_data/final_result.jpg", image)
    print("nucleus area:{}".format(level.sum()))
示例#25
0
def acwe2d_prev(img, coord, iterations, smoothing):
    print('Running: snake_2d_prev (MorphACWE)...')

    range_img = img[:, :, coord[0]]
    range_init_ls = ms.circle_level_set(range_img.shape, (coord[2], coord[1]),
                                        5)
    range_ls = ms.morphological_chan_vese(range_img,
                                          iterations=iterations,
                                          init_level_set=range_init_ls,
                                          smoothing=smoothing,
                                          lambda1=2,
                                          lambda2=1)
    # save_img(range_img, range_ls, "acwe_2d_prev_y_slice")

    slices = []
    i = 0
    for row in range_ls:
        for x in row:
            if x == 1:
                slices.append([i, middle_of_line(row)])
                break
        i += 1

    middle = int((slices[-1][0] + slices[0][0]) / 2)
    middle_index = int(len(slices) / 2)

    middle_img = img[slices[middle_index][0]]
    init_ls = ms.circle_level_set(middle_img.shape,
                                  (slices[middle_index][1], coord[0]), 5)
    middle_ls = ms.morphological_chan_vese(middle_img,
                                           iterations=iterations,
                                           init_level_set=init_ls,
                                           smoothing=smoothing,
                                           lambda1=2,
                                           lambda2=1)

    result = np.zeros(img.shape, dtype=np.uint8)
    result[slices[middle_index][0]] = middle_ls
    # save_img(middle_img, middle_ls, "acwe_2d_prev_slice")

    prev_ls = middle_ls
    for i in range(middle_index + 1, len(slices)):
        line = slices[i]
        image_part = img[line[0]]
        ls = ms.morphological_chan_vese(image_part,
                                        iterations=(iterations // 4),
                                        init_level_set=prev_ls,
                                        smoothing=smoothing,
                                        lambda1=2,
                                        lambda2=1)
        prev_ls = ls
        result[line[0]] = ls

    prev_ls = middle_ls
    for i in range(middle_index - 1, 0, -1):
        line = slices[i]
        image_part = img[line[0]]
        ls = ms.morphological_chan_vese(image_part,
                                        iterations=(iterations // 4),
                                        init_level_set=prev_ls,
                                        smoothing=smoothing,
                                        lambda1=2,
                                        lambda2=1)
        prev_ls = ls
        result[line[0]] = ls

    return result
示例#26
0
    if imgcolor.ndim != 2:
        img = rgb2gray(imgcolor)
    else:
        img = imgcolor

    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape,
                                  radius=min(img.shape) * circle_ratio)
    # Callback for visual plotting
    callback = visual_callback_2d(imgcolor)

    # Morphological Chan-Vese
    ms.morphological_chan_vese(img,
                               iterations=iterations,
                               init_level_set=init_ls,
                               smoothing=smoothing,
                               lambda1=lambda1,
                               lambda2=lambda2,
                               iter_callback=callback)

    # ms.morphological_chan_vese(img, iterations=iterations,
    #                            smoothing=3, lambda1=lambda1, lambda2=lambda2,
    #                            iter_callback=callback)

    # Try kernel_size(in smooth) and interval(in curvature calculation)
    while True:
        # Contour Smooth
        try:
            if input("Command(Press enter to continue, q for quit): ").lower(
            ) == 'q':
                break
def example_la():
    logging.info('Running: example_lakes (MorphACWE)...')
    global img
    global num_districts
    # mouse callback function
    points = find_centers(PATH_IMG_LA)

    # def note_point(event, x, y, flags, param):
    #     if event == cv2.EVENT_LBUTTONDBLCLK:
    #         points.append((y, x))

    # # Create a black image, a window and bind the function to window
    # cv2.namedWindow('image')
    # cv2.setMouseCallback('image', note_point)

    # while(1):
    #     cv2.imshow('image', imgcolor)
    #     k = cv2.waitKey(20) & 0xFF
    #     if k == ord('p'):
    #         print(points)
    #     elif k == ord('q'):
    #         break
    # cv2.destroyAllWindows()

    num_districts = len(points)

    # MorphACWE does not need g(I)
    all_scores = []
    # Initialization of the level-set.
    for point in points:
        init_ls = ms.circle_level_set(img.shape, point, 40)

        # Callback for visual plotting
        callback = visual_callback_2d(imgcolor)

        # Morphological Chan-Vese (or ACWE)
        r, score = ms.morphological_chan_vese(img,
                                              iterations=100,
                                              init_level_set=init_ls,
                                              smoothing=3,
                                              lambda1=1,
                                              lambda2=1,
                                              iter_callback=callback)

        all_scores.append(score)
        bounder = find_boundaries(r, mode='thick').astype(np.uint8)
        imgcolor[bounder != 0] = (255, 0, 0, 1)

        r = 1 - r
        imgmod = cv2.bitwise_and(imgcolor, imgcolor, mask=r)
        img = rgb2gray(imgmod)

    print('All Scores:', all_scores)
    total_score = 0
    for score in all_scores:
        if score > 1:
            total_score += (1 - (score - 1))
        else:
            total_score += score

    print('Total Score:', total_score)