def test_morphsnakes_simple_shape_geodesic_active_contour():

    img = np.float_(circle_level_set((11, 11), (5, 5), 3.5))
    gimg = inverse_gaussian_gradient(img, alpha=10.0, sigma=1.0)
    ls = circle_level_set(img.shape, (5, 5), 6)

    ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                    [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
                    [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
                    [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
                    [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
                    [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
                    [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
                   dtype=np.int8)

    gac_ls = morphological_geodesic_active_contour(gimg, iterations=10,
                                                   init_level_set=ls,
                                                   balloon=-1)

    assert_array_equal(gac_ls, ref)

    assert gac_ls.dtype == np.int8
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
示例#3
0
 def process_frames(self, data):
     # get the index of a current frame
     index_current = self.get_plugin_in_datasets()[0].get_current_frame_idx(
     )
     [dimX, dimY] = np.shape(data[0])
     mask = np.uint8(np.zeros(np.shape(data[0])))
     if ((index_current >= self.coordZ0) & (index_current <= self.coordZ1)):
         if ((self.coordX0 == 0) & (self.coordY0 == 0) & (self.coordX1 == 0)
                 & (self.coordY1 == 0)):
             # create a full region mask (except the boundaries)
             bound_width = 2  # outer boundary width
             mask[bound_width:dimX - bound_width,
                  bound_width:dimY - bound_width] = 1
         else:
             self.d_step = (index_current - self.coordZ0) * self.d_dist
             t = self.d_step / self.distance
             if (self.coordX0 == self.coordX1):
                 x_t = np.int(self.coordX0)
             else:
                 x_t1 = np.round((1.0 - t) * self.coordX0 +
                                 t * self.coordX1)
                 x_t = np.int(x_t1[0])
             if (self.coordY0 == self.coordY1):
                 y_t = np.int(self.coordY0)
             else:
                 y_t1 = np.round((1.0 - t) * self.coordY0 +
                                 t * self.coordY1)
                 y_t = np.int(y_t1[0])
             mask = np.uint8(
                 circle_level_set(np.shape(data[0]), (y_t, x_t),
                                  self.circle_radius))
     return [mask]
def example_nodule(pt):
    #     logging.info('Running: example_nodule (MorphGAC)...')

    # Load the image.
    # 用quan完之後的圖用會很糟
    img = imread(OUTPUT_CUTHIST) / 255.0

    # img2為背景圖
    img2 = imread(OUTPUT_BLACK) / 255.0

    # g(I)
    gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=5.48)

    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, pt, 15)

    # Callback for visual plotting
    callback = visual_callback_2d(img2)

    # MorphGAC.
    ms.morphological_geodesic_active_contour(gimg,
                                             iterations=45,
                                             init_level_set=init_ls,
                                             smoothing=1,
                                             threshold=0.29,
                                             balloon=1,
                                             iter_callback=callback)
示例#5
0
def find_contour(img):
    img = img/255
    gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=5.48)
    init_ls = ms.circle_level_set(img.shape, (100, 126), 20)
    callback = visual_callback_2d(img)
    ms.morphological_geodesic_active_contour(gimg, iterations=45,
                                             init_level_set=init_ls,
                                             smoothing=1, threshold=0.31,
                                             balloon=1, iter_callback=callback)
示例#6
0
def gac2d(img, coord, iterations, smoothing, balloon, threshold):
    print('Running: snake_2d (MorphGAC)...')

    range_img = img[:, :, coord[0]]
    range_init_ls = ms.circle_level_set(range_img.shape, (coord[2], coord[1]),
                                        5)
    range_gimage = inverse_gaussian_gradient(range_img)
    range_ls = ms.morphological_geodesic_active_contour(
        range_gimage,
        iterations=iterations,
        init_level_set=range_init_ls,
        smoothing=smoothing,
        balloon=balloon,
        threshold=threshold)
    # save_img(range_img, range_ls, "gac_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)

        gimage = inverse_gaussian_gradient(image_part)
        ls = ms.morphological_geodesic_active_contour(gimage,
                                                      iterations=iterations,
                                                      init_level_set=init_ls,
                                                      smoothing=smoothing,
                                                      balloon=balloon,
                                                      threshold=threshold)
        result[line[0]] = ls
        # if i == middle:
        #     save_img(image_part, ls, "gac_2d_slice")

    return result
示例#7
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))
示例#8
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))
示例#9
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
示例#10
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
示例#11
0
def gac3d(img, coord, iterations, smoothing, balloon, threshold):
    print('Running: snake_3d (MorphGAC)...')

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

    gimage = inverse_gaussian_gradient(img)
    ls = ms.morphological_geodesic_active_contour(gimage,
                                                  iterations=iterations,
                                                  init_level_set=init_ls,
                                                  smoothing=smoothing,
                                                  balloon=balloon,
                                                  threshold=threshold)
    return ls
示例#12
0
def seastarImage(image, imageRgp):
    inverseGaussianGradient = morphsnakes.inverse_gaussian_gradient(image,
                                                                    alpha=1000,
                                                                    sigma=2)
    initLevelSet = morphsnakes.circle_level_set(image.shape,
                                                center=(163, 137),
                                                radius=135)
    morphsnakes.morphological_geodesic_active_contour(
        inverseGaussianGradient,
        iterations=150,
        init_level_set=initLevelSet,
        smoothing=20,
        threshold=0.3,
        balloon=-1,
        iter_callback=plot_2d(imageRgp))
示例#13
0
def seaImg(image):
    inverseGaussianGradient = morphsnakes.inverse_gaussian_gradient(image,
                                                                    alpha=1000,
                                                                    sigma=5.48)
    initLevelSet = morphsnakes.circle_level_set(image.shape,
                                                center=(100, 126),
                                                radius=30)
    morphsnakes.morphological_geodesic_active_contour(
        inverseGaussianGradient,
        iterations=65,
        init_level_set=initLevelSet,
        smoothing=20,
        threshold=0.31,
        balloon=1,
        iter_callback=plot_2d(image))
示例#14
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)
示例#15
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)
示例#16
0
def example_nodule():
    logging.info('Running: example_nodule (MorphGAC)...')
    
    # Load the image.
    img = imread(PATH_IMG_NODULE)[..., 0] / 255.0
    
    # g(I)
    gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=5.48)
    
    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (100, 126), 20)
    
    # Callback for visual plotting
    callback = visual_callback_2d(img)
    
    # MorphGAC. 
    ms.morphological_geodesic_active_contour(gimg, iterations=45, 
                                             init_level_set=init_ls,
                                             smoothing=1, threshold=0.31,
                                             balloon=1, iter_callback=callback)
示例#17
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)
示例#18
0
def example_nodule():
    logging.info('Running: example_nodule (MorphGAC)...')

    # Load the image.
    img = imread(PATH_IMG_NODULE)[..., 0] / 255.0

    # g(I)
    gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=5.48)

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

    # Callback for visual plotting
    callback = visual_callback_2d(img)

    # MorphGAC.
    ms.morphological_geodesic_active_contour(gimg, iterations=45,
                                             init_level_set=init_ls,
                                             smoothing=1, threshold=0.31,
                                             balloon=1, iter_callback=callback)
示例#19
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)
示例#20
0
def example_starfish():
    logging.info('Running: example_starfish (MorphGAC)...')
    
    # Load the image.
    imgcolor = imread(PATH_IMG_STARFISH) / 255.0
    img = rgb2gray(imgcolor)
    
    # g(I)
    gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=2)
    
    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (163, 137), 135)
    
    # Callback for visual plotting
    callback = visual_callback_2d(imgcolor)
    
    # MorphGAC. 
    ms.morphological_geodesic_active_contour(gimg, iterations=100, 
                                             init_level_set=init_ls,
                                             smoothing=2, threshold=0.3,
                                             balloon=-1, iter_callback=callback)
示例#21
0
def example_starfish():
    logging.info('Running: example_starfish (MorphGAC)...')

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

    # g(I)
    gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=2)

    # Initialization of the level-set.
    init_ls = ms.circle_level_set(img.shape, (163, 137), 135)

    # Callback for visual plotting
    callback = visual_callback_2d(imgcolor)

    # MorphGAC.
    ms.morphological_geodesic_active_contour(gimg, iterations=100,
                                             init_level_set=init_ls,
                                             smoothing=2, threshold=0.3,
                                             balloon=-1, iter_callback=callback)
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
def morph_snakes_segmentation(snapshot,
                              start_point: Tuple[int, int],
                              start_radius: int,
                              num_iterations: int,
                              z=None):
    """
    Now only works with 2D image, thus always set z for now
    # TODO: do for 3D snapshot
    """
    assert snapshot.ndim == 3

    img = snapshot[z]
    # get the gaussian gradient for higher contrast
    gimg = ms.inverse_gaussian_gradient(img, alpha=5.0, sigma=5.0)

    # level_set is the starting
    level_set = ms.circle_level_set(img.shape, start_point, start_radius)
    mask = ms.morphological_geodesic_active_contour(gimg.astype('float64'),
                                                    num_iterations, level_set)
    # repeat the 2D mask so that it is the same size as the image
    mask = np.repeat(mask[np.newaxis, :, :], snapshot.shape[0], axis=0)

    return mask
示例#24
0
def example_tumor():
    logging.info('Running: example_tumor (MorphGAC)...')

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

    # g(I)
    gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=10)

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

    # Callback for visual plotting
    callback = visual_callback_2d(img)

    # MorphGAC.
    ms.morphological_geodesic_active_contour(gimg,
                                             iterations=160,
                                             init_level_set=init_ls,
                                             smoothing=1,
                                             threshold=0.45,
                                             balloon=1,
                                             iter_callback=callback)
示例#25
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)
示例#26
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)
示例#27
0
cap = cv2.VideoCapture('project_2乳腺肿瘤视频.avi')
windowName1 = 'original'
windowName2 = 'processed'

startTime = time.time()
#np.hstack((frameLeft, frameRight))#在水平方向上拼接两帧图片
while (cap.isOpened()):
    ret, frame = cap.read()
    if frame is None:
        break
    frame = frame[132:600, 191:794]
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    #开始处理
    gimg = ms.inverse_gaussian_gradient(frame, alpha=1000, sigma=5.48)
    init_ls = ms.circle_level_set(frame.shape, (100, 126), 20)
    callback = visual_callback_2d(frame)
    ms.morphological_geodesic_active_contour(gimg,
                                             iterations=45,
                                             init_level_set=init_ls,
                                             smoothing=1,
                                             threshold=0.31,
                                             balloon=1,
                                             iter_callback=callback)

    ##    scharrx=cv2.Scharr(frame,cv2.CV_64F,dx=1,dy=0)
    ##    scharrx=cv2.convertScaleAbs(scharrx)
    ##    scharry=cv2.Scharr(frame,cv2.CV_64F,dx=0,dy=1)
    ##    scharry=cv2.convertScaleAbs(scharry)
    ##    processedFrame=cv2.addWeighted(scharrx,0.5,scharry,0.5,0)
示例#28
0
    return callback


logging.info('Running: example_starfish (MorphGAC)...')

PATH_IMG_STARFISH = 'img2.png'

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

# g(I)
gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=5.48)

# setting starting position

# Initialization of the level-set.
init_ls = ms.circle_level_set(img.shape, (540, 360),
                              20)  #img1 = (500, 156), 20)

# Callback for visual plotting
callback = visual_callback_2d(img)

# MorphGAC.
ms.morphological_geodesic_active_contour(gimg,
                                         iterations=200,
                                         init_level_set=init_ls,
                                         smoothing=1,
                                         threshold=0.31,
                                         balloon=1,
                                         iter_callback=callback)
示例#29
0
##########


# b. Use morphsnakes to segment the objects in the image. 
#    Create the mask as shown in 'wks3_1_b.jpg'.

kernel = np.ones((5,5),np.uint8)
noiserem = cv2.morphologyEx(np.uint8(imgcolor),
                            cv2.MORPH_OPEN,
                            kernel)
cv2plt(noiserem)

gray = cv2.cvtColor(noiserem,cv2.COLOR_BGR2GRAY)
cv2plt(gray)
gray.shape

gray01 = gray/255.0
invg = ms.inverse_gaussian_gradient(gray01, alpha=700, sigma=3)
ls0 = ms.circle_level_set(gray01.shape, (200, 250), 250)

callback = ms.visual2d(cv2.cvtColor(imgcolor,cv2.COLOR_BGR2RGB))
lsf = ms.morphological_geodesic_active_contour(invg,
                                               iterations=500,
                                               init_level_set=ls0,
                                               smoothing=1,
                                               threshold=0.5,
                                               balloon=-1,
                                               iter_callback=callback)

cv2plt(lsf*255)
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)
示例#31
0
def mask_gen(mask, coordX, coordY, coordZ, mask_radius, dimX, dimY,
             index_current):
    steps1 = coordZ[1] - coordZ[0]
    distance1 = np.sqrt((coordX[1] - coordX[0])**2 +
                        (coordY[1] - coordY[0])**2)
    d_dist1 = distance1 / (steps1 - 1.0)
    d_step1 = d_dist1
    steps2 = coordZ[2] - coordZ[1]
    distance2 = np.sqrt((coordX[2] - coordX[1])**2 +
                        (coordY[2] - coordY[1])**2)
    d_dist2 = distance2 / (steps2 - 1.0)
    d_step2 = d_dist2
    if ((index_current >= coordZ[0]) & (index_current <= coordZ[1])):
        if ((coordX[0] == 0) & (coordY[0] == 0) & (coordX[1] == 0) &
            (coordY[1] == 0)):
            # create a full region mask (except the boundaries)
            bound_width = 2  # outer boundary width
            mask[bound_width:dimX - bound_width,
                 bound_width:dimY - bound_width] = 1
        else:
            d_step1 = (index_current - coordZ[0]) * d_dist1
            if (distance1 != 0.0):
                t = d_step1 / distance1
            else:
                t = 0.0
            if (coordX[0] == coordX[1]):
                x_t = np.int(coordX[0])
            else:
                x_t1 = np.round((1.0 - t) * coordX[0] + t * coordX[1])
                x_t = np.int(x_t1[0])
            if (coordY[0] == coordY[1]):
                y_t = np.int(coordY[0])
            else:
                y_t1 = np.round((1.0 - t) * coordY[0] + t * coordY[1])
                y_t = np.int(y_t1[0])
            mask = np.uint8(
                circle_level_set(np.shape(mask), (y_t, x_t), mask_radius))
    if ((index_current > coordZ[1]) & (index_current <= coordZ[2])):
        if ((coordX[1] == 0) & (coordY[1] == 0) & (coordX[2] == 0) &
            (coordY[2] == 0)):
            # create a full region mask (except the boundaries)
            bound_width = 2  # outer boundary width
            mask[bound_width:dimX - bound_width,
                 bound_width:dimY - bound_width] = 1
        else:
            d_step2 = (index_current - coordZ[1]) * d_dist2
            if (distance2 != 0.0):
                t = d_step2 / distance2
            else:
                t = 0.0
            if (coordX[1] == coordX[2]):
                x_t = np.int(coordX[1])
            else:
                x_t1 = np.round((1.0 - t) * coordX[1] + t * coordX[2])
                x_t = np.int(x_t1[0])
            if (coordY[1] == coordY[2]):
                y_t = np.int(coordY[1])
            else:
                y_t1 = np.round((1.0 - t) * coordY[1] + t * coordY[2])
                y_t = np.int(y_t1[0])
            mask = np.uint8(
                circle_level_set(np.shape(mask), (y_t, x_t), mask_radius))
    return [mask]
示例#32
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
示例#33
0
    img_contour = []

    # Load the image.
    try:
        imgcolor = imread(str(PATH_IMG_TEM)) / 255.0
    except FileNotFoundError:
        print("No such file, please check.")
        sys.exit()

    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)
示例#34
0
def sphere_seg(v,
               sigma,
               init_level_set=None,
               out_dir='./output',
               save_flag=False):
    """
    sphere_seg: membrane segmentation by sphere fitting

    @params:
        v: volume data  sigma: gaussian sigma for denoising
        init_level_set: initial level set for morphsnake

    @return:
        [x, y, z, R]: coordinates and radius of the sphere

    """
    np.random.seed(12345)
    if save_flag:
        if os.path.exists(out_dir):
            shutil.rmtree(out_dir)
        os.makedirs(out_dir)

    # morphsnake
    if init_level_set:
        init = init_level_set
    else:
        circle_set = circle_level_set(v.shape[:2], (80, 80), 60)
        init_mask = np.zeros(v.shape)
        for i in range(init_mask.shape[2]):
            init_mask[:, :, i] = circle_set
        init = checkerboard_level_set(v.shape)
        init = np.multiply(init, init_mask)

    v_im = AIVU.cub_img(v)['im']
    if save_flag:
        plt.imsave(os.path.join(out_dir, 'original.png'), v_im, cmap='gray')
    vg = FG.smooth(v, sigma)
    mask_v = ACWE(image=vg, iterations=25, init_level_set=init)
    mask_im = AIVU.cub_img(mask_v)['im']
    if save_flag:
        plt.imsave(os.path.join(out_dir, 'morphsnake_result.png'),
                   mask_im,
                   cmap='gray')

    # RANSC
    coords = np.array(np.where(mask_v == 1))
    coords = coords.T  # (N,3)

    # robustly fit line only using inlier data with RANSAC algorithm
    xyz = coords

    model_robust, inliers = ransac(xyz,
                                   CircleModel3D,
                                   min_samples=20,
                                   residual_threshold=3,
                                   max_trials=50)
    outliers = inliers == False
    # print('inliers_num = ', sum(inliers), 'inliers_num = ', sum(outliers))
    x, y, z, R = model_robust.params
    v_RANSC = np.zeros(mask_v.shape)
    assert len(inliers) == coords.shape[0]
    if save_flag:
        for i in range(len(inliers)):
            if inliers[i]:
                v_RANSC[coords[i][0]][coords[i][1]][coords[i][2]] = 2
            else:
                v_RANSC[coords[i][0]][coords[i][1]][coords[i][2]] = 1
        vim_RANSC = AIVU.cub_img(v_RANSC)['im']
        plt.imsave(os.path.join(out_dir, 'RANSC_result.png'),
                   vim_RANSC,
                   cmap='gray')

        a = FG.smooth(v, sigma)
        a.flags.writeable = True
        color = np.min(a)
        thickness = 1
        center = (x, y, z)
        grid = np.mgrid[[slice(i) for i in a.shape]]
        grid = (grid.T - center).T
        phi1 = R - np.sqrt(np.sum((grid)**2, 0))
        phi2 = np.max(R - thickness, 0) - np.sqrt(np.sum((grid)**2, 0))
        res = np.int8(phi1 > 0) - np.int8(phi2 > 0)
        a[res == 1] = color
        vim = AIVU.cub_img(a)['im']
        plt.imsave(os.path.join(out_dir, 'result.png'), vim, cmap='gray')
    return model_robust.params