Example #1
0
def _minima_seeds(pmap, start_id):

    minima = mahotas.regmin(pmap)
    seeds, num_seeds = mahotas.label(minima)
    seeds += start_id
    #seeds[seeds==start_id] = 0 # TODO I don't get this
    return seeds, num_seeds
Example #2
0
def get_seeds(boundary, method='grid', next_id=1):

    if method == 'grid':

        height = boundary.shape[0]
        width = boundary.shape[1]

        seed_positions = np.ogrid[0:height:seed_distance,
                                  0:width:seed_distance]
        num_seeds_y = seed_positions[0].size
        num_seeds_x = seed_positions[1].size
        num_seeds = num_seeds_x * num_seeds_y

        seeds = np.zeros_like(boundary).astype(np.int32)
        seeds[seed_positions] = np.arange(next_id,
                                          next_id + num_seeds).reshape(
                                              (num_seeds_y, num_seeds_x))

    if method == 'minima':

        minima = mahotas.regmin(boundary)
        seeds, num_seeds = mahotas.label(minima)
        seeds += next_id
        seeds[seeds == next_id] = 0

    if method == 'maxima_distance':

        distance = mahotas.distance(boundary < 0.5)
        maxima = mahotas.regmax(distance)
        seeds, num_seeds = mahotas.label(maxima)
        seeds += next_id
        seeds[seeds == next_id] = 0

    return seeds, num_seeds
Example #3
0
def watershed(probs, radius):
    if probs.ndim == 3:
        shed = np.zeros(probs.shape)

        for n in xrange(probs.shape[0]):
            sel = disk(radius)
            minima = mh.regmin(probs[n], Bc=sel)
            markers, nr_markers = mh.label(minima)
            shed[n] = mh.cwatershed(probs[n], markers)

    else:
        sel = disk(radius)
        minima = mh.regmin(probs, Bc=sel)
        markers, nr_markers = mh.label(minima)
        shed = mh.cwatershed(probs, markers)

    return shed
def test_float_input():
    "[watershed]: Compare floating point input with integer input"
    f = np.random.random((128, 64))
    f = mh.gaussian_filter(f, 8.)
    f = mh.gaussian_filter(f, 8.)
    markers, _ = mh.label(mh.regmin(f))
    f = np.round(f * 2**30)
    wf = mh.cwatershed(f / 2**30., markers)
    w32 = mh.cwatershed(f.astype(np.int32), markers)
    assert (wf == w32).mean() > .999
Example #5
0
def test_float_input():
    "[watershed]: Compare floating point input with integer input"
    f = np.random.random((128,64))
    f = mh.gaussian_filter(f, 8.)
    f = mh.gaussian_filter(f, 8.)
    markers,_ = mh.label(mh.regmin(f))
    f = np.round(f * 2**30)
    wf = mh.cwatershed(f / 2**30., markers)
    w32 = mh.cwatershed(f.astype(np.int32), markers)
    assert (wf == w32).mean() > .999
Example #6
0
def _segment(cell):
    # takes a numpy array of a microscopy
    # segments it based on filtering the image then applying a distance transform and
    # a watershed method to get the proper segmentation

    import mahotas as mh
    filt_cell = mh.gaussian_filter(cell, 2)
    T = mh.thresholding.otsu((np.rint(filt_cell).astype('uint8')))
    dist = mh.stretch(mh.distance(filt_cell > T))

    Bc = np.ones((3, 3))
    rmax = mh.regmin((dist))
    rmax = np.invert(rmax)
    labels, num_cells = mh.label(rmax, Bc)
    surface = (dist.max() - dist)
    areas = mh.cwatershed(dist, labels)
    areas *= T
    return areas
def _segment(cell):
    # takes a numpy array of a microscopy
    # segments it based on filtering the image then applying a distance transform and
    # a watershed method to get the proper segmentation

    import mahotas as mh
    filt_cell = mh.gaussian_filter(cell, 2)
    T = mh.thresholding.otsu((np.rint(filt_cell).astype('uint8')))
    dist = mh.stretch(mh.distance(filt_cell > T))
    
    Bc = np.ones((3,3))
    rmax = mh.regmin((dist))
    rmax = np.invert(rmax)
    labels, num_cells = mh.label(rmax, Bc)
    surface = (dist.max() - dist)
    areas = mh.cwatershed(dist, labels)
    areas *= T
    return areas
def watershedSegment(image, diskSize=20):
    gradmag = gradientMagnitudue(image)

    ## compute foreground markers

    # open image to create flat regions at cell centers
    se_disk = pymorph.sedisk(diskSize) 
    image_opened = mahotas.open(image, se_disk);

    # define foreground markers as regional maxes of cells
    # this step is slow!
    foreground_markers = mahotas.regmax(image_opened)

    ## compute background markers

    # Threshold the image, cast it to the right datatype, and then calculate the distance image
    image_black_white = image_opened > mahotas.otsu(image_opened)
    image_black_white = image_black_white.astype('uint16')

    # note the inversion here- a key difference from the matlab algorithm
    # matlab distance is to nearest non-zero pixel
    # python distance is to nearest 0 pixel
    image_distance = pymorph.to_uint16(nd.distance_transform_edt(np.logical_not(image_black_white)))
    eight_conn = pymorph.sebox()

    distance_markers = mahotas.label(mahotas.regmin(image_distance, eight_conn))[0]
    image_dist_wshed, image_dist_wshed_lines =mahotas.cwatershed(image_distance, distance_markers, eight_conn, return_lines=True)
    background_markers = image_distance_watershed_lines - image_black_white

    all_markers = np.logical_or(foreground_markers, background_markers)

    # impose a min on the gradient image.  assumes int64
    gradmag2 = imimposemin(gradmag.astype(int), all_markers, eight_conn)

    # call watershed
    segmented_cells, segmented_cell_lines = mahotas.cwatershed(gradmag2, mahotas.label(all_markers)[0], eight_conn, return_lines=True)

    # seperate watershed regions
    segmented_cells[gradientMagnitudue(segmented_cells) > 0] = 0
    return segmented_cells > 0, segmented_cells
Example #9
0
def get_seeds(boundary,
              method='grid',
              next_id=1,
              seed_distance=10,
              boundary_thres=0.5,
              label_nb=None):
    if method == 'grid':
        height = boundary.shape[0]
        width = boundary.shape[1]

        seed_positions = np.ogrid[0:height:seed_distance,
                                  0:width:seed_distance]
        num_seeds_y = seed_positions[0].size
        num_seeds_x = seed_positions[1].size
        num_seeds = num_seeds_x * num_seeds_y
        seeds = np.zeros_like(boundary).astype(np.int32)
        seeds[seed_positions] = np.arange(next_id,
                                          next_id + num_seeds).reshape(
                                              (num_seeds_y, num_seeds_x))

    if method in ['minima', 'maxima_distance']:
        if method == 'minima':
            peak = mahotas.regmin(boundary)
        elif method == 'maxima_distance':
            # distance = mahotas.distance(boundary < boundary_thres)
            distance = ndimage.morphology.distance_transform_cdt(
                boundary < boundary_thres)
            peak = mahotas.regmax(distance)
        if label_nb is None:
            seeds, num_seeds = mahotas.label(peak)
        else:
            seeds, num_seeds = mahotas.label(peak, label_nb)

        seeds[seeds > 0] += next_id

    return seeds, num_seeds
Example #10
0
                    ws = mahotas.cwatershed(blur_prob, seeds)

                with timer.Timer("gradient2"):
                    dx, dy = np.gradient(ws)
                    ws_boundary = np.logical_or(dx != 0, dy != 0)

                ## Identify possible extra-cellular space - distance method
                #extra_cellular = np.logical_and(mahotas.distance(labels==0) > 100, seeds == np.min(seeds))
                #extra_cellular = mahotas.morph.close(extra_cellular.astype(np.bool), disc)
                #extra_cellular = mahotas.morph.open(extra_cellular.astype(np.bool), disc)
                #extra_cellular_indices = np.nonzero(extra_cellular)

                ## Identify possible extra-cellular space - minima method
                with timer.Timer("extra_cellular"):
                    with timer.Timer("    (sub)min"):
                        rmin = mahotas.regmin(blur_prob, min_disc)

                    extra_cellular = np.logical_and(rmin,
                                                    seeds == np.min(seeds))
                    extra_cellular_indices = np.nonzero(extra_cellular)

                extra_cellular_id = np.max(seeds) + 1
                seeds[extra_cellular_indices] = extra_cellular_id

                with timer.Timer("second watershed"):
                    ws = mahotas.cwatershed(blur_prob, seeds)
                dx, dy = np.gradient(ws)
                ws_boundary = np.logical_or(dx != 0, dy != 0)

                ## Optional - mark the extra-cellular space as boundary
                #ws_boundary[np.nonzero(ws == extra_cellular_id)] = 1
Example #11
0
                 ws = mahotas.cwatershed(blur_prob, seeds)
 
             with timer.Timer("gradient2"):
                 dx, dy = np.gradient(ws)
                 ws_boundary = np.logical_or(dx!=0, dy!=0)
 
             ## Identify possible extra-cellular space - distance method
             #extra_cellular = np.logical_and(mahotas.distance(labels==0) > 100, seeds == np.min(seeds))
             #extra_cellular = mahotas.morph.close(extra_cellular.astype(np.bool), disc)
             #extra_cellular = mahotas.morph.open(extra_cellular.astype(np.bool), disc)
             #extra_cellular_indices = np.nonzero(extra_cellular)
 
             ## Identify possible extra-cellular space - minima method
             with timer.Timer("extra_cellular"):
                 with timer.Timer("    (sub)min"):
                     rmin = mahotas.regmin(blur_prob, min_disc)
 
                 extra_cellular = np.logical_and(rmin, seeds == np.min(seeds))
                 extra_cellular_indices = np.nonzero(extra_cellular)
 
             extra_cellular_id = np.max(seeds)+1
             seeds[extra_cellular_indices] = extra_cellular_id
 
             with timer.Timer("second watershed"):
                 ws = mahotas.cwatershed(blur_prob, seeds)
             dx, dy = np.gradient(ws)
             ws_boundary = np.logical_or(dx!=0, dy!=0)
 
             ## Optional - mark the extra-cellular space as boundary
             #ws_boundary[np.nonzero(ws == extra_cellular_id)] = 1
 
Example #12
0
def main(infile):
    img = mahotas.imread(infile)
    infile = os.path.splitext(
        os.path.basename(infile))[0]
    blue_component = img[:,:,B]

    pylab.gray()
    k = 3
    f = ndimage.gaussian_filter(blue_component, 12)
    if DEBUG:
        print 'Procesando imagen %s usando canal azul' % (infile)
        mahotas.imsave('00%s-input.jpg' % infile, f)

    clustered = segment_kmeans(f, k)
    clustered[clustered == k-1] = 0
    mask = ndimage.binary_fill_holes(clustered)

    if DEBUG:
        print 'Segmentacion inicial k-means con k=%d' % k
        mahotas.imsave('01kmeans1%s.jpg' % infile, mask)

    masked = f * mask

    if DEBUG:
        mahotas.imsave('02masked%s.jpg' % infile, masked)

    k = 4
    clustered2 = segment_kmeans(masked, k)

    if DEBUG:
        print 'Resegmentacion k-means con k=%d' % k
        mahotas.imsave('03kmeans2%s.jpg' % infile, clustered2)

    clustered2[(clustered2 != k-2)] = 0
    clustered2[(clustered2 == k-2)] = 1

    if DEBUG:
        mahotas.imsave('04kmeans2binary%s.jpg' % infile, clustered2)

    clustered2 = ndimage.binary_fill_holes(clustered2)

    labeled, _  = mahotas.label(mask)
    if DEBUG:
        print 'Etiquetando imagen segmentacion inicial k-means'
        mahotas.imsave('05kmeans2noholes%s.jpg' % infile, clustered2)
        mahotas.imsave('06kmeans2labeled%s.jpg' % infile, labeled)
        while True:
            min_max = raw_input('label1 min,max? ')
            try:
                min_max = min_max.strip().split(',')
                min_ = int(min_max[0])
                max_ = int(min_max[1])
            except:
                break
            labeled1 = remove_by_size(labeled, min_, max_)
            mahotas.imsave('07labeled1f%d,%d%s.jpg' % (min_, max_, infile), labeled1)

    labeled, _  = mahotas.label(clustered2)
    labeled2 = remove_by_size(labeled, 1600, 23000)

    if DEBUG:
        print 'Etiquetando imagen re-segmentacion k-means'
        mahotas.imsave('08labeled2f%s.jpg' % infile, labeled)
        mahotas.imsave('09labeled2f%s.jpg' % infile, labeled2)

    combined = labeled1 + labeled2

    labeled_to_binary(combined)
    if DEBUG:
        mahotas.imsave('10combined%s.jpg' % infile, combined)

    combined = ndimage.binary_fill_holes(combined)

    if DEBUG:
        mahotas.imsave('11combined_noholes%s.jpg' % infile, combined)

    borders = mahotas.labeled.borders(mahotas.label(combined)[0])

    cells = f * combined
    cells[cells == 0] = 255

    if DEBUG:
        mahotas.imsave('12maskedcellsw%s.jpg' % infile, cells)

    rmin = mahotas.regmin(cells)
    seeds, nr_nuclei = mahotas.label(rmin)

    if DEBUG:
        mahotas.imsave(
            '13gscale-final%s.jpg' % infile,
            pymorph.overlay(blue_component, rmin,
                        borders)
        )

    img2 = np.copy(img)
    img2[borders] = [0,0,0]
    img2[rmin] = [5,250,42]
    mahotas.imsave('14%s-outputcells.jpg' % (infile), img2)

    #watershed
    gradient = ndimage.morphology.morphological_gradient(combined, size=(3,3))
    gradient = gradient.astype(np.uint8)
    if DEBUG:
        print 'Watershed'
        mahotas.imsave('15%s-gradient.jpg' % infile, gradient)
    wshed, lines = mahotas.cwatershed(gradient, seeds, return_lines=True)


    pylab.jet()

    if DEBUG:
        mahotas.imsave('16wshed.jpg', wshed)

    ncells =  len(np.unique(wshed)) - 1
    print '%d cells.' % ncells
    borders = mahotas.labeled.borders(wshed)

    img[borders] = [0,0,0]
    img[rmin] = [5,250,42]
    mahotas.imsave('17%s-output-%dcells.jpg' % (infile, ncells), img)
Example #13
0
def watershedSegment(image, diskSize=20):
    """This routine implements the watershed example from 
    http://www.mathworks.com/help/images/examples/marker-controlled-watershed-segmentation.html, 
    but using pymorph and mahotas.

    :param image: an image (2d numpy array) to be segemented
    :param diskSize: an integer used as a size for a structuring element used 
                     for morphological preprocessing.
    :returns: tuple of binarized and labeled segmention masks
    """
    def gradientMagnitudue(image):
        sobel_x = nd.sobel(image.astype('double'), 0)
        sobel_y = nd.sobel(image.astype('double'), 1)
        return np.sqrt((sobel_x * sobel_x) + (sobel_y * sobel_y))

    def imimposemin(image, mask, connectivity):
        fm = image.copy()
        fm[mask] = -9223372036854775800
        fm[np.logical_not(mask)] = 9223372036854775800

        fp1 = image + 1

        g = np.minimum(fp1, fm)

        j = infrec(fm, g)
        return j

    def infrec(f, g, Bc=None):
        if Bc is None: Bc = pymorph.secross()
        n = f.size
        return fast_conditional_dilate(f, g, Bc, n)

    def fast_conditional_dilate(f, g, Bc=None, n=1):
        if Bc is None:
            Bc = pymorph.secross()
        f = pymorph.intersec(f, g)
        for i in xrange(n):
            prev = f
            f = pymorph.intersec(mahotas.dilate(f, Bc), g)
            if pymorph.isequal(f, prev):
                break
        return f

    gradmag = gradientMagnitudue(image)

    ## compute foreground markers

    # open image to create flat regions at cell centers
    se_disk = pymorph.sedisk(diskSize)
    image_opened = mahotas.open(image, se_disk)

    # define foreground markers as regional maxes of cells
    # this step is slow!
    foreground_markers = mahotas.regmax(image_opened)

    ## compute background markers

    # Threshold the image, cast it to the right datatype, and then calculate the distance image
    image_black_white = image_opened > mahotas.otsu(image_opened)
    image_black_white = image_black_white.astype('uint16')

    # note the inversion here- a key difference from the matlab algorithm
    # matlab distance is to nearest non-zero pixel
    # python distance is to nearest 0 pixel
    image_distance = pymorph.to_uint16(
        nd.distance_transform_edt(np.logical_not(image_black_white)))
    eight_conn = pymorph.sebox()

    distance_markers = mahotas.label(mahotas.regmin(image_distance,
                                                    eight_conn))[0]
    image_dist_wshed, image_dist_wshed_lines = mahotas.cwatershed(
        image_distance, distance_markers, eight_conn, return_lines=True)
    background_markers = image_dist_wshed_lines - image_black_white

    all_markers = np.logical_or(foreground_markers, background_markers)

    # impose a min on the gradient image.  assumes int64
    gradmag2 = imimposemin(gradmag.astype(int), all_markers, eight_conn)

    # call watershed
    segmented_cells, segmented_cell_lines = mahotas.cwatershed(
        gradmag2, mahotas.label(all_markers)[0], eight_conn, return_lines=True)
    segmented_cells -= 1

    # seperate watershed regions
    segmented_cells[gradientMagnitudue(segmented_cells) > 0] = 0
    return segmented_cells > 0, segmented_cells
def watershedSegment(image, diskSize=20):

    def gradientMagnitudue(image):
        sobel_x = nd.sobel(image.astype('double'), 0)
        sobel_y = nd.sobel(image.astype('double'), 1)
        return np.sqrt((sobel_x * sobel_x) + (sobel_y * sobel_y))    

    def imimposemin(image, mask, connectivity):
        fm = image.copy()
        fm[mask] = -9223372036854775800
        fm[np.logical_not(mask)] = 9223372036854775800

        fp1 = image + 1
        
        g = np.minimum(fp1, fm)
        
        j = infrec(fm, g)
        return j

    def infrec(f, g, Bc=None):
        if Bc is None: Bc = pymorph.secross()
        n = f.size
        return fast_conditional_dilate(f, g, Bc, n);

    def fast_conditional_dilate(f, g, Bc=None, n=1):
        if Bc is None:
            Bc = pymorph.secross()
        f = pymorph.intersec(f,g)
        for i in xrange(n):
            prev = f
            f = pymorph.intersec(mahotas.dilate(f, Bc), g)
            if pymorph.isequal(f, prev):
                break
        return f

    gradmag = gradientMagnitudue(image)

    ## compute foreground markers

    # open image to create flat regions at cell centers
    se_disk = pymorph.sedisk(diskSize) 
    image_opened = mahotas.open(image, se_disk);

    # define foreground markers as regional maxes of cells
    # this step is slow!
    foreground_markers = mahotas.regmax(image_opened)

    ## compute background markers

    # Threshold the image, cast it to the right datatype, and then calculate the distance image
    image_black_white = image_opened > mahotas.otsu(image_opened)
    image_black_white = image_black_white.astype('uint16')

    # note the inversion here- a key difference from the matlab algorithm
    # matlab distance is to nearest non-zero pixel
    # python distance is to nearest 0 pixel
    image_distance = pymorph.to_uint16(nd.distance_transform_edt(np.logical_not(image_black_white)))
    eight_conn = pymorph.sebox()

    distance_markers = mahotas.label(mahotas.regmin(image_distance, eight_conn))[0]
    image_dist_wshed, image_dist_wshed_lines = mahotas.cwatershed(image_distance, distance_markers, eight_conn, return_lines=True)
    background_markers = image_dist_wshed_lines - image_black_white

    all_markers = np.logical_or(foreground_markers, background_markers)

    # impose a min on the gradient image.  assumes int64
    gradmag2 = imimposemin(gradmag.astype(int), all_markers, eight_conn)

    # call watershed
    segmented_cells, segmented_cell_lines = mahotas.cwatershed(gradmag2, mahotas.label(all_markers)[0], eight_conn, return_lines=True)
    segmented_cells -= 1
    
    # seperate watershed regions
    segmented_cells[gradientMagnitudue(segmented_cells) > 0] = 0
    return segmented_cells > 0, segmented_cells
Example #15
0
def measure(origimage, cuts, gaussintensity, iteration):
    image = cut(origimage, cuts)
    adjustsize(origimage, image, cuts)
    if not default and iteration in modifyselection:
        limitmod = modifyselection[iteration]
    else:
        limitmod = 0
    ignore = findrim(image, limitmod)
    if rim and len(ignore) <= (cuts**2) * 0.33:
        while len(ignore) <= (cuts**2) * 0.33:
            limitmod += 3
            ignore = findrim(image, limitmod)
    elif len(ignore) >= (cuts**2) * 0.66:
        while len(ignore) >= (cuts**2) * 0.66:
            limitmod -= 3
            ignore = findrim(image, limitmod)
    avmod = len(ignore)
    threshold = applyth(image)
    if not default and iteration in increasegauss:
        usedgaussintensity = gaussintensity**increasegauss[iteration]
    else:
        usedgaussintensity = gaussintensity
    gauss = applygauss(image, usedgaussintensity)
    totalcellarea = 0.0
    subcount = int(math.sqrt(len(image)))
    for r in range(len(image)):
        printprogress(
            (iteration * len(image) + r + 1), (len(inputimages) * len(image)),
            prefix="processing " + str(len(inputimages) - len(badimages)) +
            " images",
            suffix="complete")
        if len(ignore) == 0 or r != ignore[0]:
            cellarea = 0.0
            area = image[r].shape[0] * image[r].shape[1]

            gaussth = gauss[r] > threshold[r]

            for array in gaussth:
                for pixel in array:
                    # variabel machen wenn Zellen hell
                    if pixel == 0:
                        cellarea += 1

            cellperc = (cellarea / area)
            inputimages[iteration][3] = cellperc * 100

            rmin = mh.regmin(gaussth)
            rmin = rmin.astype(np.uint8)

            plt.subplot(subcount, subcount, r + 1)
            plt.axis('off')
            plt.imshow(mh.overlay(image[r], rmin))

            totalcellarea += cellperc
        else:
            plt.subplot(subcount, subcount, r + 1)
            plt.axis('off')
            ignore.pop(0)
    plt.text(
        -7, 7,
        str("ID: " + str(iteration) + ", day: " +
            str(inputimages[iteration][1]) + ", " + str(substancename) +
            " concentration: " + str(inputimages[iteration][2]) + " %"))
    plt.text(
        -7, 6.5,
        str(cellname) + " coverage: " +
        str(round((totalcellarea / ((len(image)) - avmod)) * 100, 2)) + " %")
    plt.axis('off')
    pp.savefig()
    plt.gcf().clear()
Example #16
0
def watershed(probs, radius):
    sel = disk(radius)
    minima = mh.regmin(probs, Bc=sel)
    markers, nr_markers = mh.label(minima)
    return mh.cwatershed(probs, markers)