Example #1
0
def LowResSegmentation(image):
    '''Perform a simple threshold after DoG filtering'''
    noBack = RemoveModalBackground(image)
    #print "from Segmeta noBack:",noBack.min(),noBack.mean()
    blurLowRes = nd.filters.gaussian_filter(noBack, 13)
    blurHiRes = nd.filters.gaussian_filter(noBack, 1)
    midPass = pymorph.subm(blurHiRes, 0.70 * blurLowRes)
    binim = (midPass > 1.5 * midPass.mean())
    binLowRes = pymorph.open(binim, pymorph.sedisk(4))
    binLowRes = pymorph.close_holes(binLowRes)
    return binLowRes
Example #2
0
def LowResSegmentation(image):
    '''Perform a simple threshold after DoG filtering'''
    noBack = RemoveModalBackground(image)
    #print "from Segmeta noBack:",noBack.min(),noBack.mean()
    blurLowRes = nd.filters.gaussian_filter(noBack, 13)
    blurHiRes = nd.filters.gaussian_filter(noBack, 1)
    midPass = pymorph.subm(blurHiRes, 0.70 * blurLowRes)
    binim = (midPass > 1.5 * midPass.mean())
    binLowRes = pymorph.open(binim, pymorph.sedisk(4))
    binLowRes = pymorph.close_holes(binLowRes)
    return binLowRes
Example #3
0
def test_close_holes_simple():
    H = pymorph.binary([
                [0,0,0,0,0,0],
                [0,1,1,1,1,0],
                [0,1,0,0,1,0],
                [0,1,1,1,1,0],
                [0,0,0,0,0,0],
            ])

    Hclosed = pymorph.close_holes(H)
    assert np.all(Hclosed  == pymorph.binary([
                    [0,0,0,0,0,0],
                    [0,1,1,1,1,0],
                    [0,1,1,1,1,0],
                    [0,1,1,1,1,0],
                    [0,0,0,0,0,0],
                    ]))
Example #4
0
    def process(self, im):
        #single pixel restructure element
        elem = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]])

        print "starting img process.. binarizing"
        b1 = im > 205  #binarize
        print "removing single pixels"
        #remove single pixels
        singpix = mahotas.morph.hitmiss(b1, elem)
        b1 = (b1 - singpix) > 0
        print "closing holes"
        b1 = m.close_holes(b1)

        print "thinning"
        #b2 = m.thin(b1) #thin
        b2 = self.shitthin(b1)  #thin
        print "pruning"
        b3 = m.thin(b2, m.endpoints('homotopic'), 8)

        #remove single pixels
        singpix = mahotas.morph.hitmiss(b3, elem)
        b3 = b3 - singpix
        b3 = b3 > 0
        struct = np.ndarray((4, 3, 3), dtype=np.uint8)
        struct[0, :, :] = [[1, 2, 1], [0, 1, 0], [0, 1, 0]]
        for i in range(1, 4):
            print "gen %i structure.." % (i)
            struct[i, :, :] = np.rot90(struct[0], i)

        #struct = struct == 1
        print "using struct for branch summing:"
        print struct

        b4 = np.zeros((301, 398), dtype=bool)

        for i in range(0, 4):
            b4 = b4 | mahotas.morph.hitmiss(b3, struct[i])
        b4 = b4 > 0

        imgout = m.overlay(b1, b2, b4)
        mahotas.imsave("thresh.png", imgout)
        return b4
    def process(self, im):
        # single pixel restructure element
        elem = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]])

        print "starting img process.. binarizing"
        b1 = im > 205  # binarize
        print "removing single pixels"
        # remove single pixels
        singpix = mahotas.morph.hitmiss(b1, elem)
        b1 = (b1 - singpix) > 0
        print "closing holes"
        b1 = m.close_holes(b1)

        print "thinning"
        # b2 = m.thin(b1) #thin
        b2 = self.shitthin(b1)  # thin
        print "pruning"
        b3 = m.thin(b2, m.endpoints("homotopic"), 8)

        # remove single pixels
        singpix = mahotas.morph.hitmiss(b3, elem)
        b3 = b3 - singpix
        b3 = b3 > 0
        struct = np.ndarray((4, 3, 3), dtype=np.uint8)
        struct[0, :, :] = [[1, 2, 1], [0, 1, 0], [0, 1, 0]]
        for i in range(1, 4):
            print "gen %i structure.." % (i)
            struct[i, :, :] = np.rot90(struct[0], i)

            # struct = struct == 1
        print "using struct for branch summing:"
        print struct

        b4 = np.zeros((301, 398), dtype=bool)

        for i in range(0, 4):
            b4 = b4 | mahotas.morph.hitmiss(b3, struct[i])
        b4 = b4 > 0

        imgout = m.overlay(b1, b2, b4)
        mahotas.imsave("thresh.png", imgout)
        return b4
Example #6
0
def test_close_holes_random():
    H = (np.random.rand(100,100) > .2)
    Hclosed = pymorph.close_holes(H)
    assert not (H & ~Hclosed).any()
Example #7
0
import numpy as np
import matplotlib.pyplot as plt
import cv2

address = "results/48x48_av/"
pred = np.load(address + "/results/output.npy")
img = (pred[0,0]*255).astype(np.uint8)

plt.figure()
plt.imshow(img,cmap=plt.cm.gray)

ret,thresh = cv2.threshold(img,127,255,0)

import pymorph
img = pymorph.close_holes(img)

plt.figure()
plt.imshow(img,cmap=plt.cm.gray)

plt.show()
Example #8
0
    def alternative_solution(self,
                             a,
                             orientation='coronal',
                             linethickness=10,
                             outimg=False):
        '''
        Paramenters
        -----------
        a: original image in graylevel
        '''
        H, W = a.shape
        if orientation == 'coronal':
            # UL = mm.limits(a)[1]  # upper limit
            UL = 255

            b = 1 - iacircle(a.shape, H / 3, (1.4 * H / 3, W / 2))  # Circle
            b = b[0:70, W / 2 - 80:W / 2 + 80]  # Rectangle
            # if outimg:
            #     b_ = 0 * a; b_[0:70, W / 2 - 80:W / 2 + 80] = UL * b  # b_ only for presentation
            #     b_[:, W / 2 - linethickness / 2:W / 2 + linethickness / 2] = UL  # b_ only for presentation

            c = a + 0
            c[:, W / 2 - linethickness / 2:W / 2 + linethickness / 2] = UL
            c[0:70, W / 2 - 80:W / 2 +
              80] = (1 - b) * c[0:70, W / 2 - 80:W / 2 + 80] + b * UL
            c[0:40, W / 2 - 70:W / 2 + 70] = UL

            d = mm.open(c, mm.img2se(mm.binary(np.ones((20, 10)))))

            e = mm.close(d, mm.seline(5))

            f = mm.close_holes(e)

            g = mm.subm(f, d)

            h = mm.close_holes(g)

            i = mm.areaopen(h, 1000)

            j1, j2 = iaotsu(i)
            # j = i > j1
            ret, j = cv2.threshold(cv2.GaussianBlur(i, (7, 7), 0), j1, 255,
                                   cv2.THRESH_BINARY)

            k = mm.open(j, mm.seline(20, 90))

            l = mm.areaopen(k, 1000)

            # m = mm.label(l)

            res = np.vstack(
                [np.hstack([c, d, e, f, g]),
                 np.hstack([h, i, j, k, l])])
            cv2.imshow('Result', res)
            cv2.waitKey(0)
            cv2.destroyAllWindows()

            ################################
            # l_ = mm.blob(k,'AREA','IMAGE')
            # l = l_ == max(ravel(l_))

            # m = mm.open(l, mm.sedisk(3))  # VERIFICAR O MELHOR ELEMENTO ESTRUTURANTE AQUI

            # n = mm.label(m)

            if outimg:
                if not os.path.isdir('outimg'):
                    os.mkdir('outimg')

                def N(x):
                    # y = uint8(ianormalize(x, (0, 255)) + 0.5)
                    y = (ianormalize(x, (0, 255)) + 0.5).astype(np.uint8)
                    return y

                adwrite('outimg/a.png', N(a))
                adwrite('outimg/b.png', N(b_))
                adwrite('outimg/c.png', N(c))
                adwrite('outimg/d.png', N(d))
                adwrite('outimg/e.png', N(e))
                adwrite('outimg/f.png', N(f))
                adwrite('outimg/g.png', N(g))
                adwrite('outimg/h.png', N(h))
                adwrite('outimg/i.png', N(i))
                adwrite('outimg/j.png', N(j))
                adwrite('outimg/k.png', N(k))
                adwrite('outimg/l.png', N(l))
                adwrite('outimg/m.png', N(m))
                # adwrite('outimg/n.png', N(n))

            return m

        else:
            b = mm.areaopen(a, 500)

            c = mm.close(b, mm.sebox(3))

            d = mm.close_holes(c)

            e = mm.subm(d, c)

            f = mm.areaopen(e, 1000)

            # g = f > 5
            ret, g = cv2.threshold(cv2.GaussianBlur(f, (5, 5), 0), 3, 255,
                                   cv2.THRESH_BINARY)
            # ret, g = cv2.threshold(
            #     cv2.GaussianBlur(f, (7, 7), 0),
            #     5, 255,
            #     cv2.THRESH_BINARY_INV)

            h = mm.asf(g, 'CO', mm.sedisk(5))

            i = mm.close_holes(h)

            res = np.vstack(
                [np.hstack([a, b, c, d, e]),
                 np.hstack([f, g, h, i, a])])
            cv2.imshow('Result', res)
            cv2.waitKey(0)
            cv2.destroyAllWindows()

            if outimg:
                if not os.path.isdir('outimg'):
                    os.mkdir('outimg')

                def N(x):
                    y = (ianormalize(x, (0, 255)) + 0.5).astype(np.uint8)
                    return y

                adwrite('outimg/a.png', N(a))
                adwrite('outimg/b.png', N(b))
                adwrite('outimg/c.png', N(c))
                adwrite('outimg/d.png', N(d))
                adwrite('outimg/e.png', N(e))
                adwrite('outimg/f.png', N(f))
                adwrite('outimg/g.png', N(g))
                adwrite('outimg/h.png', N(h))
                adwrite('outimg/i.png', N(i))

            return i
Example #9
0
def SearchMarker(In, image_filtree, marker_param, mask):
    """Algorithme principale de recherche de marqueur et segmentation

    :In: image d'entree
    :image_filtree: image filtree par MeanShift
    :marker_param: choix de la methode de recherche (1,2 ou 3)
    :mask: masque de non interet
    :returns: image label, image pour affichee

    """
    if image_filtree.nChannels == 1:
        tmp = cv.CreateImage(cv.GetSize(image_filtree), cv.IPL_DEPTH_8U, 3)
        cv.CvtColor(image_filtree, tmp, cv.CV_GRAY2BGR)
        image_filtree = cv.CloneImage(tmp)
        del tmp

    fg = cv.CloneImage(In)
    objets = None

    # Image distance entre de watershed
    markers = cv.CreateImage(cv.GetSize(In), cv.IPL_DEPTH_32S, 1)
    img = cv.CloneImage(image_filtree)
    cv.Zero(img)

    edge = Detection_contour(In)
    cont = cv2array(edge)[:, :, 0]

    cv.Not(edge, edge)
    dist_map = cv.CreateImage(cv.GetSize(In), cv.IPL_DEPTH_32F, 1)
    cv.DistTransform(edge, dist_map, cv.CV_DIST_L2, cv.CV_DIST_MASK_5)

    dist_map_8bit = cv.CloneImage(edge)
    cv.Zero(dist_map_8bit)
    cv.ConvertScale(dist_map, dist_map, 3000.0, 0.0)
    cv.Pow(dist_map, dist_map, 0.3)
    cv.ConvertScale(dist_map, dist_map_8bit)

    cv.CvtColor(dist_map_8bit, img, cv.CV_GRAY2BGR)  #
    cv.AddWeighted(image_filtree, 0.3, img, 0.7, 1, img)    #
    cv.CvtColor(img, dist_map_8bit, cv.CV_BGR2GRAY)  #

    # Foreground by regional maxima: detection marqueurs
    if marker_param == "1" or marker_param == "3":
        print("Recherche max. regionaux...")
        I = cv2array(dist_map_8bit)[:, :, 0]
        If = ndimage.gaussian_filter(I, 5)
        rmax = pymorph.regmax(If)
        rmax = pymorph.close_holes(rmax) * 255
        #import ipdb;ipdb.set_trace()
        bool_fg = array2cv(rmax.astype(np.uint8))
        cv.ConvertScale(bool_fg, fg)

    if marker_param == "1":
        print("Recherche squelette...")
        from mamba import *
        from mambaComposed import *
        from MambaTools import *
        percent_edge = np.sum(cont) / (edge.width * edge.height)
        initial_shape = (In.height, In.width)
        im1 = fillImageWithIplimage(In)
        imWrk1 = imageMb(im1)
        blobsMarkers = imageMb(im1, 1)
        imWrk3 = imageMb(im1, 32)
        #backgroundMarker = imageMb(im1, 1)
        #finalMarkers = imageMb(im1, 1)
        print("taille se %s" % int(15.0 * 6 / percent_edge + 1))
        if In.height < 700:
            alternateFilter(im1, imWrk1,
                            int(15.0 * 6 / percent_edge) + 1, True)
        elif In.height < 1400:
            alternateFilter(im1, imWrk1,
                            int(30.0 * 6 / percent_edge) + 1, True)
        else:
            alternateFilter(im1, imWrk1,
                            int(60.0 * 6 / percent_edge) + 1, True)
        minima(imWrk1, blobsMarkers)
        thinD(blobsMarkers, blobsMarkers)
        nbStones = label(blobsMarkers, imWrk3)
        bg_array = getArrayFromImage(imWrk3)[
            0: initial_shape[0],
            0: initial_shape[1]]
        tmp_array = (bg_array > 0) * 255
        bg_ = array2cv(tmp_array.astype(np.uint8))
        bg = cv.CloneImage(dist_map_8bit)
        cv.ConvertScale(bg_, bg)
        cv.Or(fg, bg, fg)
    cv.ConvertScale(fg, markers)

    # Watershed
    print("Watershed...")

    storage = cv.CreateMemStorage(0)
    contours = cv.FindContours(fg, storage,
                               cv.CV_RETR_CCOMP,
                               cv.CV_CHAIN_APPROX_SIMPLE)

    def contour_iterator(contour):
        while contour:
            yield contour
            contour = contour.h_next()
    cv.Zero(markers)
    comp_count = 0
    for c in contour_iterator(contours):
        cv.DrawContours(markers,
                        c,
                        cv.ScalarAll(comp_count + 1),
                        cv.ScalarAll(comp_count + 1),
                        -1,
                        -1,
                        8)
        comp_count += 1

    cv.Watershed(img, markers)

    if img.nChannels == 3:
        cv.CvtColor(In, img, cv.CV_GRAY2BGR)
    elif img.nChannels == 1:
        img = cv.CloneImage(image_filtree)
        cv.CvtColor(In, img, cv.CV_GRAY2BGR)
    else:
        print("nChannels >< 3 or 1")
    cv.CvtColor(fg, img, cv.CV_GRAY2BGR)
    cv.CvtColor(In, img, cv.CV_GRAY2BGR)

    #bug
    wshed = Affichage_watershed(markers, img, fg)

    wshed_lbl = cv2array(markers)[:, :, 0]

    if marker_param == "1" or marker_param == "2":
        objets = cv2array(bg)[:, :, 0]
        objets = objets > 1
        print("Keep objects not in background ...")
        cmpt = 0
        label_map = wshed_lbl * 0
        for label in np.unique(wshed_lbl):
            if np.sum(objets * (wshed_lbl == label)) > 0:
                label_map[wshed_lbl == label] = 0
            else:
                cmpt += 1
                label_map[wshed_lbl == label] = cmpt
    else:
        label_map = wshed_lbl
    label_map = Enleve_bord(label_map, mask)
    return label_map, wshed