Пример #1
0
def incorporate_cells(binary_image):    
    # invert input binary image
    inv_image = np.invert(binary_image)
    
    # matrix for binary_dilation
    struct = generate_binary_structure(2, 1)

    # do bunary dilation until the colony number even out
    plate_bin_dil = binary_dilation(inv_image, structure=struct)
    plate_dil_labels = label(plate_bin_dil)
    labels_number = len(np.unique(plate_dil_labels))  # initial number of colonies
    new_labels_number = labels_number - 1  # starting value
    cycle_number = 0  # starting value for dilation cycles
    while True:
        cycle_number += 1
        if cycle_number >= 30:
            break  # defence against infinite cycling
        else:
            if new_labels_number >= labels_number:
                break   # further dilation is useless (in theory)
            else:
                labels_number = new_labels_number
                plate_bin_dil = binary_dilation(plate_bin_dil, structure=struct)
                plate_dil_labels = label(plate_bin_dil)
                new_labels_number = len(np.unique(plate_dil_labels))
                
    return plate_bin_dil
Пример #2
0
def onoff(dc, attribute, roi, spectrum_name="spectrum"):

    # Extract data
    data = dc[attribute]

    # Get limits from ROI
    l, r = np.clip([roi.xmin, roi.xmax], 0, data.shape[2])
    b, t = np.clip([roi.ymin, roi.ymax], 0, data.shape[1])

    # make the 2d on spectrum mask
    mslice = np.zeros(data.shape[1:], dtype=bool)
    mslice[b:t+1,l:r+1] = True

    # make an off spectrum mask
    in_edge_pix = 4
    coreslice = binary_dilation(mslice, iterations=in_edge_pix)
    annular_width_pix = 4
    annslice = binary_dilation(coreslice, iterations=annular_width_pix)
    annslice = annslice-coreslice

    onoffspect = np.zeros(data.shape[0])

    for i, slc in enumerate(data):
        onoffspect[i] = (np.mean(slc[mslice]) -np.mean(slc[annslice]))

    # There is currently a bug that causes cubes to sometimes - but not always
    # have named coordinates.
    try:
        velocity = dc["Velocity", :,0,0]
    except IncompatibleAttribute:
        velocity = dc["World 0", :,0,0]

    return velocity, onoffspect
Пример #3
0
def add_neighbor_border_properties( segment1, segment2, vol):

	if segment1.label < segment2.label:
	# only process them once
		return

	bbx = get_bounding_box_intersection_two_segments(segment1, segment2)

	vol_crop = vol[bbx.xmin:bbx.xmax, bbx.ymin:bbx.ymax, bbx.zmin:bbx.zmax]

	CollectiveBoundingBox = namedtuple("CollectiveBoundingBox",["xmin", "xmax", "ymin", "ymax", "zmin", "zmax"])

	bbx1 = segment1.bounding_box
	bbx2 = segment2.bounding_box
	
	mask1 = binary_dilation(segment1.border_mask[bbx.xmin-bbx1.xmin : bbx.xmax-bbx1.xmin, bbx.ymin-bbx1.ymin : bbx.ymax-bbx1.ymin, bbx.zmin-bbx1.zmin : bbx.zmax-bbx1.zmin] ,structure=np.ones((3,3,1)))
	mask2 = binary_dilation(segment2.border_mask[bbx.xmin-bbx2.xmin : bbx.xmax-bbx2.xmin, bbx.ymin-bbx2.ymin : bbx.ymax-bbx2.ymin, bbx.zmin-bbx2.zmin : bbx.zmax-bbx2.zmin] ,structure=np.ones((3,3,1)))

	mask = mask1*mask2


	s1 = mask1.sum()
	s2 = mask2.sum()
	s = mask.sum()
	segment1.feature_dict["percent_border_with_neighbor"].append((segment2.label, s/float(s1) ))
	segment2.feature_dict["percent_border_with_neighbor"].append((segment1.label, s/float(s2) ))
	segment1.feature_dict["size_border_with_neighbor"].append((segment2.label, s))
	segment2.feature_dict["size_border_with_neighbor"].append((segment1.label, s))
	segment1.feature_dict["mean_intensity_border_with_neighbor"].append((segment2.label, np.sum(mask*vol_crop)/float(s)))
	segment2.feature_dict["mean_intensity_border_with_neighbor"].append((segment1.label, segment1.feature_dict["mean_intensity_border_with_neighbor"][-1][1]))
	
	score1 = segment1.feature_dict["mean_intensity_border_with_neighbor"][-1][1] * ( 1 - segment1.feature_dict["percent_border_with_neighbor"][-1][1])
	segment1.feature_dict["weighted_merge_score"].append((segment2.label, score1))
	segment2.feature_dict["weighted_merge_score"].append((segment1.label, score1))
Пример #4
0
def nlbin(im, threshold=0.5, zoom=0.5, escale=1.0, border=0.1, perc=80,
          range=20, low=5, high=90):
    """
    Performs binarization using non-linear processing.

    Args:
        im (PIL.Image):
        threshold (float):
        zoom (float): Zoom for background page estimation
        escale (float): Scale for estimating a mask over the text region
        border (float): Ignore this much of the border
        perc (int): Percentage for filters
        range (int): Range for filters
        low (int): Percentile for black estimation
        high (int): Percentile for white estimation

    Returns:
        PIL.Image containing the binarized image
    """
    if im.mode == '1':
        return im
    raw = pil2array(im)
    # rescale image to between -1 or 0 and 1
    raw = raw/np.float(np.iinfo(raw.dtype).max)
    if raw.ndim == 3:
        raw = np.mean(raw, 2)
    # perform image normalization
    if np.amax(raw) == np.amin(raw):
        raise KrakenInputException('Image is empty')
    image = raw-np.amin(raw)
    image /= np.amax(image)

    m = interpolation.zoom(image, zoom)
    m = filters.percentile_filter(m, perc, size=(range, 2))
    m = filters.percentile_filter(m, perc, size=(2, range))
    m = interpolation.zoom(m, 1.0/zoom)
    w, h = np.minimum(np.array(image.shape), np.array(m.shape))
    flat = np.clip(image[:w, :h]-m[:w, :h]+1, 0, 1)

    # estimate low and high thresholds
    d0, d1 = flat.shape
    o0, o1 = int(border*d0), int(border*d1)
    est = flat[o0:d0-o0, o1:d1-o1]
    # by default, we use only regions that contain
    # significant variance; this makes the percentile
    # based low and high estimates more reliable
    v = est-filters.gaussian_filter(est, escale*20.0)
    v = filters.gaussian_filter(v**2, escale*20.0)**0.5
    v = (v > 0.3*np.amax(v))
    v = morphology.binary_dilation(v, structure=np.ones((escale*50, 1)))
    v = morphology.binary_dilation(v, structure=np.ones((1, escale*50)))
    est = est[v]
    lo = np.percentile(est.ravel(), low)
    hi = np.percentile(est.ravel(), high)

    flat -= lo
    flat /= (hi-lo)
    flat = np.clip(flat, 0, 1)
    bin = np.array(255*(flat > threshold), 'B')
    return array2pil(bin)
Пример #5
0
def circle_markers(blobs, pic_shape):
    '''Return array with circles around foci found'''

    markers_rad = np.zeros(pic_shape, dtype = np.bool)

    x_max, y_max = pic_shape

    for blob in blobs:

        x, y, r = blob

        r = r*np.sqrt(2)

        rr, cc = circle_perimeter(x, y, np.round(r).astype(int))
        rr_new, cc_new = [], []

        for x_c,y_c in zip(rr,cc):

            if (x_c >= 0) and (x_c < x_max) and (y_c >= 0) and (y_c < y_max):
                rr_new.append(x_c)
                cc_new.append(y_c)

        markers_rad[rr_new, cc_new] = True

    selem = np.array([0,1,0,1,1,1,0,1,0], dtype=bool).reshape((3,3))
    markers_rad = binary_dilation(binary_dilation(markers_rad, selem), selem)

    return markers_rad
Пример #6
0
def fix_holes(im,out,isin):

    if isin.all():
        raise ValueError('Cannot fix holes. All pixels are labeled as holes.')

    isout = isin == False

    # strel for eroding
    se = num.ones((3,3),bool)

    # store dilated version here
    isout1 = num.zeros(isout.shape,dtype=bool)

    # loop, dilating known regions
    while not isout.all():
        
        # get pixels just inside the border
        morph.binary_dilation(isout,se,output=isout1)
        border = isout1 & num.logical_not(isout)
        (yb,xb) = num.nonzero(border)
        yn = num.vstack([yb-1,
                         yb-1,
                         yb-1,
                         yb,
                         yb,
                         yb+1,
                         yb+1,
                         yb+1])
        xn = num.vstack([xb-1,
                         xb,
                         xb+1,
                         xb-1,
                         xb+1,
                         xb-1,
                         xb,
                         xb+1])
        badidx = num.logical_or(yn >= im.shape[0],
                                num.logical_or(yn < 0,
                                               num.logical_or(xn >= im.shape[1],
                                                              xn < 0)))
        yn = yn[badidx == False]
        xn = xn[badidx == False]
        #print "xn = " + str(xn)
        #print "yn = " + str(yn)
        #print "isout[yn,xn] = " + str(isout[yn,xn].astype(int))
        out[yb,xb] = num.average(out[yn,xn],axis=0,weights=isout[yn,xn].astype(float))

#        plt.subplot(121)
#        plt.imshow(isout)
#        plt.subplot(122)
#        plt.imshow(out)
#        plt.show()
        
        # swap isout, isout1x
        isout2 = isout1
        isout1 = isout
        isout = isout2

    return isin
Пример #7
0
def removeLines(img, n):
    imfft = np.fft.fft2(imggray)
    imffts = np.fft.fftshift(imfft)
    
    mags = np.abs(imffts)
    angles = np.angle(imffts)
    
    visual = np.log(mags)

    #visual2 = (visual - visual.min()) / (visual .max() - visual.min())*255
    
    #print np.mean(visual)
    visual3 = np.abs(visual.astype(np.int16) - np.mean(visual))
    
    ret = houghLines(visual3)
    ret = morphology.binary_dilation(ret )
    ret = morphology.binary_dilation(ret )
    ret = morphology.binary_dilation(ret )
    ret = morphology.binary_dilation(ret )
    ret = morphology.binary_dilation(ret )
    w,h=ret.shape
    ret[w/2-3:w/2+3, h/2-3:h/2+3]=False
    
    
    delta = np.mean(visual[ret]) - np.mean(visual)
    imsave("visual_re" + str(n) + ".jpg", visual)
    
    visual_blured = ndimage.gaussian_filter(visual, sigma=5)
    
    #visual[ret] = np.minimum(visual[ret], np.mean(visual)) # visual[vismask] - delta
    
    visual[ret] =visual_blured[ret]
    imsave("visual_ret" + str(n) + ".jpg", visual)
    
    newmagsshift = np.exp(visual)
    
    newffts = newmagsshift * np.exp(1j*angles)
    
    newfft = np.fft.ifftshift(newffts)
    
    imrev = np.fft.ifft2(newfft)
    
    newim2 =  np.abs(imrev).astype(np.uint8)
    
    #newim2[newim2<20] = 255
    newim2 = np.maximum(newim2, img)
    
    
    
    #newim2 = morphology.grey_closing(newim2, 3 )
    
    
    return newim2
Пример #8
0
def foci_markers(blobs, pic_shape):
    '''Return array with foci markers'''

    markers = np.zeros(pic_shape, dtype = np.bool)

    for blob in blobs:

        x, y, r = blob

        markers[x,y] = True

    selem = np.array([0,1,0,1,1,1,0,1,0], dtype=bool).reshape((3,3))
    markers = binary_dilation(binary_dilation(markers, selem), selem)

    return markers
Пример #9
0
	def _get_border_pixels_from_mask(self, mask_in):



		mask = np.zeros((mask_in.shape[0]+2 , mask_in.shape[1] + 2, mask_in.shape[2]+2))
		mask[1:-1,1:-1, 1:-1] = mask_in

		dilated = binary_dilation (mask)


		old_x, old_y, old_z = np.nonzero(dilated - mask)
			
		old_x = old_x - 1
		old_y = old_y - 1
		old_z = old_z - 1

		new_x = np.clip(old_x, 0, mask_in.shape[0]-1)
		new_y = np.clip(old_y, 0, mask_in.shape[1]-1)
		new_z = np.clip(old_z, 0, mask_in.shape[2]-1)


		adjusted_boundary = zip(new_x, new_y, new_z)


		return adjusted_boundary
Пример #10
0
 def __init__(self, geometric_model='affine', tps_grid_size=3, tps_reg_factor=0, h_matches=15, w_matches=15, use_conv_filter=False, dilation_filter=None, use_cuda=True, normalize_inlier_count=False, offset_factor=227/210):
     super(WeakInlierCount, self).__init__()
     self.normalize=normalize_inlier_count
     self.geometric_model = geometric_model
     self.geometricTnf = GeometricTnf(geometric_model=geometric_model,
                                      tps_grid_size=tps_grid_size,
                                      tps_reg_factor=tps_reg_factor,
                                      out_h=h_matches, out_w=w_matches,
                                      offset_factor = offset_factor,
                                      use_cuda=use_cuda)
     # define dilation filter
     if dilation_filter is None:
         dilation_filter = generate_binary_structure(2, 2)
     # define identity mask tensor (w,h are switched and will be permuted back later)
     mask_id = np.zeros((w_matches,h_matches,w_matches*h_matches))
     idx_list = list(range(0, mask_id.size, mask_id.shape[2]+1))
     mask_id.reshape((-1))[idx_list]=1
     mask_id = mask_id.swapaxes(0,1)
     # perform 2D dilation to each channel 
     if not use_conv_filter:
         if not (isinstance(dilation_filter,int) and dilation_filter==0):
             for i in range(mask_id.shape[2]):
                 mask_id[:,:,i] = binary_dilation(mask_id[:,:,i],structure=dilation_filter).astype(mask_id.dtype)
     else:
         for i in range(mask_id.shape[2]):
             flt=np.array([[1/16,1/8,1/16],
                              [1/8, 1/4, 1/8],
                              [1/16,1/8,1/16]])
             mask_id[:,:,i] = scipy.signal.convolve2d(mask_id[:,:,i], flt, mode='same', boundary='fill', fillvalue=0)
         
     # convert to PyTorch variable
     mask_id = Variable(torch.FloatTensor(mask_id).transpose(1,2).transpose(0,1).unsqueeze(0),requires_grad=False)
     self.mask_id = mask_id
     if use_cuda:
         self.mask_id = self.mask_id.cuda();
Пример #11
0
    def _prep(self):
        self._nforeground = self._bimg.sum()        
        # Dilate bimg to make it less strict for the big gap criteria
        # It is needed since sometimes the tracing goes along the
        # boundary of the thin fibre in the binary img
        self._dilated_bimg = binary_dilation(self._bimg)

        if not self._silent:
            print('(2) --Boundary DT...')
        self._make_dt()
        if not self._silent:
            print('(3) --Fast Marching with %s quality...' % ('high' if self._quality else 'low'))
        self._fast_marching()
        if not self._silent:
            print('(4) --Compute Gradients...')
        self._make_grad()

        # Make copy of the timemap
        self._tt = self._t.copy()
        self._tt[self._bimg <= 0] = -2

        # Label all voxels of soma with -3
        self._tt[self._soma.mask > 0] = -3

        # For making a large tube to contain the last traced branch
        self._bb = np.zeros(shape=self._tt.shape)
Пример #12
0
    def _init_mask(self):
        """
        Initialize the mask
        """
        if self.raw_mask is not None:
            self.mask = (self.raw_mask != 0).astype(numpy.int8)
        else:
            self.mask = (self.raw < 0).astype(numpy.int8)
        #mask out the border of the image
        self.mask[0, :] = 1
        self.mask[-1, :] = 1
        self.mask[:, 0] = 1
        self.mask[:, -1] = 1
        to_mask = numpy.where(self.mask)
        #always use a mask!!
        self.do_mask = True #to_mask[0].size > 0
        if self.do_mask:
            self.raw[to_mask] = 0

            #initial grow of 4*sigma_dest ... subsequent re-grow of half
            grow = int(round(4.0 * self.dest_sigma))
            if not pyFAI_morphology:
                my, mx = numpy.ogrid[-grow:grow + 1, -grow:grow + 1]
                grow = (mx * mx + my * my) <= grow * grow
            self.cur_mask = morphology.binary_dilation(self.mask, grow)
            #subsequent grow
            grow = int(2.0 * self.dest_sigma)
            if not pyFAI_morphology:
                my, mx = numpy.ogrid[-grow:grow + 1, -grow:grow + 1]
                grow = (mx * mx + my * my) <= grow * grow
            self.grow = grow
Пример #13
0
    def fix_hole(self,im,out,polygon,isin=None):

        s = num.ones((3,3),bool)        

        # get points on the inside of the polygon
        if isin is None:
            isin = point_inside_polygon(self.X,self.Y,polygon)
        (y_isin,x_isin) = num.nonzero(isin)

        # get points on the outside boundary of the polygon
        isboundary = num.logical_and(morph.binary_dilation(isin,s),
                                     ~isin)

        (y_isboundary,x_isboundary) = num.nonzero(isboundary)

        # for each point inside the polygon, get an average from
        # all the boundary points
        for i in range(len(y_isin)):
            x = x_isin[i]
            y = y_isin[i]
            d = num.sqrt((y_isboundary-y)**2+(x_isboundary-x)**2)
            w = num.exp(-d)
            out[y,x] = num.sum(im[isboundary] * w) / num.sum(w)

        return isin
Пример #14
0
	def get_neighbors(self, label_map):

		cropped_map = label_map[self.bounding_box.xmin : self.bounding_box.xmax+1, self.bounding_box.ymin : self.bounding_box.ymax +1, self.bounding_box.zmin:self.bounding_box.zmax +1]
		neighbors = np.unique( binary_dilation(self.border_mask).astype("int")* cropped_map)
		for x in neighbors:
			if not x in set((0,1,self.label)):
				self.neighbor_labels.add(x)
Пример #15
0
def dilate_mask(maskData, dilation=1, isFullSized=False, is2D=False):
    structuringElement = get_structuring_element(isFullSized, is2D)
    timesDilated = 0
    while timesDilated < dilation:
        maskData = morphology.binary_dilation(maskData, structure=structuringElement)
        timesDilated += 1
    return maskData
Пример #16
0
 def __init__(self, world, x, y):
     self.world = world
     self.listeners = []
     self.viewMap = pad(world.wmap, 1, 'constant')
     self.nears = binary_dilation((world.wmap-255).astype(bool))
     self.reset(x,y)
     self.notNears = logical_not(self.nears)
def measure_of_chaos(img,nlevels): 
    ''' Function for calculating a measure of image noise using level sets
    # Inputs: image - numpy array of pixel intensities
             nlevels - number of levels to calculate over (note that we approximating a continuious distribution with a 'large enough' number of levels)
    # Outputs: measure_value
     
    This function calculates the number of connected regions above a threshold at an evenly spaced number of threshold
    between the min and max values of the image.

    There is some morphological operations to deal with orphaned pixels and heuristic parameters in the image processing.

    # Usage 
    img = misc.imread('/Users/palmer/Copy/ion_image.png').astype(float)
    print measure_of_chaos(img,20)
    '''
    # Image in/preparation
    sum_notnull = np.sum(img > 0)
    if sum_notnull == 0:
        return 0
    im=clean_image(img)

    return float(np.sum([
        ndimage.label(
            morphology.binary_erosion(
                morphology.binary_dilation(im > lev,structure=dilate_mask)
            , structure=erode_mask)
        )[1] for lev in np.linspace(np.amin(im),np.amax(im),nlevels)]))/(sum_notnull*nlevels)
Пример #18
0
def dilate_mask_by_one_voxel(input_nifti, output_nifti=None):
    """
    Dilate Nifti image by one voxel, using a 6-neighborhood structuring element
    (voxels in diagonal are not included in the dilation).
    """

    if not input_nifti.endswith(".nii.gz"):
        raise ValueError("Input has to be .nii.gz file, passed: %s" % input_nifti)

    image = nibabel.load(input_nifti)
    dtype = image.get_data_dtype()

    if output_nifti is None:
        output_nifti = input_nifti.split(".nii.gz")[0] + "_dilated_1vox_6conn.nii.gz"

    structuring_element = np.array([[[0, 0, 0],
                                     [0, 1, 0],
                                     [0, 0, 0]],

                                    [[0, 1, 0],
                                     [1, 1, 1],
                                     [0, 1, 0]],

                                    [[0, 0, 0],
                                     [0, 1, 0],
                                     [0, 0, 0]]])
    data         = image.get_data()
    data_dilated = binary_dilation(data, structuring_element).astype(dtype)

    # Create and save Nifti
    image_dilated = nibabel.Nifti1Image(data_dilated, image.get_affine(),
                                        header=image.get_header())
    image_dilated.to_filename(output_nifti)

    return output_nifti
Пример #19
0
def InsideOutside(s):
    '''
    Create inside-outside function for slice and extract nodes, values
    just inside, just outside and on the boundary
    
    Arguments
    ----
    s : 2D numpy integer array
        Extracted slice of label volume
    '''
    
    nx, ny = s.shape

    # Create boundary layer mask from difference between dilation
    # and erosion of label. The mask represents the layers of
    # voxels immediately inside and outside the boundary.
    bound_mask = binary_dilation(s) - binary_erosion(s)
    
    # Inside-outside function from complement Euclidian distance transforms
    # Positive outside, negative inside
    io = EDT(1-s) - EDT(s)
    
    # Extract x, y coordinates and IO function values boundary layers
    xy = np.argwhere(bound_mask) # N x 2 coordinates of non-zero voxels
    
    # Random downsample by 3
    # Every third point(ish) on boundary should be sufficient for accurate RBF
    n = xy.shape[0]
    samp = np.random.choice(np.arange(n), int(n/3.0))
    xy = xy[samp,:]
    
    io_xy = io[xy[:,0], xy[:,1]] 
    
    return io_xy, xy
Пример #20
0
    def erodeDilate(self, img, method=None):
        """
        Use morphological operators to erode or dilate the ridge structure.
        Dilate uses a recursive call to first dilate then erode.  Dilation
        alone produces ridge structures that are too thick to look
        authentic. Recursive call introduces random spurious minutiae when
        some valley structures are bridged.
        """
        img = np.array(img)
        if not method:
            method = random.choice(('erode', 'dilate', 'none'))
        inkIndex = np.where(img < 250)
        imgBin = np.zeros(np.shape(img))
        imgBin[inkIndex] = 1
        
        strel = morphology.generate_binary_structure(2,2)
        if method == 'erode':
            imgBin = morphology.binary_erosion(imgBin, strel)
        elif method == 'dilate':
            imgBin = morphology.binary_dilation(imgBin, strel)
        else:
            return img

        inkIndex = np.where(imgBin == 1)
        returnImg = 255*np.ones(np.shape(img))
        returnImg[inkIndex] = 0
        
        # Recursive call to erode after dilation to give more authentic
        # appearance.  Erode after dilate introduces spurious minutiae
        # but does not make the ridge structure too thick
        if method == 'dilate':
            self.erodeDilate(returnImg, method='erode')
        
        return returnImg
Пример #21
0
def manual_split(probs, seg, body, seeds, connectivity=1, boundary_seeds=None):
    """Manually split a body from a segmentation using seeded watershed.

    Input:
        - probs: the probability of boundary in the volume given.
        - seg: the current segmentation.
        - body: the label to be split.
        - seeds: the seeds for the splitting (should be just two labels).
        [-connectivity: the connectivity to use for watershed.]
        [-boundary_seeds: if not None, these locations become inf in probs.]
    Value:
        - the segmentation with the selected body split.
    """
    struct = generate_binary_structure(seg.ndim, connectivity)
    body_pixels = seg == body
    bbox = find_objects(body_pixels)[0]
    body_pixels = body_pixels[bbox]
    body_boundary = binary_dilation(body_pixels, struct) - body_pixels
    non_body_pixels = True - body_pixels - body_boundary
    probs = probs.copy()[bbox]
    probs[non_body_pixels] = probs.min()-1
    if boundary_seeds is not None:
        probs[boundary_seeds[bbox]] = probs.max()+1
    probs[body_boundary] = probs.max()+1
    seeds = label(seeds.astype(bool)[bbox], struct)[0]
    outer_seed = seeds.max()+1 # should be 3
    seeds[non_body_pixels] = outer_seed
    seg_new = watershed(probs, seeds, 
        dams=(seg==0).any(), connectivity=connectivity, show_progress=True)
    seg = seg.copy()
    new_seeds = unique(seeds)[:-1]
    for new_seed, new_label in zip(new_seeds, [0, body, seg.max()+1]):
        seg[bbox][seg_new == new_seed] = new_label
    return seg
def getPara(predict, true, threshold, resolution, windowsize):
    (TP, FP, TN, FN, class_lable) = perf_measure(true, predict, threshold)
    if((TP + FN) == 0):
        TPR = 0
    else:
        TPR = np.float(TP) / (TP + FN)

    class_lable = class_lable.astype(bool).reshape(250,  130)
    true = true.astype(bool).reshape((250,  130))

    num = 2
    x = np.arange( -num , num+1, 1)
    xx, yy  = np.meshgrid( x, x )
    struc = (xx * xx + yy * yy)<= num * num
    class_lable = binary_dilation(class_lable, struc)
    class_lable = binary_erosion(class_lable, struc)

    # predict2 = remove_small_objects(class_lable, windowsize * resolution, in_place=False)
    predict2 = remove_small_objects(class_lable, windowsize, in_place=False)
    labeled_array1, num_features1 = label(predict2)
    labeled_array2, num_features2 = label(true)
    FP_num = num_features1 - num_features2
    if FP_num < 0:
        FP_num = 0
    return TPR, FP_num
Пример #23
0
 def plot_maxima(self, display = False):
     vis_maxima = binary_dilation(self.maxima,
                                  structure = np.ones(shape = (1,5,5)))
     masked_maxima = np.ma.masked_where(vis_maxima == 0, vis_maxima)
     self.plot_maxima_stack(masked_maxima, self.smooth_dist_map)
     if display:
         plt.show()
Пример #24
0
def remove_background (image):

  # remove frame if any
  image = image[5:-5, 5:-5, :]

  thresh = np.array([10,10,10]).astype(int)
  c = get_dominant_colors(image, bin_size=thresh/4)
  if c is None: return None

  b, g, r = np.rollaxis(image, axis=-1)
  c = c.astype(int)
  mask = np.ones(r.shape, dtype=bool)
  mask = np.bitwise_and(mask, b.astype(int) >= c[0]-thresh[0])
  mask = np.bitwise_and(mask, b.astype(int) <= c[0]+thresh[0])
  mask = np.bitwise_and(mask, g.astype(int) >= c[1]-thresh[1])
  mask = np.bitwise_and(mask, g.astype(int) <= c[1]+thresh[1])
  mask = np.bitwise_and(mask, r.astype(int) >= c[2]-thresh[2])
  mask = np.bitwise_and(mask, r.astype(int) <= c[2]+thresh[2])

  mask = np.invert(binary_fill_holes(np.invert(mask)))
  for i in range(DILATE_ITER):
    mask = binary_dilation(mask)

  r[mask] = 0
  g[mask] = 0
  b[mask] = 0
  image = np.dstack((b, g, r, np.invert(mask.astype(np.uint8)*255)))
  return image
Пример #25
0
def detect_sources(snmap, threshold):
    hot = (snmap > threshold)
    hot = binary_dilation(hot, iterations=2)
    hot = binary_fill_holes(hot)
    blobs,nblobs = label(hot)
    print(nblobs, 'blobs')
    #print('blobs min', blobs.min(), 'max', blobs.max())
    slices = find_objects(blobs)
    px,py = [],[]
    for i,slc in enumerate(slices):
        blob_loc = blobs[slc]
        sn_loc = snmap[slc]
        imax = np.argmax((blob_loc == (i+1)) * sn_loc)
        y,x = np.unravel_index(imax, blob_loc.shape)
        y0,x0 = slc[0].start, slc[1].start
        px.append(x0+x)
        py.append(y0+y)
        #if i == 0:
        #    plt.subplot(2,2,1)
        #    plt.imshow(blob_loc, interpolation='nearest', origin='lower')
        #    plt.colorbar()
        #    plt.subplot(2,2,2)
        #    plt.imshow((blob_loc==(i+1))*sn_loc, interpolation='nearest', origin='lower')
        #    plt.subplot(2,2,3)
        #    plt.plot(x, y, 'ro')
    return np.array(px),np.array(py)
Пример #26
0
def measure_noise(image_bp, image_raw, radius):
    """Compute the mean and standard deviation of the dark pixels outside the
    signal. The bandpassed image is used to identify background regions. The
    raw image is used to characterize the background.
    See Biophysical journal 88(1) 623-638 Figure C.

    Parameters
    ----------
    image_bp : ndarray
        preprocessed (bandpassed) image
    image_raw : ndarray
        raw image
    radius : number or tuple of numbers
        feature radius used for centroid identification

    Returns
    -------
    background mean, background standard deviation
    """
    structure = binary_mask(radius, image_bp.ndim)
    background = ~morphology.binary_dilation(image_bp, structure=structure)
    n_background = background.sum()
    if n_background == 0:  # edge case of no background identified
        return np.nan, np.nan
    elif n_background == 1:  # edge case of not enough background identified
        return image_raw[background].mean(), np.nan
    else:
        return image_raw[background].mean(), image_raw[background].std()
Пример #27
0
 def plot_boundary_map(X):
     bounds = binary_dilation(X) - X
     H,W = X.shape
     rgba = np.zeros((H,W,4), np.uint8)
     rgba[:,:,1] = bounds*255
     rgba[:,:,3] = bounds*255
     plt.imshow(rgba, interpolation='nearest', origin='lower')
def main():
    args = getArguments(getParser())

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
    
    # loading input images
    b0img, b0hdr = load(args.b0image)
    bximg, bxhdr = load(args.bximage)
    
    # convert to float
    b0img = b0img.astype(numpy.float)
    bximg = bximg.astype(numpy.float)

    # check if image are compatible
    if not b0img.shape == bximg.shape:
        raise ArgumentError('The input images shapes differ i.e. {} != {}.'.format(b0img.shape, bximg.shape))
    if not header.get_pixel_spacing(b0hdr) == header.get_pixel_spacing(bxhdr):
        raise ArgumentError('The input images voxel spacing differs i.e. {} != {}.'.format(header.get_pixel_spacing(b0hdr), header.get_pixel_spacing(bxhdr)))
    
    # check if supplied threshold value as well as the b value is above 0
    if args.threshold is not None and not args.threshold >= 0:
        raise ArgumentError('The supplied threshold value must be greater than 0, otherwise a division through 0 might occur.')
    if not args.b > 0:
        raise ArgumentError('The supplied b-value must be greater than 0.')
    
    # compute threshold value if not supplied
    if args.threshold is None:
        b0thr = otsu(b0img, 32) / 4. # divide by 4 to decrease impact
        bxthr = otsu(bximg, 32) / 4.
        if 0 >= b0thr:
            raise ArgumentError('The supplied b0image seems to contain negative values.')
        if 0 >= bxthr:
            raise ArgumentError('The supplied bximage seems to contain negative values.')
    else:
        b0thr = bxthr = args.threshold
    
    logger.debug('thresholds={}/{}, b-value={}'.format(b0thr, bxthr, args.b))
    
    # threshold b0 + bx DW image to obtain a mask
    # b0 mask avoid division through 0, bx mask avoids a zero in the ln(x) computation
    mask = binary_fill_holes(b0img > b0thr) & binary_fill_holes(bximg > bxthr)
    
    # perform a number of binary morphology steps to select the brain only
    mask = binary_erosion(mask, iterations=1)
    mask = largest_connected_component(mask)
    mask = binary_dilation(mask, iterations=1)
    
    logger.debug('excluding {} of {} voxels from the computation and setting them to zero'.format(numpy.count_nonzero(mask), numpy.prod(mask.shape)))
    
    # compute the ADC
    adc = numpy.zeros(b0img.shape, b0img.dtype)
    adc[mask] = -1. * args.b * numpy.log(bximg[mask] / b0img[mask])
    adc[adc < 0] = 0
            
    # saving the resulting image
    save(adc, args.output, b0hdr, args.force)
Пример #29
0
def main():
    args = getArguments(getParser())

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
    
    # load input image
    data_input, header_input = load(args.input)
    
    # treat as binary
    data_input = data_input.astype(numpy.bool)
    
    # check dimension argument
    if args.dimension and (not args.dimension >= 0 or not args.dimension < data_input.ndim):
        argparse.ArgumentError(args.dimension, 'Invalid dimension of {} supplied. Image has only {} dimensions.'.format(args.dimension, data_input.ndim))
        
    # compute erosion and dilation steps
    erosions = int(math.ceil(args.width / 2.))
    dilations = int(math.floor(args.width / 2.))
    logger.debug("Performing {} erosions and {} dilations to achieve a contour of width {}.".format(erosions, dilations, args.width))
    
    # erode, dilate and compute contour
    if not args.dimension:
        eroded = binary_erosion(data_input, iterations=erosions) if not 0 == erosions else data_input
        dilated = binary_dilation(data_input, iterations=dilations) if not 0 == dilations else data_input
        data_output = dilated - eroded
    else:
        slicer = [slice(None)] * data_input.ndim
        bs_slicer = [slice(None)] * data_input.ndim
        data_output = numpy.zeros_like(data_input)
        for sl in range(data_input.shape[args.dimension]):
            slicer[args.dimension] = slice(sl, sl+1)
            bs_slicer[args.dimension] = slice(1, 2)
            bs = generate_binary_structure(data_input.ndim, 1)
            
            eroded = binary_erosion(data_input[slicer], structure=bs[bs_slicer], iterations=erosions) if not 0 == erosions else data_input[slicer]
            dilated = binary_dilation(data_input[slicer], structure=bs[bs_slicer], iterations=dilations) if not 0 == dilations else data_input[slicer]
            data_output[slicer] = dilated - eroded
    logger.debug("Contour image contains {} contour voxels.".format(numpy.count_nonzero(data_output)))

    # save resulting volume
    save(data_output, args.output, header_input, args.force)
    
    logger.info("Successfully terminated.")    
Пример #30
0
def find_circle(img, npts=25, nstart=0, navg=20, plot=False):

    filled_img = binary_fill_holes(img)
    dil_img = binary_dilation(filled_img)
    edges = dil_img-filled_img
    pts = np.transpose(np.nonzero(edges))
    
    # select an evenly spaced subset of points (to speed up computation):
    if len(pts) > npts:
        indices = np.linspace(nstart, len(pts)-1, npts)
        indices = [int(indices[i]) for i in range(len(indices))]        
    else:
        indices = np.arange(0, len(pts), 1).tolist()
    pts_subset = pts[indices,:]
    
    len_pts_diff = np.arange(1,len(pts_subset), 1)
    
    pts_diff = np.zeros(np.sum(len_pts_diff))
    pts_diff_arr = np.zeros([np.sum(len_pts_diff), 2])
    
    iarr = 0
    for i in range(len(pts_subset)):
        indices = np.arange(i+1, len(pts_subset), 1)
        pts_diff_arr[iarr:len(indices)+iarr, 1] = indices
        pts_diff_arr[iarr:len(indices)+iarr, 0] = np.ones_like(indices)*i
        
        d_arr = pts_subset[indices.tolist(), :] - pts_subset[i,:]
        d = np.array( [np.linalg.norm(d_arr[n]) for n in range(len(d_arr))] )
        pts_diff[iarr:len(indices)+iarr] = d
        
        iarr += len(indices)
        
    ordered_pairs = np.argsort(pts_diff)[::-1]
    best_pairs = pts_diff_arr[(ordered_pairs[0:navg]).tolist()]
    
    center_arr = np.zeros([len(best_pairs), 2])
    radius_arr = np.zeros([len(best_pairs), 1])
    
    #centers = np.zeros([len(best_pairs)])
    for i, pair in enumerate(best_pairs):
        pt1 = np.array(pts_subset[ pair[0] ], dtype=float)
        pt2 = np.array(pts_subset[ pair[1] ], dtype=float)
    
        pt_diff = pt2 - pt1
        radius_arr[i] = np.linalg.norm( pt_diff ) / 2.
        center_arr[i] = pt1 + pt_diff/2
        
    center = np.mean(center_arr, axis=0)
    radius = np.mean(radius_arr)
    
    if plot:
        fig = plt.figure(None)
        ax = fig.add_axes([.1,.1,.8,.8])
        circle = patches.Circle( center, radius=radius, facecolor='none', edgecolor='green')
        ax.add_artist(circle)
        ax.imshow(edges)
        
    return center, radius
Пример #31
0
def dilate_segment(data, segmap, segID, parentID, makecopy=False, expand=5):
    '''
    Dilate a segment. Only pixels in the parent segment with brightness
    less than the minimum of the pre-dilated segment can be updated.
    
    Parameters
    ----------
    data : 2D float array
        The data.
        
    segmap : 2D int array
        The segmentation image.
        
    segID : int
        The segment ID of the segment to dilate.
        
    parentID : int
        The segment ID of the parent segment.
        
    makecopy : bool
        Make a copy of the segmentation image?
        
    expand : int
        The size of the dilation kernel.
    '''    
    if makecopy:
        segmap=segmap.copy()
      
    #Do the dilation
    kernel = geometry.unit_tophat(expand)  
    dilated = binary_dilation(segmap==segID, structure=kernel)
    
    #Update the segmap
    cond = (dilated>0) & (segmap==parentID) & (data<data[segmap==segID].min())
    segmap[cond] = segID
        
    return segmap
Пример #32
0
def manual_split(probs, seg, body, seeds, connectivity=1, boundary_seeds=None):
    """Manually split a body from a segmentation using seeded watershed.

    Input:
        - probs: the probability of boundary in the volume given.
        - seg: the current segmentation.
        - body: the label to be split.
        - seeds: the seeds for the splitting (should be just two labels).
        [-connectivity: the connectivity to use for watershed.]
        [-boundary_seeds: if not None, these locations become inf in probs.]
    Value:
        - the segmentation with the selected body split.
    """
    struct = generate_binary_structure(seg.ndim, connectivity)
    body_pixels = seg == body
    bbox = find_objects(body_pixels)[0]
    body_pixels = body_pixels[bbox]
    body_boundary = binary_dilation(body_pixels, struct) - body_pixels
    non_body_pixels = True - body_pixels - body_boundary
    probs = probs.copy()[bbox]
    probs[non_body_pixels] = probs.min() - 1
    if boundary_seeds is not None:
        probs[boundary_seeds[bbox]] = probs.max() + 1
    probs[body_boundary] = probs.max() + 1
    seeds = label(seeds.astype(bool)[bbox], struct)[0]
    outer_seed = seeds.max() + 1  # should be 3
    seeds[non_body_pixels] = outer_seed
    seg_new = watershed(probs,
                        seeds,
                        dams=(seg == 0).any(),
                        connectivity=connectivity,
                        show_progress=True)
    seg = seg.copy()
    new_seeds = unique(seeds)[:-1]
    for new_seed, new_label in zip(new_seeds, [0, body, seg.max() + 1]):
        seg[bbox][seg_new == new_seed] = new_label
    return seg
Пример #33
0
def single_obj_scoremap(scoremap, filter_size=21):
    
    s = scoremap.size() # (b,2,256,256)
    #assert len(s) == 4, "score map must be 4D"

    scoremap_softmax = F.softmax(scoremap, dim=1)
    scoremap_softmax = scoremap_softmax[:, 1:, :, :] # hand score map
    scoremap_val, _ = scoremap_softmax.max(dim=1, keepdim=False) # argmax (b, 256, 256)
    detmap_fg = torch.round(scoremap_val) # (b,256,256)
    

    max_loc = find_max_location(scoremap_val).to(torch.float32) # (b, 256, 256)

    # max location을 사용하여 dilation
    objectmap_list = []
    kernel_dil = torch.ones(filter_size, filter_size, device=scoremap.device) / float(filter_size * filter_size)

    for i in range(s[0]): # 각 배치마다 
        objectmap = max_loc[i].clone()
        
        num_passes = max(s[2], s[3]) // (filter_size//2)
        
        for j in range(num_passes): # max값 
            objectmap = torch.reshape(objectmap, [1, 1, s[2], s[3]]) # (1, 256, 256)
            objectmap_num = objectmap.cpu().detach().numpy()

            ####### TODO: dilation morphology #######
            objectmap_dil = binary_dilation(objectmap_num).astype(np.float32)
            objectmap_dil = torch.tensor(objectmap_dil).to(device)
            objectmap_dil = torch.reshape(objectmap_dil, [s[2],s[3]])
            objectmap = torch.round(detmap_fg[i]*objectmap_dil)
        
        objectmap = torch.reshape(objectmap, [1, s[2],s[3]])
        objectmap_list.append(objectmap)
    
    objectmap_list = torch.stack(objectmap_list) # 1x1x256x256
    return objectmap_list
Пример #34
0
    def _binary_dilation(self):
        vol_name = str(self.out_edit.text())
        num = self.structure_combo.currentIndex() + 3
        self.structure_array = np.ones((num,num,num), dtype=np.int)
        # self.orgin = self.origin_edit.text()

        if not vol_name:
            self.out_edit.setFocus()
            return

        source_row = self.source_combo.currentIndex()
        source_data = self._model.data(self._model.index(source_row),
                                       Qt.UserRole + 6)

        binary_vol = imtool.binaryzation(source_data,
                                    (source_data.max() + source_data.min()) / 2)
        new_vol = morphology.binary_dilation(binary_vol,
                                             structure=self.structure_array,
                                             border_value=1)
        self._model.addItem(new_vol,
                            None,
                            vol_name,
                            self._model._data[0].get_header())
        self.done(0)
Пример #35
0
def get_probe_from_vacuum_3Dstack(data,
                                  mask_threshold=0.2,
                                  mask_expansion=12,
                                  mask_opening=3):
    """
    Averages all diffraction patterns in a 3D stack of diffraction patterns, assumed to
    be taken over vacuum, to create and average vacuum probe. No alignment is performed
    - i.e. it is assumed that the beam was stationary during acquisition of the stack.

    Values outisde the average probe are zeroed, using a binary mask determined by the
    optional parameters mask_threshold, mask_expansion, and mask_opening.  An initial
    binary mask is created using a threshold of less than mask_threshold times the
    maximal probe value. A morphological opening of mask_opening pixels is performed to
    eliminate stray pixels (e.g. from x-rays), followed by a dilation of mask_expansion
    pixels to ensure the entire probe is captured.

    Args:
        data (array): a 3D stack of vacuum diffraction patterns, shape (Q_Nx,Q_Ny,N)
        mask_threshold (float): threshold determining mask which zeros values outside of
            probe
        mask_expansion (int): number of pixels by which the zeroing mask is expanded to
            capture the full probe
        mask_opening (int): size of binary opening used to eliminate stray bright pixels

    Returns:
        (array of shape (Q_Nx,Q_Ny)): the average probe
    """
    probe = np.average(data, axis=2)

    mask = probe > np.max(probe) * mask_threshold
    mask = binary_opening(mask, iterations=mask_opening)
    mask = binary_dilation(mask, iterations=1)
    mask = np.cos((np.pi / 2) * np.minimum(
        distance_transform_edt(np.logical_not(mask)) / mask_expansion, 1))**2

    return probe * mask
Пример #36
0
def counts_in_contour(contours, fitsim, dilate=2):

    if not isinstance(contours, matplotlib.path.Path):
        contours = matplotlib.path.Path(contours)

    header = fitsim.header
    img = fitsim.data

    wcs = pywcs.WCS(header)
    #wcsgrid = wcs.wcs_pix2world( np.array(zip(np.arange(wcs.naxis1),np.arange(wcs.naxis2))), 0 ).T
    yy,xx = np.indices(img.shape)
    wyx = wcs.wcs_pix2world(zip(yy.ravel(),xx.ravel()),0)
    mask = contours.contains_points(wyx)

    #pix_paths = [wcs.wcs_world2pix(p,0) for p in contours]

    mask = mask.reshape(img.shape)

    inside = img[mask].sum()

    rind = np.array(binary_dilation(mask, iterations=dilate) - mask,dtype='bool')
    outside = img[rind].mean()

    return inside-outside*mask.sum()
Пример #37
0
def preprocess(camera,f):    
    img=cam.image(camera,f);  ###img object contains four data fields: rgb, red, rbr, and cm 
    img.undistort(rgb=True);  ###undistortion
    if img.rgb is None:
        return
#     plt.imshow(img.rbr,vmin=-0.7,vmax=0.2); plt.show();
    
    
    mask=(img.rgb[:,:,2]>0) & ((img.rgb[:,:,2]<76))  ####all other cameras
#     mask=(img.rgb[:,:,2]>0) & ((img.rgb[:,:,2]<80) | ((img.rgb[:,:,1]<img.rgb[:,:,0]-5) & (img.rgb[:,:,1]<img.rgb[:,:,2]-5)))  ####HD5A

    mask=morphology.binary_closing(mask,np.ones((9,9)))
    mask=remove_small_objects(mask, min_size=15, connectivity=4)
    mask=morphology.binary_dilation(mask,np.ones((21,21))) 
    mask=morphology.binary_closing(mask,np.ones((17,17))) 
    mask=remove_small_objects(mask, min_size=1000, connectivity=4)

    fig,ax=plt.subplots(2,2,sharex=True,sharey=True);     
    ax[0,0].imshow(img.rgb); ax[0,1].imshow(img.rbr,vmin=-0.2,vmax=0.1); 
    ax[1,0].imshow(mask); ax[1,1].imshow(img.rgb[:,:,2]) 
#     plt.figure(); plt.hist(img.rbr[img.rbr>-1],bins=100);
    plt.show()

    np.save(camID+'_mask',mask);   
Пример #38
0
def vad_trim_silences(wav):
    samples_per_window = (config.VAD_WIN_LEN * config.SR) // 1000
    wav = wav[:len(wav) - (len(wav) % samples_per_window)]
    pcm_wave = struct.pack(
        "%dh" % len(wav),
        *(np.round(wav * config.INT_16_MAX)).astype(np.int16))

    voice_flags = []
    vad = webrtcvad.Vad(mode=3)
    for window_start in range(0, len(wav), samples_per_window):
        window_end = window_start + samples_per_window
        voice_flags.append(
            vad.is_speech(pcm_wave[window_start * 2:window_end * 2],
                          sample_rate=config.SR))

    voice_flags = np.array(voice_flags)
    audio_mask = moving_average(voice_flags, config.VAD_AVERAGE)
    audio_mask = np.round(audio_mask).astype(np.bool)

    audio_mask = binary_dilation(audio_mask,
                                 np.ones(config.VAD_MAX_SILENCE + 1))
    audio_mask = np.repeat(audio_mask, samples_per_window)

    return wav[audio_mask == True]
Пример #39
0
	def fill(img,szs,Xs):
		sz=szs[0]
		image_size=img.shape[0]
		r=np.random.randint(image_size-sz)
		c=np.random.randint(image_size-sz)
		img[r:r+sz,c:c+sz]=1.0
		Xs[0]=img==1

		for i,sz in enumerate(szs[1:]):
			# print sz
			validmask=binary_dilation(img,struct2,sz)

			zeroxc=xc[validmask==0].flatten()
			zeroyc=yc[validmask==0].flatten()
			validmask=np.logical_and(zeroxc<=image_size-sz,zeroyc<=image_size-sz) 
			ri=np.random.randint(validmask.sum())
			zeroxc=zeroxc[validmask]
			zeroyc=zeroyc[validmask]
			r=zeroxc[ri]
			c=zeroyc[ri]
			img[r:r+sz,c:c+sz]=1.0
			Xs[i+1][r:r+sz,c:c+sz] =True

		return img,Xs[0],Xs[1],Xs[2]
Пример #40
0
    def create_mask(self, path, outdir):
        """create a mask using otsu thresholding"""
        filename = os.path.basename(path)
        filename = os.path.splitext(filename)[0]

        image, header = nrrd.read(path)
        image = self.normalize_intensity(image)
        image = self.hist_equalization(image)
        #nrrd.write(outdir+filename+ '_histogram_normalized.nrrd', image, header=header)

        #normalized_image = (image - np.mean(image)) / np.std(image)
        #nrrd.write(outdir + filename + '_normalized.nrrd', normalized_image, header=header)

        val = filters.threshold_otsu(image)
        # convert to binary to speed up next processing
        blobs = image > val
        # Dilation enlarges bright regions and shrinks dark regions
        mask = morph.binary_dilation(blobs, iterations=20)
        # Closing remove pepper spots and connects small bright cracks. Close up dark gaps between bright features
        mask = morph.binary_closing(mask, iterations=10)

        # Create a convex hull - Not the fastest way
        #for z in range(0, mask.shape[2]):
        #    mask[:,:,z] = skimorph.convex_hull_image(mask[:,:,z])

        #mask = spatial.ConvexHull(mask, incremental = True)
        # convert to 0 and 1 float
        mask = measure.label(mask, background=0.0).astype('float32')
        mask[mask > 0] = 1
        nrrd.write(outdir + filename + '_dilated_mask.nrrd',
                   mask,
                   header=header)

        #print('--- Done ' + filename + ' ---')

        return mask
Пример #41
0
def denoise_spectrogram(spect, threshold=1, filter_size = (2,2)):
  """
  input:
    spectrogram, matrix
  output:
    denoised spectrogram, binary matrix as in bird singing paper
  """

  # map to [0,1]
  minVal = np.min(spect)
  maxVal = np.max(spect)
  spect = (spect - minVal)/(maxVal - minVal)

  # convert to binary
  row_medians = np.tile(np.median(spect, axis=1, keepdims=True), (1, spect.shape[1]))
  col_medians = np.tile(np.median(spect, axis=0, keepdims=True), (spect.shape[0], 1))
  spect_ = (spect > threshold * row_medians).astype('int') * (spect > threshold * col_medians).astype('int')
  
  # apply erosion + dilation
  structure_filter = np.ones(filter_size)
  spect_ = binary_erosion(spect_, structure=structure_filter)
  spect_ = binary_dilation(spect_, structure=structure_filter)

  return spect_
Пример #42
0
def BluryEdgeOfROI(initial_ROI):
    '''
    This function blurry the ROI. This function can be used when the ROI was drawn not definitely.
    :param initial_ROI: The binary ROI image, support 2D and 3D
    :return:
    '''
    if len(np.shape(initial_ROI)) == 2:
        kernel = np.ones((3, 3))
    elif len(np.shape(initial_ROI)) == 3:
        kernel = np.ones((3, 3, 3))
    else:
        print('Only could process 2D or 3D data')
        return []

    initial_ROI = initial_ROI == 1

    ROI_dilate = binary_dilation(input=initial_ROI,
                                 structure=kernel,
                                 iterations=1)
    ROI_erode = binary_erosion(input=ROI_dilate,
                               structure=kernel,
                               iterations=1)
    ROI_erode1 = binary_erosion(input=ROI_erode,
                                structure=kernel,
                                iterations=1)
    ROI_erode2 = binary_erosion(input=ROI_erode1,
                                structure=kernel,
                                iterations=1)

    dif_dilate = (ROI_dilate - ROI_erode) * 0.25
    dif_ori = (ROI_erode - ROI_erode1) * 0.5
    dif_in = (ROI_erode1 - ROI_erode2) * 0.75

    blurred_ROI = ROI_erode2 + dif_dilate + dif_ori + dif_in

    return blurred_ROI
Пример #43
0
def get_intermediate_skintorso_labels(w_mask, sat_margin, sat_filled):
    """FIXME! briefly describe function

    :param w_mask: 2d numpy.ndarray, water mask
    :param sat_margin: 2d numpy.ndarray
    :param sat_filled: 2d numpy.ndarray
    :returns:
    :rtype: tuple of three 2d numpy.ndarray of bools

    """
    # find (watery) skin around torso
    # iteratively push skin margin mask to the outside (by binary dilation)
    # if union with the water mask drops by drop_ratio_thresh then stop
    # number of iterations = skinwidth_torso
    skin_filled = sat_filled
    skin_margin = sat_margin
    nvoxels_skin_torso = len(np.where(sat_margin)[0])
    nvoxels_skin_torso_prev = nvoxels_skin_torso
    nvoxel_rel_drop = (np.abs(nvoxels_skin_torso - nvoxels_skin_torso_prev) /
                       nvoxels_skin_torso_prev)
    drop_ratio_thresh = 0.5
    while nvoxel_rel_drop <= drop_ratio_thresh:
        skin_filled = skin_margin | skin_filled
        skin_margin = (binary_dilation(skin_filled) ^ skin_filled) & w_mask
        nvoxels_skin_torso = nvoxels_skin_torso_prev
        nvoxels_skin_torso_prev = len(np.where(skin_margin)[0])
        if nvoxels_skin_torso_prev == 0:
            break
        nvoxel_rel_drop = \
            (np.abs(nvoxels_skin_torso_prev - nvoxels_skin_torso) /
             nvoxels_skin_torso_prev)

    skin_filled = skin_margin | skin_filled
    skintorso_mask = (skin_margin | skin_filled) ^ sat_filled

    return skintorso_mask, skin_margin, skin_filled
Пример #44
0
def brain_detection(image,
                    voxel,
                    foreground_mask,
                    subsample=[4, 2, 1],
                    iterations=[40, 8, 2],
                    lambda2=20):
    """Create mask of brain region only"""
    if foreground_mask is not None:
        se = np.ones((5, ) * len(foreground_mask.shape))
        mask = ndim.binary_erosion(foreground_mask, structure=se, iterations=3)
        mask = _largest_connected_component(mask)
    else:
        mask = None
    mean, std = _background_statistics(image)
    for i, s in enumerate(subsample):
        new_res = np.ceil(np.array(image.shape) / s).astype(int)
        if tuple(new_res) == image.shape:
            image_small = image
        else:
            image_small = _resample(image, res=list(new_res))
        if mask is not None:
            mask = _resample(mask, res=list(new_res), order=0)
        mask = _segment(image_small,
                        lambda2=lambda2,
                        iterations=iterations[i],
                        sigma=8. / voxel,
                        threshold=mean,
                        init=mask)
    # simple topological corrections
    mask = ndim.binary_erosion(mask, iterations=2)
    mask = _largest_connected_component(mask)
    mask = ndim.binary_dilation(mask, iterations=2)
    mask = ndim.binary_fill_holes(mask).astype(np.uint8)
    if mask.shape != image.shape:
        mask = _resample(mask, res=image.shape, order=0)
    return mask
Пример #45
0
def rasterize_file_dilated_line(
        vector_filename_in, reference_file, thin_line_raster_filename_out,
        dilation_structure=None, dilation_iterations=1, query=None,
):
    """
    Rasterize the vector geometry at vector_filename_in, returning an
    ndarray.  Use the image dimensions, boundary, and other metadata
    from reference_file (an in-memory object).  A rasterization with
    only 1px-thick lines is written to thin_line_raster_filename_out.

    The lines are thickened with binary dilation, with the structuring
    element and iteration count provided by the dilation_structure and
    dilation_iterations arguments respectively.

    If query is passed, it is used as a SQL where-clause to select
    certain features.
    """
    rasterize_file_thin_line(vector_filename_in, reference_file,
                             thin_line_raster_filename_out, query)
    thin_line_file = gdal_utils.gdal_open(thin_line_raster_filename_out)
    return morphology.binary_dilation(
        thin_line_file.GetRasterBand(1).ReadAsArray(),
        dilation_structure, dilation_iterations,
    )
Пример #46
0
def genSegMalis(gg3, iter_num):  # given input seg map, widen the seg border
    from scipy.ndimage import morphology as skmorph
    #from skimage import morphology as skmorph
    gg3_dz = np.zeros(gg3.shape).astype(np.uint32)
    gg3_dz[1:, :, :] = (np.diff(gg3, axis=0))
    gg3_dy = np.zeros(gg3.shape).astype(np.uint32)
    gg3_dy[:, 1:, :] = (np.diff(gg3, axis=1))
    gg3_dx = np.zeros(gg3.shape).astype(np.uint32)
    gg3_dx[:, :, 1:] = (np.diff(gg3, axis=2))

    gg3g = ((gg3_dx + gg3_dy) > 0)
    #stel=np.array([[1, 1],[1,1]]).astype(bool)
    #stel=np.array([[0, 1, 0],[1,1,1], [0,1,0]]).astype(bool)
    stel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]).astype(bool)
    #stel=np.array([[1,1,1,1],[1, 1, 1, 1],[1,1,1,1],[1,1,1,1]]).astype(bool)
    gg3gd = np.zeros(gg3g.shape)
    for i in range(gg3g.shape[0]):
        gg3gd[i, :, :] = skmorph.binary_dilation(gg3g[i, :, :],
                                                 structure=stel,
                                                 iterations=iter_num)
    out = gg3.copy()
    out[gg3gd ==
        1] = 0  #out[0,:,:]=0 # for malis                                                                            return out
    return out
Пример #47
0
def mean_binary(binaries,
                image,
                iterations=1,
                min_intensity=0,
                area_threshold=0,
                sigma=None):
    """Compares two binary of image and produces a
    filter based on the overlap"""

    intensity_map = image * np.mean(binaries, axis=0)
    intensity_mask = np.where(intensity_map > min_intensity, True, False)

    # Remove small holes and objects from masks
    intensity_mask = remove_small_holes(intensity_mask,
                                        area_threshold=area_threshold)
    intensity_mask = remove_small_objects(intensity_mask,
                                          min_size=area_threshold)

    # Dilate image
    binary = binary_dilation(intensity_mask, iterations=iterations)

    smooth_binary(binary, sigma)

    return binary.astype(int)
Пример #48
0
def process_mask(mask):
    """
    mask标注预处理相关
    :param mask: 
    :return: 
    """
    convex_mask = np.copy(mask)
    for i_layer in range(convex_mask.shape[0]):
        # np.ascontiguousarray方法copy返回一个跟参数array有一样shape的连续数组
        mask1 = np.ascontiguousarray(mask[i_layer])
        if np.sum(mask1) > 0:  # 有mask目标
            # convex_hull_image是CV高级形态学处理函数,输入为二值图像,输出一个逻辑二值图像,在凸包内的点为True, 否则为False
            mask2 = convex_hull_image(mask1)
            if np.sum(mask2) > 1.5 * np.sum(
                    mask1):  # 凸包生成的凸多边形太过分,掩盖了原始mask1的大致形状信息,则放弃凸包处理
                mask2 = mask1
        else:  # 没有mask目标
            mask2 = mask1
        convex_mask[i_layer] = mask2
    # 二值膨胀
    struct = generate_binary_structure(3, 1)
    dilatedMask = binary_dilation(convex_mask, structure=struct, iterations=10)
    # 返回膨胀后的mask
    return dilatedMask
Пример #49
0
    def _run_interface(self, runtime):
        orig_file_nii = nb.load(self.inputs.in_file)
        in_file_data = orig_file_nii.get_fdata()

        # pad the data to avoid the mask estimation running into edge effects
        in_file_data_padded = np.pad(
            in_file_data, (1, 1), "constant", constant_values=(0, 0)
        )

        padded_nii = nb.Nifti1Image(
            in_file_data_padded, orig_file_nii.affine, orig_file_nii.header
        )

        mask_nii = compute_epi_mask(padded_nii, exclude_zeros=True)

        mask_data = np.asanyarray(mask_nii.dataobj).astype(np.uint8)
        if isdefined(self.inputs.dilation):
            mask_data = binary_dilation(mask_data).astype(np.uint8)

        # reverse image padding
        mask_data = mask_data[1:-1, 1:-1, 1:-1]

        # exclude zero and NaN voxels
        mask_data[in_file_data == 0] = 0
        mask_data[np.isnan(in_file_data)] = 0

        better_mask = nb.Nifti1Image(
            mask_data, orig_file_nii.affine, orig_file_nii.header
        )
        better_mask.set_data_dtype(np.uint8)
        better_mask.to_filename("mask_file.nii.gz")

        self._mask_file = os.path.join(runtime.cwd, "mask_file.nii.gz")

        runtime.returncode = 0
        return super(ComputeEPIMask, self)._run_interface(runtime)
Пример #50
0
    def _remove_outside_body(self, img_patch):

        h, w = img_patch.shape

        se = generate_binary_structure(2, 2)
        img_patch = binary_dilation(img_patch, structure=se).astype('uint8')

        for c in [0, w - 1]:
            x = np.where(img_patch[:, c] == 0)[0]
            while(len(x)):
                mask = region_growing([[x[0], c]], img_patch == 0)
                img_patch += mask
                x = np.where(img_patch[:, c] == 0)[0]

        for r in [0, h - 1]:
            x = np.where(img_patch[r, :] == 0)[0]
            while(len(x)):
                mask = region_growing([[r, x[0]]], img_patch == 0)
                img_patch += mask
                x = np.where(img_patch[r, :] == 0)[0]

        img_patch = binary_erosion(img_patch, structure=se).astype('uint8')

        return img_patch
Пример #51
0
def MRClean(frame, z_thresh=8.0):
    """
    Attempt to repair scan lines corrupted by MRI RF or gradient pulses.

    Parameters
    ----------
    frame : numpy integer array
        Original corrupted, interlaced video frame
    cfg : configuration object
        Pipeline configuration parameters

    Returns
    -------
    frame_clean : numpy integer array
        Repaired interlaced frame
    art_power : float
        Artifact power in frame

    Example
    -------
    >>>

    """

    # Internal debug flag
    DEBUG = False

    # Init repaired frame
    frame_clean = frame.copy()

    # Split frame into even and odd lines
    fr_even = frame[0::2, :]
    fr_odd = frame[1::2, :]

    # Odd - even frame difference
    df = fr_odd.astype(float) - fr_even.astype(float)

    # Row mean of frame difference
    df_row_mean = np.mean(df, axis=1)

    # Artifact power - mean square of row means
    art_power = np.mean(df_row_mean**2)

    # Robust estimate of noise SD in row projection
    sd_n = ip.WaveletNoiseSD(df_row_mean)

    # Frame difference projection z-scores
    z = df_row_mean / sd_n

    # Find scanlines with |z| > z_thresh
    bad_rows = np.abs(z) > z_thresh

    # Median smooth the bad rows mask then dilate by 3 lines (kernel 2*3+1 = 7)
    bad_rows = medfilt(bad_rows)
    bad_rows = binary_dilation(bad_rows, structure=np.ones((7, )))

    # If an artifact is present
    if np.sum(bad_rows) > 0:

        # Add leading and trailing zero to bad rows flag array
        # This lets forward difference work correctly below
        bad_rows_pad = np.append(0, np.append(bad_rows, 0))

        # Find bad row block start and end indices by forward differencing
        # Add leading and trailing zeros to avoid unterminated blocks
        # Remember this later when determining correct row indices
        dbad = np.diff(bad_rows_pad)

        # Bad row block start and end indices
        # bad_on indicates row indices immediately prior to block starts
        # bad_off indicates row indices immediate after block ends
        bad_on = (np.where(dbad > 0))[0] - 1
        bad_off = (np.where(dbad < 0))[0]

        if bad_on.size != bad_off.size:
            print('Block start and end arrays differ in size - returning')
            return frame_clean, art_power

        # Init cleaned half frames
        fr_odd_clean = fr_odd.copy()
        fr_even_clean = fr_even.copy()

        # Loop over last good rows before bad blocks
        for i, r0 in enumerate(bad_on):

            # First good row after bad block
            r1 = bad_off[i]

            # Protect against overrange rows
            # This reduces artifact cleanup effectiveness if bad rows
            # Are adjacent to the top or bottom of the frame
            nr = fr_odd.shape[0]
            r0 = utils._clamp(r0, 0, nr - 1)
            r1 = utils._clamp(r1, 0, nr - 1)

            # Linear interp between leading and trailing good rows
            odd_interp = InterpRows(fr_odd, r0, r1)
            even_interp = InterpRows(fr_even, r0, r1)

            # Extract equivalent rows from original odd and even frames
            odd_orig = fr_odd[r0:r1 + 1, :]
            even_orig = fr_even[r0:r1 + 1, :]

            # Calculate RMS difference between interp and orig
            odd_rms_diff = utils._rms(odd_orig - odd_interp)
            even_rms_diff = utils._rms(even_orig - even_interp)

            # If RMS diff for odd < even, consider odd rows, clean
            # and vise versa
            if odd_rms_diff < even_rms_diff:
                fr_even_clean[r0:r1 + 1, :] = odd_orig
            else:
                fr_odd_clean[r0:r1 + 1, :] = even_orig

        # Reinterlace cleaned frame
        frame_clean[0::2, :] = fr_odd_clean
        frame_clean[1::2, :] = fr_even_clean

        # Display results
        if DEBUG:

            ny = bad_rows.shape[0]
            y = np.arange(0, ny)

            plt.figure(1)
            plt.set_cmap('jet')

            plt.subplot(321)
            plt.imshow(fr_odd)
            plt.title('Odd')

            plt.subplot(322)
            plt.imshow(fr_even)
            plt.title('Even')

            plt.subplot(323)
            plt.imshow(fr_odd_clean)
            plt.title('Odd Repaired')

            plt.subplot(324)
            plt.imshow(fr_even_clean)
            plt.title('Even Repaired')

            plt.subplot(325)
            plt.imshow(df)
            plt.title('Odd - Even')

            plt.subplot(326)
            plt.plot(y, z, y, bad_rows * z.max() * 0.9)
            plt.title('Z-score and Bad Row Mask')

            plt.show()

    return frame_clean, art_power
Пример #52
0
mask_cc_part_img = nib.Nifti1Image(mask_cc_part.astype(np.uint8), affine)
nib.save(mask_cc_part_img, 'cc.nii.gz')
"""Now that we are happy with our crude CC mask that selected voxels in the x-direction,
we can use all the voxels to estimate the mean signal in this region.

"""

mean_signal = np.mean(data[mask_cc_part], axis=0)
"""Now, we need a good background estimation. We will re-use the brain mask
computed before and invert it to catch the outside of the brain. This could
also be determined manually with a ROI in the background.
[Warning: Certain MR manufacturers mask out the outside of the brain with 0's.
One thus has to be careful how the noise ROI is defined].
"""

mask_noise = binary_dilation(mask, iterations=10)
mask_noise[..., :mask_noise.shape[-1] // 2] = 1
mask_noise = ~mask_noise
mask_noise_img = nib.Nifti1Image(mask_noise.astype(np.uint8), affine)
nib.save(mask_noise_img, 'mask_noise.nii.gz')

noise_std = np.std(data[mask_noise, :])
print('Noise standard deviation sigma= ', noise_std)
"""We can now compute the SNR for each DWI. For example, report SNR
for DW images with gradient direction that lies the closest to
the X, Y and Z axes.
"""

# Exclude null bvecs from the search
idx = np.sum(gtab.bvecs, axis=-1) == 0
gtab.bvecs[idx] = np.inf
Пример #53
0
def bird_net_filter(spectra, f_ind=None, area_threshold=5):
    ''' Series of pre-proecessing filters  based on 
    http://www.animalsoundarchive.org/RefSys/Nips4b2013NotesAndSourceCode/ 
    WorkingNotes_Mario.pdf
    
    Input: 
        spectra - magnitude squared spectra
        f_idx1 - index of the lowest frequency to retain
        f_idx2 - index of the highest frequency to retain
    
    1) Normalise
    2) Brute band pass filter 
    3) Set pixles to 1 if >3x median rows AND columns
    4) closing
    5) Dialation
    5) Median filtering
    6) Remove non-connnected pixels at a given threshold

    '''

    flag = False
    if len(spectra.shape) == 2:
        flag = True
        spectra = np.reshape(spectra, (1, spectra.shape[0], spectra.shape[1]))

    # 1) normalize
    spectra = np.real(spectra)
    sums = np.sum(np.sum(spectra, axis=1), axis=1)
    dvision = spectra / np.reshape(sums, [spectra.shape[0], 1, 1])
    spectra = np.sqrt(dvision)

    #2) Clip lowest and highest bins
    if f_ind is not None:
        spectra = spectra[:, :, f_ind[0]:f_ind[1]]

    for ii in range(spectra.shape[0]):

        spec = spectra[ii, :, :]

        #3) set values greter than 3x the median to 1 and others to 0
        med_threshold = max(max(np.median(spec, axis=0)),
                            max(np.median(spec, axis=1)))

        spec[spec > med_threshold] = 1
        spec[spec <= med_threshold] = 0

        #4) Closing
        spec = binary_closing(spec).astype(np.int)

        #5) Dialation
        spec = binary_dilation(spec).astype('float32')

        #6) Median filter
        spec = medfilt2d(spec).astype('float32')

        #7) Threshold remove pixels
        # 7a) Label regions
        spec = label(spec, connectivity=1)
        # 7b) get metrics for each region
        metrics = regionprops(spec)

        # 7c) remove the values less than image
        for m in metrics:
            if m.area < area_threshold:
                spec[spec == m.label] = 0

        #8) Set all labeled values back to 1
        spec[spec > 1] = 1

        spectra[ii, :, :] = spec

    np.sum(np.sum(spectra, axis=1), axis=1)

    if flag is True:
        spectra = np.reshape(spectra, (spectra.shape[1], spectra.shape[2]))

    return spectra
Пример #54
0
    res = None
    for i in images:
        if res is None:
            res = i.astype(int)
        else:
            res = res + i.astype(int)
    res = res / len(images)
    return res


if __name__ == "__main__":
    sub_dir = sys.argv[1]

    treshold = float(sys.argv[2])
    iterations = int(sys.argv[3])

    nif = nib.load(sub_dir + '/combined.nii.gz')
    fd = nif.get_fdata()
    aff = nif.affine
    imares = fd > treshold

    imares = morph.binary_fill_holes(imares)
    imares = morph.binary_dilation(imares, iterations=iterations)
    imares = morph.binary_fill_holes(imares)
    imares = morph.binary_erosion(imares, iterations=iterations)

    imares = imares.astype(np.int8)

    nif = nib.Nifti1Image(imares, aff)
    nib.save(nif, sub_dir + '/output.nii.gz')
Пример #55
0
rotated_cube = np.dot(cube_points, q3.rotation_matrix)

rotated_cube = np.round(rotated_cube - np.min(rotated_cube)).astype(int)

sample_nx = np.max(rotated_cube) + 2

sample = np.zeros((sample_nx, sample_nx, sample_nx))

for i in range(cube_nx ** 3):
    sample[rotated_cube[i, 0], rotated_cube[i, 1], rotated_cube[i, 2]] = 1


generation_ims = []
fig = plt.figure()
for i in range(np.max(rotated_cube) + 2):

    sample_im = sample[:, :, i]

    # scipym.binary_fill_holes(sample_im,structure=np.ones((2,2)),output=sample_im)
    scipym.binary_dilation(sample_im, structure=np.ones((2, 2)), output=sample_im)

    generation_im = plt.imshow(sample_im, animated=True)

    generation_ims.append([generation_im])

ani = animation.ArtistAnimation(
    fig, generation_ims, interval=100, blit=False, repeat_delay=0
)

plt.show()
Пример #56
0
def generate_morph_imbib_curv(seg_image_input,R_critical):
    # This funciton works well at high-Pc-low-Sw 
    # There is no retarded Sw when the curvature is high
    # The method of this functions:
    # 1. Perform erosion with the radius of R_critical
    # 2. Perform dilation with the radius of R_critical
    # *********************************************************************
    # Input: seg_image: a well shaped segmented image with size (lz,ly,lx)
    #        seg_image has values as : NW phase -> 1
    #                                   W phase -> 2
    #                               solid phase -> 0
    # *********************************************************************
    if seg_image_input.ndim == 2:
        pore_vol = 1.0*(seg_image_input>0.0).sum()
        radius = R_critical
        print 'Morphological Imbibition: processing critical radius: '+str(radius)+' now......'

        # Step 1.1: Create structuring element
        domain_size = int(np.rint(radius*2)+2)
        grid = np.indices((domain_size,domain_size))
        mk_circle = (grid[0]-domain_size/2)**2 + (grid[1]-domain_size/2)**2 <= radius**2
        circle = np.zeros((domain_size,domain_size),dtype=np.uint8)
        circle[mk_circle]=1
        circle = extract_shape(circle).astype(bool)
        
        # Step 1.2: Perform erosion with radius of R_critical
        seg_image_ero = morphology.binary_erosion(seg_image_input>0.0,structure=circle,border_value=1) 
        # NOTE: Be careful with the 'border_value' of the erosion - should be 'border_value=1'

        # Step 2: Perform dilation with radius of R_critical
        seg_image_ero_dil = morphology.binary_dilation(seg_image_ero,structure=circle,border_value=0)
        # NOTE: 'border_value' for dilation should be 'False'
        # NOTE: the dtype of the array after dilation is 'bool'
        seg_image_ero_dil[seg_image_input<=0.0]=False

        Sw = 1.0 - seg_image_ero_dil.sum()/pore_vol
    else:
        pore_vol = 1.0*(seg_image_input>0.0).sum()
        radius = R_critical
        print 'Morphological Imbibition: processing critical radius: '+str(radius)+' now......'

        # Step 1.1: Create structuring element
        domain_size = int(np.rint(radius*2)+2)
        grid = np.indices((domain_size,domain_size,domain_size))
        mk_circle = (grid[0]-domain_size/2)**2 + (grid[1]-domain_size/2)**2 + (grid[2]-domain_size/2)**2 <= radius**2
        circle = np.zeros((domain_size,domain_size,domain_size),dtype=np.uint8)
        circle[mk_circle]=1
        circle = extract_shape(circle).astype(bool)
        
        # Step 1.2: Perform erosion with radius of R_critical
        seg_image_ero = morphology.binary_erosion(seg_image_input>0.0,structure=circle,border_value=1) 
        # NOTE: Be careful with the 'border_value' of the erosion - should be 'border_value=1'

        # Step 2: Perform dilation with radius of R_critical
        seg_image_ero_dil = morphology.binary_dilation(seg_image_ero,structure=circle,border_value=0)
        # NOTE: 'border_value' for dilation should be 'False'
        # NOTE: the dtype of the array after dilation is 'bool'
        seg_image_ero_dil[seg_image_input<=0.0]=False

        Sw = 1.0 - seg_image_ero_dil.sum()/pore_vol
    #end if
    return Sw
Пример #57
0
def generate_morph_drain_curv(seg_image_input,R_critical):
    # The method for this function follows Hilper & Miller AWR(2001)
    # 1. Perform erosion for the pore space with radius of R_critical
    # 2. Label the eroded pore space, and leave only the pore space that is still 
    #    connected with the non-wetting phase reservoir
    # 3. Perform the dilation for the labelled pore space with radius of R_critical
    # ****************************************************************************
    # Currently I am provided with a 3D SignDist image which has positive values
    # in the pore space and 0.0 in the solid phase.
    # ****************************************************************************
    if seg_image_input.ndim == 2:

        pore_vol = 1.0*(seg_image_input>0.0).sum()
        radius = R_critical
        print 'Morphological Drainage: processing critical radius: '+str(radius)+' now......'

        # Step 1.1: Create structuring element
        domain_size = int(np.rint(radius*2)+2)
        grid = np.indices((domain_size,domain_size))
        mk_circle = (grid[0]-domain_size/2)**2 + (grid[1]-domain_size/2)**2 <= radius**2
        circle = np.zeros((domain_size,domain_size),dtype=np.uint8)
        circle[mk_circle]=1
        circle = extract_shape(circle).astype(bool)

        # Step 1.2: Perform erosion on the pore space
        # NOTE: the dtype of 'seg_im_ero' is 'bool'
        seg_im_ero = morphology.binary_erosion(seg_image_input>0.0,structure=circle,border_value=1)
        # NOTE: 'border_value' for erosion should be 'True'

        # Step 2: Label the eroded pore space
        # NOTE: Assume the NW phase reservoir is at the first layer of the domain
        #       i.e. at seg_image[0,:] - adjust it if this does not suit your need
        # For erosion, assume that diagonals are not considered
        seg_im_ero_label_temp,num_features = measurements.label(seg_im_ero,structure=morphology.generate_binary_structure(2,1))
        #seg_im_ero_label_temp,num_features = measurements.label(seg_im_ero,structure=morphology.generate_binary_structure(2,2))
        # NOTE: Here I assume the inlet is at the first layer of the array's axis=2 (i.e. domain[0,:,:])\
        #       You can always change to any other layers as the inlet for this drainage.
        label_check = seg_im_ero_label_temp[0,seg_im_ero_label_temp[0,:]!=0]
        label_check = np.unique(label_check)

        # NOTE the following lines are only for your to check things
        # ******************** For check *******************************#
        # It assign the labelled array as: NW -> 1, W -> 2, Solid -> 0
        #seg_im_ero_label_show = seg_im_ero_label.copy()
        #seg_im_ero_label_show[seg_im_ero_label_show !=1] = 2
        #seg_im_ero_label_show[np.logical_not(seg_image_2d)]=0
        # ******************** End: for check **************************#
        
        seg_im_ero_label = np.zeros_like(seg_im_ero_label_temp,dtype=bool)
        for labels in label_check:
            seg_im_ero_label = np.logical_or(seg_im_ero_label,seg_im_ero_label_temp==labels)
        #seg_im_ero_label = seg_im_ero_label.astype(np.uint8)
        
        # Step 3: perform dilation on the labelled pore space 
        seg_im_ero_label_dil = morphology.binary_dilation(seg_im_ero_label,structure=circle,border_value=0)
        # NOTE: 'border_value' for dilation should be 'False'
        # NOTE: the dtype of 'seg_im_ero_label_dil' is 'bool'
        seg_im_ero_label_dil[seg_image_input<=0.0]=False
        
        Sw = 1.0 - seg_im_ero_label_dil.sum()/pore_vol
    else:

        pore_vol = 1.0*(seg_image_input>0.0).sum()
        radius = R_critical
        print 'Morphological Drainage: processing critical radius: '+str(radius)+' now......'

        # Step 1.1: Create structuring element
        domain_size = int(np.rint(radius*2)+2)
        grid = np.indices((domain_size,domain_size,domain_size))
        mk_circle = (grid[0]-domain_size/2)**2 + (grid[1]-domain_size/2)**2 + (grid[2]-domain_size/2)**2 <= radius**2
        circle = np.zeros((domain_size,domain_size,domain_size),dtype=np.uint8)
        circle[mk_circle]=1
        circle = extract_shape(circle).astype(bool)

        # Step 1.2: Perform erosion on the pore space
        # NOTE: the dtype of 'seg_im_ero' is 'bool'
        seg_im_ero = morphology.binary_erosion(seg_image_input>0.0,structure=circle,border_value=1)
        # NOTE: 'border_value' for erosion should be 'True'

        # Step 2: Label the eroded pore space
        # NOTE: Assume the NW phase reservoir is at the first layer of the domain
        #       i.e. at seg_image[0,:] - adjust it if this does not suit your need
        # For erosion, assume that diagonals are not considered
        seg_im_ero_label_temp,num_features = measurements.label(seg_im_ero,structure=morphology.generate_binary_structure(3,1))
        #seg_im_ero_label_temp,num_features = measurements.label(seg_im_ero,structure=morphology.generate_binary_structure(3,3))
        # NOTE: Here I assume the inlet is at the first layer of the array's axis=2 (i.e. domain[0,:,:])\
        #       You can always change to any other layers as the inlet for this drainage.
        label_check = seg_im_ero_label_temp[0,seg_im_ero_label_temp[0,:]!=0]
        label_check = np.unique(label_check)

        # NOTE the following lines are only for your to check things
        # ******************** For check *******************************#
        # It assign the labelled array as: NW -> 1, W -> 2, Solid -> 0
        #seg_im_ero_label_show = seg_im_ero_label.copy()
        #seg_im_ero_label_show[seg_im_ero_label_show !=1] = 2
        #seg_im_ero_label_show[np.logical_not(seg_image_2d)]=0
        # ******************** End: for check **************************#
        
        seg_im_ero_label = np.zeros_like(seg_im_ero_label_temp,dtype=bool)
        for labels in label_check:
            seg_im_ero_label = np.logical_or(seg_im_ero_label,seg_im_ero_label_temp==labels)
        #seg_im_ero_label = seg_im_ero_label.astype(np.uint8)
        
        # Step 3: perform dilation on the labelled pore space 
        seg_im_ero_label_dil = morphology.binary_dilation(seg_im_ero_label,structure=circle,border_value=0)
        # NOTE: 'border_value' for dilation should be 'False'
        # NOTE: the dtype of 'seg_im_ero_label_dil' is 'bool'
        seg_im_ero_label_dil[seg_image_input<=0.0]=False
        
        Sw = 1.0 - seg_im_ero_label_dil.sum()/pore_vol
    #end if 
    return Sw
Пример #58
0
                file_names_tumor.append(root+'\\'+name)   
            elif name.endswith(".tif") and name.find("normal")>=0:
                file_names_normal.append(root+'\\'+name)
            else:
                raise('chyba')
                
                
                
    for file_name in file_names_tumor:
        
        mask_name=file_name.replace('\\data\\','\\mask\\')
        
        mask_name=mask_name[:-4] + '_mask.tif'
        
        dil_mask_name=mask_name.replace('\\mask\\','\\mask_dil_lvl3\\')
        
        
        mask0=imread_gdal_mask(mask_name,lvl)>0
        
#        cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(16,16))
        s=np.ones((16,16))>0
        mask=binary_dilation(mask0,s)
        
        write_gdal_mask(mask,dil_mask_name)        
        
        
        
        
        
                
    
Пример #59
0
        for i in range(sz128_iso[0]):
            print i
            out[i, 32:, 32:] = imread(Dl + fin + '/%04d.png' % (4 * i + 1),
                                      'L')[::2, ::2]
        writeh5(Do, 'main', out)
    elif opt == '1.1':  # cc
        # for visualization (hp03): python -i ng_pair_128nm.py cell_yl_den_cc_bv.h5
        from skimage.measure import label
        from scipy.ndimage.morphology import binary_opening, binary_dilation
        dopt = int(sys.argv[2])
        numI = int(sys.argv[3])
        numD = int(sys.argv[4])
        Do = D0 + 'cell128nm/'
        fn = 'cell_yl_den'
        seg = np.array(h5py.File(Do + fn + '.h5')['main'])

        suf = '_bv'
        seg_db = np.array(h5py.File(Do + 'cell_bv.h5')['main'])
        mm = seg_db > 0 if numD == 0 else binary_dilation(seg_db > 0,
                                                          iterations=numD)
        seg[mm] = 0
        if dopt == 1:  # cell mask from db
            seg_db = np.array(h5py.File(Do + 'cell_daniel.h5')['main'])
            mm = seg_db > 0 if numD == 0 else binary_dilation(seg_db > 0,
                                                              iterations=numD)
            seg[mm] = 0
            suf += '_db'
        writeh5(
            Do + fn + '_cc%s_open%d_dl%d.h5' % (suf, numI, numD), 'main',
            relabel(label(binary_opening(seg, iterations=numI)), do_sort=True))
def apply_gradients_dilation(x):
        if len(x.shape)==5:
            shape_5=True
            x=np.reshape(x, newshape=[x.shape[0], x.shape[1], x.shape[2], x.shape[3]])
        print ("applying gradients and dilation for every element from 0 to : ",x.shape[0])
        for i in range(x.shape[0]):

            volume = np.gradient(x[i])
            #print("248", x[i].shape)
            #print(volume[0].shape)
            #print("min: ", np.min(volume[0]))
            #print("max: ", np.max(volume[0]))
            #print("counting occurrencies in volume[0]")
            #unique, counts = np.unique(volume[0], return_counts=True)
            #print(dict(zip(unique, counts)))
            #print("NOW THEY SHOULD BECOME EITHER 0 OR 1")
            for k in np.nditer(volume[0], op_flags=['readwrite']):
                if (k[...]!=0.0):
                    k[...]=1
            # print("counting occurrencies in volume[0]")
            # unique, counts = np.unique(volume[0], return_counts=True)
            # print(dict(zip(unique, counts)))

            #print(volume[1].shape)
            # print("min: ", np.min(volume[1]))
            # print("max: ", np.max(volume[1]))
            # print("counting occurrencies in volume[1]")
            # unique, counts = np.unique(volume[1], return_counts=True)
            # print(dict(zip(unique, counts)))
            # print("NOW THEY SHOULD BECOME EITHER 0 OR 1")
            for k in np.nditer(volume[1], op_flags=['readwrite']):
                if (k[...] != 0.0):
                    k[...] = 1
            # print("counting occurrencies in volume[1]")
            # unique, counts = np.unique(volume[1], return_counts=True)
            # print(dict(zip(unique, counts)))

            #print(volume[2].shape)
            # print("min: ", np.min(volume[2]))
            # print("max: ", np.max(volume[2]))
            # print("counting occurrencies in volume[2]")
            # unique, counts = np.unique(volume[2], return_counts=True)
            # print(dict(zip(unique, counts)))
            # print("NOW THEY SHOULD BECOME EITHER 0 OR 1")
            # print("counting occurrencies in volume[2]")
            # unique, counts = np.unique(volume[2], return_counts=True)
            # print(dict(zip(unique, counts)))

            volume = volume[0] + volume[1]
            # print("counting occurrencies in gradient sum")
            # unique, counts = np.unique(volume, return_counts=True)
            # print(dict(zip(unique, counts)))
            volume=np.clip(volume, a_min=0, a_max=1)
            # print("counting occurrencies in gradient sum CLIPPED")
            # unique, counts = np.unique(volume, return_counts=True)
            # print(dict(zip(unique, counts)))
            _, y= volume.nonzero()
            # print("sum gradients, min: ", np.min(volume))
            # print("sum gradients, max: ", np.max(volume))
            # print("x length: ", len(y))

            dilated_volume = binary_dilation(volume).astype(volume.dtype)
            #print("dilated min: ", np.min(dilated_volume))
            #print("dilated max: ", np.max(dilated_volume))
            #print("counting occurrencies in dilated vol")
            #unique, counts = np.unique(dilated_volume, return_counts=True)
            #print(dict(zip(unique, counts)))

            #print(x[i].shape)
            x[i, :, :, :]=dilated_volume
        if shape_5:
            x=np.reshape(x, newshape=[x.shape[0], x.shape[1], x.shape[2], x.shape[3], 1])

        print("DONE\n\n\n: ", x.shape)
        print("min: ", np.min(x))
        print("max: ", np.max(x))
        print("counting occurrencies before returning x")
        unique, counts = np.unique(x, return_counts=True)
        print(dict(zip(unique, counts)))

        return x