Exemplo n.º 1
0
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
Exemplo n.º 2
0
    def addCell(self, eventTuple):
        if self.maskOn:
            if self.data.ndim == 2:
                self.aveData = self.data.copy()
            else:
                self.aveData = self.data.mean(axis=2)

            x, y = eventTuple
            localValue = self.currentMask[x, y]
            print str(self.mode) + " " + "x: " + str(x) + ", y: " + str(y) + ", mask val: " + str(localValue)

            # ensure mask is uint16
            self.currentMask = self.currentMask.astype("uint16")

            sys.stdout.flush()

            ########## NORMAL MODE
            if self.mode is None:
                if localValue > 0 and localValue != self.currentMaskNumber:
                    print "we are altering mask at at %d, %d" % (x, y)

                    # copy the old mask
                    newMask = self.currentMask.copy()

                    # make a labeled image of the current mask
                    labeledCurrentMask = mahotas.label(newMask)[0]
                    roiNumber = labeledCurrentMask[x, y]

                    # set that ROI to zero
                    newMask[labeledCurrentMask == roiNumber] = self.currentMaskNumber
                    newMask = newMask.astype("uint16")

                    self.listOfMasks.append(newMask)
                    self.currentMask = self.listOfMasks[-1]
                elif localValue > 0 and self.data.ndim == 3:
                    # update info panel
                    labeledCurrentMask = mahotas.label(self.currentMask.copy())[0]
                    roiNumber = labeledCurrentMask[x, y]
                    self.updateInfoPanel(ROI_number=roiNumber)

                elif localValue == 0:

                    xmin = int(x - self.diskSize)
                    xmax = int(x + self.diskSize)
                    ymin = int(y - self.diskSize)
                    ymax = int(y + self.diskSize)

                    sub_region_image = self.aveData[xmin:xmax, ymin:ymax].copy()
                    # threshold = mahotas.otsu(self.data[xmin:xmax, ymin:ymax].astype('uint16'))

                    # do a gaussian_laplacian filter to find the edges and the center

                    g_l = nd.gaussian_laplace(
                        sub_region_image, 1
                    )  # second argument is a free parameter, std of gaussian
                    g_l = mahotas.dilate(mahotas.erode(g_l >= 0))
                    g_l = mahotas.label(g_l)[0]
                    center = g_l == g_l[g_l.shape[0] / 2, g_l.shape[0] / 2]
                    # edges = mahotas.dilate(mahotas.dilate(mahotas.dilate(center))) - center

                    newCell = np.zeros_like(self.currentMask)
                    newCell[xmin:xmax, ymin:ymax] = center
                    newCell = mahotas.dilate(newCell)

                    if self.useNMF:
                        modes, thresh_modes, fit_data, this_cell, is_cell, nmf_limits = self.doLocalNMF(x, y, newCell)

                        for mode, mode_thresh, t, i in zip(modes, thresh_modes, this_cell, is_cell):
                            # need to place it in the right place
                            # have x and y
                            mode_width, mode_height = mode_thresh.shape
                            mode_thresh_fullsize = np.zeros_like(newCell)
                            mode_thresh_fullsize[
                                nmf_limits[0] : nmf_limits[1], nmf_limits[2] : nmf_limits[3]
                            ] = mode_thresh

                            # need to add all modes belonging to this cell first,
                            # then remove the ones nearby.

                            if i:
                                if t:
                                    valid_area = np.logical_and(
                                        mahotas.dilate(
                                            mahotas.dilate(mahotas.dilate(mahotas.dilate(newCell.astype(bool))))
                                        ),
                                        mode_thresh_fullsize,
                                    )
                                    newCell = np.logical_or(newCell.astype(bool), valid_area)
                                else:
                                    newCell = np.logical_and(
                                        newCell.astype(bool), np.logical_not(mahotas.dilate(mode_thresh_fullsize))
                                    )

                        newCell = mahotas.close_holes(newCell.astype(bool))
                        self.excludePixels(newCell, 2)

                    newCell = newCell.astype(self.currentMask.dtype)

                    # remove all pixels in and near current mask and filter for ROI size
                    newCell[mahotas.dilate(self.currentMask > 0)] = 0
                    newCell = self.excludePixels(newCell, 10)

                    newMask = (newCell * self.currentMaskNumber) + self.currentMask
                    newMask = newMask.astype("uint16")

                    self.listOfMasks.append(newMask.copy())
                    self.currentMask = newMask.copy()

            elif self.mode is "OGB":
                # build structuring elements
                se = pymorph.sebox()
                se2 = pymorph.sedisk(self.cellRadius, metric="city-block")
                seJunk = pymorph.sedisk(max(np.floor(self.cellRadius / 4.0), 1), metric="city-block")
                seExpand = pymorph.sedisk(self.diskSize, metric="city-block")

                # add a disk around selected point, non-overlapping with adjacent cells
                dilatedOrignal = mahotas.dilate(self.currentMask.astype(bool), Bc=se)
                safeUnselected = np.logical_not(dilatedOrignal)

                # tempMask is
                tempMask = np.zeros_like(self.currentMask, dtype=bool)
                tempMask[x, y] = True
                tempMask = mahotas.dilate(tempMask, Bc=se2)
                tempMask = np.logical_and(tempMask, safeUnselected)

                # calculate the area we should add to this disk based on % of a threshold
                cellMean = self.aveData[tempMask == 1.0].mean()
                allMeanBw = self.aveData >= (cellMean * float(self.contrastThreshold))

                tempLabel = mahotas.label(np.logical_and(allMeanBw, safeUnselected).astype(np.uint16))[0]
                connMeanBw = tempLabel == tempLabel[x, y]

                connMeanBw = np.logical_and(np.logical_or(connMeanBw, tempMask), safeUnselected).astype(np.bool)
                # erode and then dilate to remove sharp bits and edges

                erodedMean = mahotas.erode(connMeanBw, Bc=seJunk)
                dilateMean = mahotas.dilate(erodedMean, Bc=seJunk)
                dilateMean = mahotas.dilate(dilateMean, Bc=seExpand)

                modes, thresh_modes, fit_data, this_cell, is_cell, limits = self.doLocaNMF(x, y)

                newCell = np.logical_and(dilateMean, safeUnselected)
                newMask = (newCell * self.currentMaskNumber) + self.currentMask
                newMask = newMask.astype("uint16")

                self.listOfMasks.append(newMask.copy())
                self.currentMask = newMask.copy()

            ########## SQUARE MODE
            elif self.mode is "square":
                self.modeData.append((x, y))
                if len(self.modeData) == 2:
                    square_mask = np.zeros_like(self.currentMask)
                    xstart = self.modeData[0][0]
                    ystart = self.modeData[0][1]

                    xend = self.modeData[1][0]
                    yend = self.modeData[1][1]

                    square_mask[xstart:xend, ystart:yend] = 1

                    # check if square_mask interfers with current mask, if so, abort
                    if np.any(np.logical_and(square_mask, self.currentMask)):
                        return None

                    # add square_mask to mask
                    newMask = (square_mask * self.currentMaskNumber) + self.currentMask
                    newMask = newMask.astype("uint16")

                    self.listOfMasks.append(newMask)
                    self.currentMask = self.listOfMasks[-1]

                    # clear current mode data
                    self.clearModeData()

            ########## CIRCLE MODE
            elif self.mode is "circle":
                # make a strel and move it in place to make circle_mask
                if self.diskSize < 1:
                    return None

                if self.diskSize is 1:
                    se = np.ones((1, 1))
                elif self.diskSize is 2:
                    se = pymorph.secross(r=1)
                else:
                    se = pymorph.sedisk(r=(self.diskSize - 1))

                se_extent = int(se.shape[0] / 2)
                circle_mask = np.zeros_like(self.currentMask)
                circle_mask[x - se_extent : x + se_extent + 1, y - se_extent : y + se_extent + 1] = se * 1.0
                circle_mask = circle_mask.astype(bool)

                # check if circle_mask interfers with current mask, if so, abort
                if np.any(np.logical_and(circle_mask, mahotas.dilate(self.currentMask.astype(bool)))):
                    return None

                # add circle_mask to mask
                newMask = (circle_mask * self.currentMaskNumber) + self.currentMask
                newMask = newMask.astype("uint16")

                self.listOfMasks.append(newMask)
                self.currentMask = self.listOfMasks[-1]

            ########## POLY MODE
            elif self.mode is "poly":
                self.modeData.append((x, y))

            sys.stdout.flush()
            self.makeNewMaskAndBackgroundImage()
def tentDetection_wt_mm(strInputFile, maxTentArea, strOutputFile, strShape='box', iThresh_coeff=0):
    import pywt
    import pymorph as pymm
    
    objImg = osgeo.gdal.Open(strInputFile, GA_ReadOnly)
    nRasterCount = objImg.RasterCount
    poDataset = objImg.ReadAsArray().astype(np.float)
    geotransform = objImg.GetGeoTransform()
    pixelWidth = np.fabs(geotransform[1])
    pixelHeight = np.fabs(geotransform[5])
    resolution = pixelWidth * pixelHeight
    # NoDataValue = objImg.GetRasterBand(1).GetNoDataValue()
    
    # gray scale image
    if (nRasterCount == 1):  
        objnImg = pymm.to_int32(poDataset)
    # RGB image   
    elif(nRasterCount == 3):
        objnImg = pymm.to_gray(poDataset) 
    else:
        print 'it only supports gray-scale or RGB image'
        sys.exit(1)
        
    # determine the structure element
    iNum = int(np.sqrt(maxTentArea) / resolution) + 1
    if (strShape == 'box'):
        objStructureElement = pymm.sebox(iNum)
    elif (strShape == 'cross'):
        objStructureElement = pymm.secross(iNum)
    else:
        objStructureElement = pymm.sedisk(iNum)
          
    # decomposition until 1 level
    wp = pywt.WaveletPacket2D(data=objnImg, wavelet='db4', mode='sym', maxlevel=1)
    # iMaxLevel = wp.maxlevel()
    # top-hat
    wp['h'].data = pymm.openrecth(pymm.to_int32(wp['h'].data), objStructureElement, objStructureElement)
    wp['v'].data = pymm.openrecth(pymm.to_int32(wp['v'].data), objStructureElement, objStructureElement) 
    wp['d'].data = pymm.openrecth(pymm.to_int32(wp['d'].data), objStructureElement, objStructureElement)
    wp['a'].data = 0.5 * wp['a'].data
    # reconstruction 
    wp.reconstruct(update=True)
    
    # top-hat for reconstructed image
    objtophat = pymm.openrecth(pymm.to_int32(wp.data), objStructureElement, objStructureElement)
    
    # y = mean + k*std
    (minValue, maxValue, meanValue, stdValue) = objImg.GetRasterBand(1).GetStatistics(0, 1)
    
    if (nRasterCount == 3):
       (minValue2, maxValue2, meanValue2, stdValue2) = objImg.GetRasterBand(2).GetStatistics(0, 1)
       (minValue3, maxValue3, meanValue3, stdValue3) = objImg.GetRasterBand(3).GetStatistics(0, 1)
       meanValue = 0.2989 * meanValue + 0.5870 * meanValue2 + 0.1140 * meanValue3
       maxValue = 0.2989 * maxValue + 0.5870 * maxValue2 + 0.1140 * maxValue3
    
    # meanValue = 438
    # maxValue = 2047

    threshad = meanValue + iThresh_coeff * stdValue
    
    objTent = pymm.threshad(objtophat, stdValue, maxValue)
            
    data_list = []
    data_list.append(objTent)
   
    WriteOutputImage(strOutputFile, 1, data_list, 0, 0, 0, strInputFile)
def tentDetection_MM(strInputFile, maxTentArea, strOutputFile, strShape='box', iThresh_coeff=0):
    
    # five step to do this
    # 1. opening-determine the square structure element (6-60 m2/resolution)
    # 2. opening by reconstruction
    # 3. top-hat by reconstruction
    # 4. lower threshold
    # 5. double threshold
    import pymorph as pymm
        
    objImg = osgeo.gdal.Open(strInputFile, GA_ReadOnly)
    nRasterCount = objImg.RasterCount
    poDataset = objImg.ReadAsArray().astype(np.float)
    geotransform = objImg.GetGeoTransform()
    pixelWidth = np.fabs(geotransform[1])
    pixelHeight = np.fabs(geotransform[5])
    resolution = pixelWidth * pixelHeight
    # NoDataValue = objImg.GetRasterBand(1).GetNoDataValue()
    
    # gray scale image
    if (nRasterCount == 1):  
        objnImg = pymm.to_int32(poDataset)
    # RGB image   
    elif(nRasterCount == 3):
        objnImg = pymm.to_gray(poDataset) 
    else:
        print 'it only supports gray-scale or RGB image'
        sys.exit(1)
        
    # determine the structure element
    iNum = int(np.sqrt(maxTentArea) / resolution) + 1
    if (strShape == 'box'):
        objStructureElement = pymm.sebox(iNum)
    elif (strShape == 'cross'):
        objStructureElement = pymm.secross(iNum)
    else:
        objStructureElement = pymm.sedisk(iNum)
          
    # opening
    objOpen = pymm.open(objnImg, objStructureElement)
                   
    # opening by reconstruction
    objOpenRec = pymm.openrec(objOpen, objStructureElement, objStructureElement)
        
    objtophat = pymm.openrecth(objnImg, objStructureElement, objStructureElement)
    # objtophat = pymm.subm(objnImg, objOpenRec)
              
    # objTent = pymm.threshad(objtophat, 0.25 * objnImg, 0.40 * objnImg)
    # y = mean + k*std
    (minValue, maxValue, meanValue, stdValue) = objImg.GetRasterBand(1).GetStatistics(0, 1)
    
    if (nRasterCount == 3):
       (minValue2, maxValue2, meanValue2, stdValue2) = objImg.GetRasterBand(2).GetStatistics(0, 1)
       (minValue3, maxValue3, meanValue3, stdValue3) = objImg.GetRasterBand(3).GetStatistics(0, 1)
       meanValue = 0.2989 * meanValue + 0.5870 * meanValue2 + 0.1140 * meanValue3
       maxValue = 0.2989 * maxValue + 0.5870 * maxValue2 + 0.1140 * maxValue3
       
    # meanValue = 438
    # maxValue = 2047
    threshad = meanValue + iThresh_coeff * stdValue
    
    objTent = pymm.threshad(objtophat, threshad, maxValue)
            
    data_list = []
    data_list.append(objTent)
   
    WriteOutputImage(strOutputFile, 1, data_list, 0, 0, 0, strInputFile)

    '''
Exemplo n.º 5
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
Exemplo n.º 6
0
def test_sebox():
    assert np.all(pymorph.sebox(0) == np.array([1]))
    assert np.all(pymorph.sebox(1) == np.ones((3,3)))
    assert np.all(pymorph.sebox(9) == np.ones((2*9+1,2*9+1)))
Exemplo n.º 7
0
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
Exemplo n.º 8
0
def tentDetection_wt_mm(strInputFile,
                        maxTentArea,
                        strOutputFile,
                        strShape='box',
                        iThresh_coeff=0):
    import pywt
    import pymorph as pymm

    objImg = osgeo.gdal.Open(strInputFile, GA_ReadOnly)
    nRasterCount = objImg.RasterCount
    poDataset = objImg.ReadAsArray().astype(np.float)
    geotransform = objImg.GetGeoTransform()
    pixelWidth = np.fabs(geotransform[1])
    pixelHeight = np.fabs(geotransform[5])
    resolution = pixelWidth * pixelHeight
    # NoDataValue = objImg.GetRasterBand(1).GetNoDataValue()

    # gray scale image
    if (nRasterCount == 1):
        objnImg = pymm.to_int32(poDataset)
    # RGB image
    elif (nRasterCount == 3):
        objnImg = pymm.to_gray(poDataset)
    else:
        print 'it only supports gray-scale or RGB image'
        sys.exit(1)

    # determine the structure element
    iNum = int(np.sqrt(maxTentArea) / resolution) + 1
    if (strShape == 'box'):
        objStructureElement = pymm.sebox(iNum)
    elif (strShape == 'cross'):
        objStructureElement = pymm.secross(iNum)
    else:
        objStructureElement = pymm.sedisk(iNum)

    # decomposition until 1 level
    wp = pywt.WaveletPacket2D(data=objnImg,
                              wavelet='db4',
                              mode='sym',
                              maxlevel=1)
    # iMaxLevel = wp.maxlevel()
    # top-hat
    wp['h'].data = pymm.openrecth(pymm.to_int32(wp['h'].data),
                                  objStructureElement, objStructureElement)
    wp['v'].data = pymm.openrecth(pymm.to_int32(wp['v'].data),
                                  objStructureElement, objStructureElement)
    wp['d'].data = pymm.openrecth(pymm.to_int32(wp['d'].data),
                                  objStructureElement, objStructureElement)
    wp['a'].data = 0.5 * wp['a'].data
    # reconstruction
    wp.reconstruct(update=True)

    # top-hat for reconstructed image
    objtophat = pymm.openrecth(pymm.to_int32(wp.data), objStructureElement,
                               objStructureElement)

    # y = mean + k*std
    (minValue, maxValue, meanValue,
     stdValue) = objImg.GetRasterBand(1).GetStatistics(0, 1)

    if (nRasterCount == 3):
        (minValue2, maxValue2, meanValue2,
         stdValue2) = objImg.GetRasterBand(2).GetStatistics(0, 1)
        (minValue3, maxValue3, meanValue3,
         stdValue3) = objImg.GetRasterBand(3).GetStatistics(0, 1)
        meanValue = 0.2989 * meanValue + 0.5870 * meanValue2 + 0.1140 * meanValue3
        maxValue = 0.2989 * maxValue + 0.5870 * maxValue2 + 0.1140 * maxValue3

    # meanValue = 438
    # maxValue = 2047

    threshad = meanValue + iThresh_coeff * stdValue

    objTent = pymm.threshad(objtophat, stdValue, maxValue)

    data_list = []
    data_list.append(objTent)

    WriteOutputImage(strOutputFile, 1, data_list, 0, 0, 0, strInputFile)
Exemplo n.º 9
0
def tentDetection_MM(strInputFile,
                     maxTentArea,
                     strOutputFile,
                     strShape='box',
                     iThresh_coeff=0):

    # five step to do this
    # 1. opening-determine the square structure element (6-60 m2/resolution)
    # 2. opening by reconstruction
    # 3. top-hat by reconstruction
    # 4. lower threshold
    # 5. double threshold
    import pymorph as pymm

    objImg = osgeo.gdal.Open(strInputFile, GA_ReadOnly)
    nRasterCount = objImg.RasterCount
    poDataset = objImg.ReadAsArray().astype(np.float)
    geotransform = objImg.GetGeoTransform()
    pixelWidth = np.fabs(geotransform[1])
    pixelHeight = np.fabs(geotransform[5])
    resolution = pixelWidth * pixelHeight
    # NoDataValue = objImg.GetRasterBand(1).GetNoDataValue()

    # gray scale image
    if (nRasterCount == 1):
        objnImg = pymm.to_int32(poDataset)
    # RGB image
    elif (nRasterCount == 3):
        objnImg = pymm.to_gray(poDataset)
    else:
        print 'it only supports gray-scale or RGB image'
        sys.exit(1)

    # determine the structure element
    iNum = int(np.sqrt(maxTentArea) / resolution) + 1
    if (strShape == 'box'):
        objStructureElement = pymm.sebox(iNum)
    elif (strShape == 'cross'):
        objStructureElement = pymm.secross(iNum)
    else:
        objStructureElement = pymm.sedisk(iNum)

    # opening
    objOpen = pymm.open(objnImg, objStructureElement)

    # opening by reconstruction
    objOpenRec = pymm.openrec(objOpen, objStructureElement,
                              objStructureElement)

    objtophat = pymm.openrecth(objnImg, objStructureElement,
                               objStructureElement)
    # objtophat = pymm.subm(objnImg, objOpenRec)

    # objTent = pymm.threshad(objtophat, 0.25 * objnImg, 0.40 * objnImg)
    # y = mean + k*std
    (minValue, maxValue, meanValue,
     stdValue) = objImg.GetRasterBand(1).GetStatistics(0, 1)

    if (nRasterCount == 3):
        (minValue2, maxValue2, meanValue2,
         stdValue2) = objImg.GetRasterBand(2).GetStatistics(0, 1)
        (minValue3, maxValue3, meanValue3,
         stdValue3) = objImg.GetRasterBand(3).GetStatistics(0, 1)
        meanValue = 0.2989 * meanValue + 0.5870 * meanValue2 + 0.1140 * meanValue3
        maxValue = 0.2989 * maxValue + 0.5870 * maxValue2 + 0.1140 * maxValue3

    # meanValue = 438
    # maxValue = 2047
    threshad = meanValue + iThresh_coeff * stdValue

    objTent = pymm.threshad(objtophat, threshad, maxValue)

    data_list = []
    data_list.append(objTent)

    WriteOutputImage(strOutputFile, 1, data_list, 0, 0, 0, strInputFile)
    '''
Exemplo n.º 10
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