Exemple #1
0
 def fast_odf(self, s):
     odf = np.zeros(self.odfn)
     Eq = np.zeros((self.sz, self.sz, self.sz))
     #for i in range(self.dn):
     #    Eq[self.q[i][0],self.q[i][1],self.q[i][2]]+=s[i]/s[0]
     Eq[self.q[:, 0], self.q[:, 1], self.q[:, 2]] = s[:] / np.float(s[0])
     #self.Eqs.append(Eq)
     if self.operator == 'laplacian':
         LEq = laplace(Eq)
         sign = -1
     if self.operator == 'laplap':
         LEq = laplace(laplace(Eq))
         sign = 1
     if self.operator == 'signal':
         LEq = Eq
         sign = 1
     #LEs=map_coordinates(LEq,self.Ys.T,order=1)
     #"""
     LEs = np.zeros(self.Ysn)
     strides = np.array(LEq.strides, 'i8')
     map_coordinates_trilinear_iso(LEq, self.Ys, strides, self.Ysn, LEs)
     #LEs=map_coordinates(LEq,self.zoom*self.Ys,order=1)
     LEs = LEs.reshape(self.odfn, self.radiusn)
     LEs = LEs * self.radius
     #LEs=LEs*self.radius*self.zoom
     LEsum = np.sum(LEs, axis=1)
     #This is what the following code is doing
     #for i in xrange(self.odfn):
     #    odf[i]=np.sum(LEsum[self.eqinds[i]])/self.eqinds_len[i]
     #odf2=odf.copy()
     LES = LEsum[self.eqinds_com]
     sum_on_blocks_1d(LES, self.eqinds_len, odf, self.odfn)
     odf = odf / self.eqinds_len
     return self.angular_weighting(sign * odf)
Exemple #2
0
 def fast_odf(self,s):
     odf = np.zeros(self.odfn)
     Eq=np.zeros((self.sz,self.sz,self.sz))
     #for i in range(self.dn):
     #    Eq[self.q[i][0],self.q[i][1],self.q[i][2]]+=s[i]/s[0]
     Eq[self.q[:,0],self.q[:,1],self.q[:,2]]=s[:]/np.float(s[0])
     #self.Eqs.append(Eq)
     if  self.operator=='laplacian':
         LEq=laplace(Eq)
         sign=-1
     if self.operator=='laplap':
         LEq=laplace(laplace(Eq))
         sign=1
     if  self.operator=='signal':
         LEq=Eq
         sign=1
     #LEs=map_coordinates(LEq,self.Ys.T,order=1)
     #"""
     LEs=np.zeros(self.Ysn)
     strides=np.array(LEq.strides,'i8')
     map_coordinates_trilinear_iso(LEq,self.Ys,
                                   strides,self.Ysn, LEs)
     #LEs=map_coordinates(LEq,self.zoom*self.Ys,order=1)
     LEs=LEs.reshape(self.odfn,self.radiusn)
     LEs=LEs*self.radius
     #LEs=LEs*self.radius*self.zoom
     LEsum=np.sum(LEs,axis=1)
     #This is what the following code is doing
     #for i in xrange(self.odfn):
     #    odf[i]=np.sum(LEsum[self.eqinds[i]])/self.eqinds_len[i]
     #odf2=odf.copy()
     LES=LEsum[self.eqinds_com]
     sum_on_blocks_1d(LES,self.eqinds_len,odf,self.odfn)
     odf=odf/self.eqinds_len
     return self.angular_weighting(sign*odf)
def processing():
    """processing the digital images"""
    # original image, cat
    cat = folder + 'cat.jpg'
    image = cv2.imread(cat, 0)
    frequency(image, output + 'cat_frequency.jpg')
    image_padded = padding(image, output + 'cat_padded.jpg')
    filter_derivative(image_padded, output + 'cat_derivative.jpg')
    # overwrite for the quality
    image_derivative = ned.laplace(image)
    imageio.imwrite(output + 'cat_derivative.jpg', image_derivative)
    image_sharpened = image - image_derivative
    imageio.imwrite(output + 'cat_sharpened.jpg', image_sharpened)

    # original image, triangle
    triangle = folder + 'triangle.jpg'
    image = cv2.imread(triangle, 0)
    frequency(image, output + 'triangle_frequency.jpg')
    image_padded = padding(image, output + 'triangle_padded.jpg')
    filter_derivative(image_padded, output + 'triangle_derivative.jpg')
    # overwrite for the quality
    image_derivative = ned.laplace(image)
    imageio.imwrite(output + 'triangle_derivative.jpg', image_derivative)
    image_sharpened = image - image_derivative
    imageio.imwrite(output + 'triangle_sharpened.jpg', image_sharpened)
    return
Exemple #4
0
 def fast_odf(self,s):
     odf = np.zeros(self.odfn)        
     Eq=np.zeros((self.sz,self.sz,self.sz))
     #for i in range(self.dn):            
     #    Eq[self.q[i][0],self.q[i][1],self.q[i][2]]+=s[i]/s[0]
     Eq[self.q[:,0],self.q[:,1],self.q[:,2]]=s[:]/s[0]
         
     if  self.operator=='2laplacian':       
         LEq=self.eit_operator(Eq,2)
         sign=-1
     if  self.operator=='laplacian':
         LEq=laplace(Eq)
         sign=-1
     if self.operator=='laplap':
         LEq=laplace(laplace(Eq))
         sign=1
     if  self.operator=='signal':
         LEq=Eq
         sign=1
                        
     LEs=map_coordinates(LEq,self.Ys,order=1)        
     LEs=LEs.reshape(self.odfn,self.radiusn)
     LEs=LEs*self.radius
     LEsum=np.sum(LEs,axis=1)
     #This is what the following code is doing        
     #for i in xrange(self.odfn):
     #    odf[i]=np.sum(LEsum[self.eqinds[i]])/self.eqinds_len[i]        
     #odf2=odf.copy()
     LES=LEsum[self.eqinds_com]        
     sum_on_blocks_1d(LES,self.eqinds_len,odf,self.odfn)
     odf=odf/self.eqinds_len
     
     
     return sign*odf
Exemple #5
0
def Solve_diff_eq_RK4(stimulus,lamda,t0,h,D,t_N):
    """
    Finds a solution to the linear and spatially discrete diffusion equation:
    
                        df/dt = D*K(f) - s*delta(t-t0)  
                        
    using the 4th order Runge-Kutta method (ignoring leakage currents). The 
    stimulus is inject at t0 and then the defined lamda value permits certain
    diffusion behaviour to occur iteratively over this initial stimuli. The
    result is a diffusion of the maximum and minimum values across the stimuli
    to obtain a global value of luminance extremities through local interactions.   
    
    Parameters
    ---------------
    stimulus : array_like   input stimuli [x,y] "photo receptor activity elicited by
                            some real-world luminance distribution"
    lamda : int             a value between +/- inf
    t0 : int                point of stimulus "injection"
    h : int                 Runga-kutta step size
    N : int                 stimulus array size
    D : int                 diffusion coefficient weights rate of diffusion [0<D<1]
    
    Returns
    ----------------
    f : array_like          computed diffused array
    
    """
    f = np.zeros((t_N+1,stimulus.shape[0],stimulus.shape[1])) #[time, equal shape space dimension]
    t = np.zeros(t_N+1)
    
    if lamda ==0:
        """    Linearity  Global Activity Preserved   """
        for n in np.arange(0,t_N,h):
            k1 = D*flt.laplace(f[t[n],:,:]) + stimulus*Dirac_delta_test(t[n]-t0)
            k1 = k1.astype(np.float64)
            k2 = D*flt.laplace(f[t[n]+(h/2.),:,:]+(0.5*h*k1)) + stimulus*Dirac_delta_test((t[n]+(0.5*h))- t0)
            k2 = k2.astype(np.float64)
            k3 = D*flt.laplace(f[t[n]+(h/2.),:,:]+(0.5*h*k2)) + stimulus*Dirac_delta_test((t[n]+(0.5*h))-t0)
            k3 = k3.astype(np.float64)
            k4 = D*flt.laplace(f[t[n]+h,:,:]+(h*k3)) + stimulus*Dirac_delta_test((t[n]+h)-t0)
            k4 = k4.astype(np.float64)
            f[n+1,:,:] = f[n,:,:] + (h/6.) * (k1 + 2.*k2 + 2.*k3 + k4)
            t[n+1] = t[n] + h
        return f
    
    else:
        """    Non-Linearity   (max/min syncytium) Global Activity Not Preserved   """
        for n in np.arange(0,t_N):
            k1 = D*Diffusion_operator(lamda,f[t[n],:,:],t[n]) + stimulus*Dirac_delta_test(t[n]-t0)
            k1 = k1.astype(np.float64)
            k2 = D*Diffusion_operator(lamda,(f[t[n]+(h/2.),:,:]+(0.5*h*k1)),t[n]) + stimulus*Dirac_delta_test((t[n]+(0.5*h))- t0)
            k2 = k2.astype(np.float64)
            k3 = D*Diffusion_operator(lamda,(f[t[n]+(h/2.),:,:]+(0.5*h*k2)),t[n]) + stimulus*Dirac_delta_test((t[n]+(0.5*h))-t0)
            k3 = k3.astype(np.float64)
            k4 = D*Diffusion_operator(lamda,(f[t[n]+h,:,:]+(h*k3)),t[n]) + stimulus*Dirac_delta_test((t[n]+h)-t0)
            k4 = k4.astype(np.float64)
            f[n+1,:,:] = f[n,:,:] + (h/6.) * (k1 + 2.*k2 + 2.*k3 + k4)
            t[n+1] = t[n] + h   
        return f
def fusion(im1,im2):
    
    sigma_r = 5
    average_filter_size=31
    r_1=45
    r_2=7
    eps_1=0.3
    eps_2=10e-6

    if im1.max()>1:
        im1=im1/255
    if im2.max()>1:
        im2=im2/255
    
    im1_blue, im1_green, im1_red = cv2.split(im1)
    im2_blue, im2_green, im2_red = cv2.split(im2)
    
    base_layer1 = uniform_filter(im1, mode='reflect',size=average_filter_size)
    b1_blue, b1_green, b1_red = cv2.split(base_layer1)
    
    base_layer2 = uniform_filter(im2, mode='reflect',size=average_filter_size)
    b2_blue, b2_green, b2_red = cv2.split(base_layer2)
    
    detail_layer1 = im1 - base_layer1
    d1_blue, d1_green, d1_red = cv2.split(detail_layer1)
    
    detail_layer2 = im2 - base_layer2
    d2_blue, d2_green, d2_red = cv2.split(detail_layer2)
    
    
    saliency1 = gaussian_filter(abs(laplace(im1_blue+im1_green+im1_red,mode='reflect')),sigma_r,mode='reflect')
    saliency2 = gaussian_filter(abs(laplace(im2_blue+im2_green+im2_red,mode='reflect')),sigma_r,mode='reflect')
    mask = np.float32(np.argmax([saliency1, saliency2], axis=0))
    
    im1=np.float32(im1)
    im2=np.float32(im2)
    
    g1r1 = guided_filter(1 - mask, im1[:,:,0], r_1, eps_1)+guided_filter(1 - mask, im1[:,:,1], r_1, eps_1)+guided_filter(1 - mask, im1[:,:,2], r_1, eps_1)
    
    g2r1 = guided_filter(mask, im2[:,:,0], r_1, eps_1)+guided_filter(mask, im2[:,:,1], r_1, eps_1)+guided_filter(mask, im2[:,:,2], r_1, eps_1)
    g1r2 = guided_filter(1 - mask, im1[:,:,0], r_2, eps_2)+ guided_filter(1 - mask, im1[:,:,1], r_2, eps_2)+ guided_filter(1 - mask, im1[:,:,2], r_2, eps_2)
    g2r2 =  guided_filter(mask, im2[:,:,0], r_2, eps_2)+ guided_filter(1 - mask, im2[:,:,1], r_2, eps_2)+ guided_filter(1 - mask, im2[:,:,2], r_2, eps_2)

    
    fused_base1 = np.float32((b1_blue * (g1r1) + b2_blue * (g2r1))/((g1r1+g2r1)))          
    fused_detail1 = np.float32((d1_blue * (g1r2) + d2_blue * (g2r2))/((g1r2+g2r2)))  
    fused_base2 = np.float32((b1_green * g1r1 + b2_green * g2r1)/((g1r1+g2r1)))   
    fused_detail2 = np.float32((d1_green * (g1r2) + d2_green * (g2r2))/((g1r2+g2r2)))    
    fused_base3 = np.float32((b1_red * (g1r1) + b2_red * (g2r1))/((g1r1+g2r1)))
    fused_detail3 = np.float32((d1_red * (g1r2) + d2_red * (g2r2))/((g1r2+g2r2)))
        
        
    B1=np.float32(fused_base1+fused_detail1)
    B2=np.float32(fused_base2+fused_detail2)
    B3=np.float32(fused_base3+fused_detail3)
    
    fusion1=np.float32(cv2.merge((B1, B2, B3)))
    fusion1=fusion1/fusion1.max()
    return fusion1
Exemple #7
0
def _inpaint_biharmonic_single_channel(mask, out, limits):
    # Initialize sparse matrices
    matrix_unknown = sparse.lil_matrix((np.sum(mask), out.size))
    matrix_known = sparse.lil_matrix((np.sum(mask), out.size))

    # Find indexes of masked points in flatten array
    mask_i = np.ravel_multi_index(np.where(mask), mask.shape)

    # Find masked points and prepare them to be easily enumerate over
    mask_pts = np.array(np.where(mask)).T

    # Iterate over masked points
    for mask_pt_n, mask_pt_idx in enumerate(mask_pts):
        # Get bounded neighborhood of selected radius
        b_lo, b_hi = _get_neighborhood(mask_pt_idx, 2, out.shape)

        # Create biharmonic coefficients ndarray
        neigh_coef = np.zeros(b_hi - b_lo)
        neigh_coef[tuple(mask_pt_idx - b_lo)] = 1
        neigh_coef = laplace(laplace(neigh_coef))

        # Iterate over masked point's neighborhood
        it_inner = np.nditer(neigh_coef, flags=['multi_index'])
        for coef in it_inner:
            if coef == 0:
                continue
            tmp_pt_idx = np.add(b_lo, it_inner.multi_index)
            tmp_pt_i = np.ravel_multi_index(tmp_pt_idx, mask.shape)

            if mask[tuple(tmp_pt_idx)]:
                matrix_unknown[mask_pt_n, tmp_pt_i] = coef
            else:
                matrix_known[mask_pt_n, tmp_pt_i] = coef

    # Prepare diagonal matrix
    flat_diag_image = sparse.dia_matrix((out.flatten(), np.array([0])),
                                        shape=(out.size, out.size))

    # Calculate right hand side as a sum of known matrix's columns
    matrix_known = matrix_known.tocsr()
    rhs = -(matrix_known * flat_diag_image).sum(axis=1)

    # Solve linear system for masked points
    matrix_unknown = matrix_unknown[:, mask_i]
    matrix_unknown = sparse.csr_matrix(matrix_unknown)
    result = spsolve(matrix_unknown, rhs)

    # Handle enormous values
    result = np.clip(result, *limits)

    result = result.ravel()

    # Substitute masked points with inpainted versions
    for mask_pt_n, mask_pt_idx in enumerate(mask_pts):
        out[tuple(mask_pt_idx)] = result[mask_pt_n]

    return out
Exemple #8
0
def _inpaint_biharmonic_single_channel(mask, out, limits):
    # Initialize sparse matrices
    matrix_unknown = sparse.lil_matrix((np.sum(mask), out.size))
    matrix_known = sparse.lil_matrix((np.sum(mask), out.size))

    # Find indexes of masked points in flatten array
    mask_i = np.ravel_multi_index(np.where(mask), mask.shape)

    # Find masked points and prepare them to be easily enumerate over
    mask_pts = np.array(np.where(mask)).T

    # Iterate over masked points
    for mask_pt_n, mask_pt_idx in enumerate(mask_pts):
        # Get bounded neighborhood of selected radius
        b_lo, b_hi = _get_neighborhood(mask_pt_idx, 2, out.shape)

        # Create biharmonic coefficients ndarray
        neigh_coef = np.zeros(b_hi - b_lo)
        neigh_coef[tuple(mask_pt_idx - b_lo)] = 1
        neigh_coef = laplace(laplace(neigh_coef))

        # Iterate over masked point's neighborhood
        it_inner = np.nditer(neigh_coef, flags=['multi_index'])
        for coef in it_inner:
            if coef == 0:
                continue
            tmp_pt_idx = np.add(b_lo, it_inner.multi_index)
            tmp_pt_i = np.ravel_multi_index(tmp_pt_idx, mask.shape)

            if mask[tuple(tmp_pt_idx)]:
                matrix_unknown[mask_pt_n, tmp_pt_i] = coef
            else:
                matrix_known[mask_pt_n, tmp_pt_i] = coef

    # Prepare diagonal matrix
    flat_diag_image = sparse.dia_matrix((out.flatten(), np.array([0])),
                                        shape=(out.size, out.size))

    # Calculate right hand side as a sum of known matrix's columns
    matrix_known = matrix_known.tocsr()
    rhs = -(matrix_known * flat_diag_image).sum(axis=1)

    # Solve linear system for masked points
    matrix_unknown = matrix_unknown[:, mask_i]
    matrix_unknown = sparse.csr_matrix(matrix_unknown)
    result = spsolve(matrix_unknown, rhs)

    # Handle enormous values
    result = np.clip(result, *limits)

    result = result.ravel()

    # Substitute masked points with inpainted versions
    for mask_pt_n, mask_pt_idx in enumerate(mask_pts):
        out[tuple(mask_pt_idx)] = result[mask_pt_n]

    return out
Exemple #9
0
def cplxlaplacian_filter(real_input, imag_input, mode_='reflect', cval_=0.0):
    """CPLXFILTER apply scipy's laplace filter to complex 3D image

    filtered_image = cplxlaplacian_filter(realimg, imagimg)

    :param mode: {'reflect', 'constant', 'nearest', 'mirror', 'wrap'},
    optional. The mode parameter determines how the array borders are handled,
    where cval is the value when mode is equal to 'constant'. Default is
    'reflect'
       :param cval: [optional] Value to fill past edges of input if mode is
    'constant'. Default is 0.0

    :return filtered_image: complex 3D array of gaussian laplace filtered
    image,
    scipy.ndimage.filters.laplace

    scipy.ndimage.filters.laplace(input, output=None, mode='reflect',
    cval=0.0)[source] N-dimensional Laplace filter based on approximate second
    derivatives.

    Parameters:
    input : array_like
    Input array to filter.
    output : array, optional
    The output parameter passes an array in which to store the filter output.
    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional

    The mode parameter determines how the array borders are handled, where cval
    is the value when mode is equal to 'constant'. Default is 'reflect' cval :
    scalar, optional Value to fill past edges of input if mode is
    'constant'. Default is 0.0

    """
    print "Complex Gaussian_laplace filter  ", " mode ", mode_
    if real_input.ndim == 3:
        real_img = laplace(real_input, mode=mode_, cval=cval_)
        imag_img = laplace(imag_input, mode=mode_, cval=cval_)
    else:
        real_img = np.empty_like(real_input, dtype=np.float32)
        imag_img = np.empty_like(real_input, dtype=np.float32)
        for echo in xrange(0, real_input.shape[4]):
            for acq in xrange(0, real_input.shape[3]):
                real_img[:, :, :, acq, echo] = laplace(real_input[:, :, :, acq,
                                                                  echo],
                                                       mode=mode_,
                                                       cval=cval_)
                imag_img[:, :, :, acq, echo] = laplace(imag_input[:, :, :, acq,
                                                                  echo],
                                                       mode=mode_,
                                                       cval=cval_)
    filtered_image = np.empty_like(real_input, dtype=np.complex64)
    filtered_image.real = real_img
    filtered_image.imag = imag_img
    return filtered_image
Exemple #10
0
def gvf(f,
        mu=0.05,
        iterations=30,
        anisotropic=False,
        ignore_second_term=False):
    # Gradient vector flow
    # Translated from https://github.com/smistad/3D-Gradient-Vector-Flow-for-Matlab
    f = (f - f.min()) / (f.max() - f.min())
    f = enforce_mirror_boundary(
        f)  # Enforce the mirror conditions on the boundary

    dx, dy, dz = np.gradient(f)  # Initialse with normal gradients
    '''
    Initialise the GVF vectors following S3 in
    Yu, Zeyun, and Chandrajit Bajaj. 
    "A segmentation-free approach for skeletonization of gray-scale images via anisotropic vector diffusion." 
    CVPR, 2004. CVPR 2004. 
    It only uses one of the surronding neighbours with the lowest intensity
    '''
    # dx, dy, dz = distgradient(f)

    magsq = dx**2 + dy**2 + dz**2

    # Set up the initial vector field
    u = dx.copy()
    v = dy.copy()
    w = dz.copy()

    bar = progressbar.ProgressBar(max_value=iterations)
    for i in range(iterations):
        bar.update(i + 1)

        # The boundary might not matter here
        # u = enforce_mirror_boundary(u)
        # v = enforce_mirror_boundary(v)
        # w = enforce_mirror_boundary(w)

        # Update the vector field
        if anisotropic:
            G = g_all(u, v, w)
            u += mu / 6. * div(np.sum(G * d(u), axis=0))
            v += mu / 6. * div(np.sum(G * d(v), axis=0))
            w += mu / 6. * div(np.sum(G * d(w), axis=0))
        else:
            u += mu * 6 * laplace(u)
            v += mu * 6 * laplace(v)
            w += mu * 6 * laplace(w)

        if not ignore_second_term:
            u -= (u - dx) * magsq
            v -= (v - dy) * magsq
            w -= (w - dz) * magsq

    return np.stack((u, v, w), axis=0)
Exemple #11
0
def _get_neigh_coef(shape, center, dtype=float):
    # Create biharmonic coefficients ndarray
    neigh_coef = np.zeros(shape, dtype=dtype)
    neigh_coef[center] = 1
    neigh_coef = laplace(laplace(neigh_coef))

    # extract non-zero locations and values
    coef_idx = np.where(neigh_coef)
    coef_vals = neigh_coef[coef_idx]

    coef_idx = np.stack(coef_idx, axis=0)
    return neigh_coef, coef_idx, coef_vals
Exemple #12
0
def harris(im):
    '''
    gauss1d_k = numpy.array(gen_gauss1d_k([-1, 0, 1], 1))
    res1 = numpy.zeros(im.shape, dtype=numpy.uint8)
    for i in range(im.shape[0]):
        for j in range(im.shape[1]):
            if j >= (len(gauss1d_k)//2) and j <= (im.shape[1] - len(gauss1d_k)//2 - 1):#Skipping the border pixels
                res1[i][j] = int(sum(im[i][j-len(gauss1d_k)//2:j+1+len(gauss1d_k)//2]*gauss1d_k))
            else: # copying the border pixels of the original image as it is
                res1[i][j] = im[i][j]
    '''

    Gim = gaussian_filter(im, 1.5)
    print Gim
    derx = numpy.array([[-1, 0, 1], [-1, 0, 1],
                        [-1, 0, 1]])  #derivative filter in X direction
    dery = derx.transpose()  # derivative filter on y component
    Ix = cv2.filter2D(im, -1, derx)  # Derivative of X component of Image
    Iy = cv2.filter2D(im, -1, dery)
    Ixy = cv2.filter2D(im, -1, dery)
    Lx = laplace(Ix)
    Ly = laplace(Iy)
    Lxy = laplace(Ixy)
    alpha = 0.04
    R = numpy.empty(im.shape)
    res = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
    for i in range(im.shape[0]):
        for j in range(im.shape[1]):
            h2 = numpy.matrix([[Lx[i, j] * Lx[i, j], Lxy[i, j]],
                               [Lxy[i, j], Ly[i, j] * Ly[i, j]]])
            R[i, j] = numpy.linalg.det(h2) - (alpha * numpy.trace(h2))

    th = numpy.max(R * 0.99)
    for i in range(im.shape[0]):
        for j in range(im.shape[1]):
            if R[i, j] > th:
                res[i, j] = [0, 0, 255]

    cv2.imshow("Gim", Gim)
    cv2.waitKey(0)
    cv2.imshow("Ix", Ix)
    cv2.waitKey(0)
    cv2.imshow("Iy", Iy)
    cv2.waitKey(0)
    cv2.imshow("Lx", Lx)
    cv2.waitKey(0)
    cv2.imshow("Ly", Ly)
    cv2.waitKey(0)
    cv2.imshow("Lxy", Lxy)
    cv2.waitKey(0)
    cv2.imshow("res", res)
    cv2.waitKey(0)
Exemple #13
0
def create_GVF(f, mu, count, dt):
    u = np.zeros_like(f)
    v = np.zeros_like(f)
    fy, fx = np.gradient(f)
    b = fx**2 + fy**2
    c1 = b * fx
    c2 = b * fy
    for i in range(count):
        Delta_u = laplace(u, mode="constant")
        Delta_v = laplace(v, mode="constant")
        u = (1 - b * dt) * u + (mu * Delta_u + c1) * dt
        v = (1 - b * dt) * v + (mu * Delta_v + c2) * dt
    return u, v
Exemple #14
0
def generate_stencials():
    stencils = []
    for i in range(5):
        for j in range(5):
            A = np.zeros((5, 5))
            A[i, j] = 1
            S = laplace(laplace(A))
            x_range = np.array([i - 2, i + 3]).clip(0, 5)
            y_range = np.array([j - 2, j + 3]).clip(0, 5)
            S = S[x_range[0]:x_range[1], y_range[0]:y_range[1]]
            stencils.append(S)

    return stencils
Exemple #15
0
    def _calculate_media(self, check_start=40, check_interval_growth=5):
        check_interval = check_interval_growth
        limiting = max(self.spec.uptake_rate, self.spec.diffusion_constant)
        dt = 1.0/(4*limiting)

        cells = self._narrow_cells()
        boundary = self._make_boundary_layer(cells)

        media = np.ones_like(cells, np.float32)*self.spec.media_concentration
        # guess a linear solution for faster convergence
        heights = utils.compute_heights(np.logical_not(boundary))
        for col, height in enumerate(heights):
            if height == 0: continue
            media[:height, col] = np.linspace(0, self.spec.media_concentration,
                                              height)
        media_next = np.empty_like(media)

        # def error_handler(type, flag):
        #     if type == "underflow": return
        #     np.seterr(all='warn')
        #     print "Floating point error (%s), with flag %s" % (type, flag)
        #     print dt, self.spec.diffusion_constant, self.spec.uptake_rate
        #     print self.spec.media_concentration
        #     from matplotlib import pyplot as plt
        #     plt.figure(); plt.imshow(media); plt.colorbar()
        #     plt.figure(); plt.imshow(media_next); plt.colorbar()
        #     plt.figure(); plt.imshow(boundary); plt.colorbar()
        #     plt.figure(); plt.imshow(cells); plt.colorbar()
        #     plt.show()
        #     print step
        #     raise Exception()

        # np.seterrcall(error_handler)
        # np.seterr(all='call')

        for step in range(self.spec.max_diffusion_iterations):
            laplace(media, output=media_next)
            media_next *= self.spec.diffusion_constant*dt
            media_next += media
            media_next[cells] *= 1 - self.spec.uptake_rate*dt
            media_next[boundary] = self.spec.media_concentration
            media, media_next = media_next, media

            if step >= check_start and step%check_interval == 0:
                media_next -= media
                np.abs(media_next, out=media_next)
                error = media_next.sum()/(dt*media_next.size)
                if error <= self.spec.diffusion_tol: break
                check_interval += check_interval_growth

        self.media = media
Exemple #16
0
def diffuse(cells=None, boundary=None, d=1.0, uptake=0.1, num_steps=1000):
    dt = 1.0/(4*d)
    u = 1.0*boundary

    # dx = dy = 1
    u_next = np.empty_like(u)
    storage = np.empty_like(u)
    for _ in range(num_steps):
        laplace(u, output=storage)
        u_next = u + d*dt*storage
        u_next[cells] *= 1 - uptake*dt
        u_next[boundary] = 1.0
        u, u_next = u_next, u

    return u
Exemple #17
0
def errfun(coords, src, target, reg):
	coords = np.array(coords)
	coords = coords.reshape((2,) + src.shape)

	mask  = gen_mask(src.shape)
	
	offset = coords + np.meshgrid(range(src.shape[0]), range(src.shape[1]), indexing='ij')

	warped = map_coordinates(src, offset)

	laplace_sum = np.sum(filters.laplace(coords[0])**2 + filters.laplace(coords[1])**2)

	match_sum = np.sum((warped - target)[mask]**2)

	return match_sum + reg*laplace_sum
Exemple #18
0
    def level_set_evolution(self):
        self.public_data()

        for i in range(self.iter_num):
            #  Neumann Boundary Condition
            self.neum_bound_cond()

            #  dirac
            dirac_phi = self.dirac()

            #  local binary fit
            f1, f2 = self.local_bin_fit()

            #  data force
            lbf = self.data_force(f1, f2)

            #  curvature central
            curv = self.curvature_central()

            # each item
            area_term = -dirac_phi * lbf
            len_term = self.nu * dirac_phi * curv

            laplace_operator_phi = filters.laplace(
                self.phi)  # self.phi laplace operator
            penalty = self.mu * (laplace_operator_phi - curv)

            self.phi = self.phi + self.time_step * (area_term + penalty +
                                                    len_term)

        # binary phi and then return
        rtn_phi = np.uint8(self.phi > 0)

        return rtn_phi * 255
def get_sharpness(img, sigma=10):

    blurred = gaussian_filter(img, sigma)
    #sharp = np.absolute(img - blurred)
    #TAKE THE LOG (laplacian of a guassian) INSTEAD
    sharp = np.absolute(laplace(blurred))
    return sharp
Exemple #20
0
def scale_space_transform(image, sigmas):
    from scipy.ndimage.filters import gaussian_filter, gaussian_laplace, laplace

    size = np.array(image.shape)
    spacing = np.array(image.voxelsize)
    scale_space = np.zeros((len(sigmas), size[0], size[1], size[2]),
                           dtype=float)

    for i in xrange(len(sigmas)):
        print "Sigma : ", np.exp(spacing * sigmas[i])
        if i == 0:
            previous_gaussian_img = gaussian_filter(image,
                                                    sigma=np.exp(spacing *
                                                                 sigmas[i]),
                                                    order=0)
        else:
            gaussian_img = gaussian_filter(np.array(image, np.float64),
                                           sigma=np.exp(spacing * sigmas[i]),
                                           order=0)

            laplace_img = laplace(gaussian_img)
            scale_space[i, :, :, :] = laplace_img
            # scale_space[i, : , : , : ] = gaussian_img
            previous_gaussian_img = gaussian_img

    return scale_space
Exemple #21
0
def main(argv):

    try:
        file = argv[0]
    except:
        usage()
        sys.exit(1)

    g_name = 'unwrapPhase'
    g_name_out = 'unwrapPhase_laplace'

    print('calculate Laplace filter of {} based on approximate second derivatives.'.format(g_name))

    f = h5py.File(file, 'a')
    ds = f[g_name]
    if g_name_out in f.keys():
        ds_out = f[g_name_out]
    else:
        ds_out = f.create_dataset(g_name_out, shape=ds.shape, dtype=np.float32, chunks=True, compression=None)
    print('write to dataset /{}'.format(g_name_out))

    num_ifgram = ds.shape[0]
    prog_bar = ptime.progressBar(maxValue=num_ifgram)
    for i in range(num_ifgram):
        unw = ds[i, :, :]
        ds_out[i, :, :] = laplace(unw)
        prog_bar.update(i+1, suffix='{}/{}'.format(i+1, num_ifgram))
    prog_bar.close()
    f.close()
    print('finished writing to {}'.format(file))
    return
Exemple #22
0
def load_and_getDelSq(path_base):
	i = 1
	max_DelSq = 0
	ind = 0
	arr = []
	while True:
		from_path = os.path.join(path_base, path_base + "-" + get_str_from_number(i) + ".jpg")
		# from_path = path_base + "/" + str(i) + ".png"
		try:
			img = plt.imread(from_path)
			arr.append(img)
			ds = np.sum(laplace(img[:, :, 0]) ** 2)
			if ds > max_DelSq:
				max_DelSq = ds
				ind = i
			i += 1
		except (FileNotFoundError, OSError):
			break
	if ind > 25:
		ind = 25
	arr = np.array(arr)
	##
	if arr.shape == (0,):
		print("IT'S GOING WRONG UP HERE THIS IS IT: ")
		print(path_base)
	##
	return arr, ind
Exemple #23
0
def _apply_laplacian(nx, ny, alpha, image):
    """ Apply isotropic Laplacian to an image.

    Parameters
    ----------
    nx, ny: int
        Dimensions of 2D image
    alpha: float
        Diffusion parameter
    image: ndarray, ndim=1
        Image as a 1D vector

    Returns
    -------
    output: ndarray, ndim=2
        Image after application of Laplacian
    """
    # reshape
    n = len(image)
    image = image.reshape((ny, nx))

    output = image - alpha * laplace(image)
    output = output.reshape(n)

    return output
Exemple #24
0
    def drlse_edge(self, phi):
        [vy, vx] = np.gradient(self.F)
        for k in range(self.iter):
            phi = self.applyNeumann(phi)
            [phi_y, phi_x] = np.gradient(phi)
            s = np.sqrt(np.square(phi_x) + np.square(phi_y))
            smallNumber = 1e-10
            Nx = phi_x / (s + smallNumber)
            Ny = phi_y / (s + smallNumber)
            curvature = self.div(Nx, Ny)
            if self.potential_function == 'single-well':
                distRegTerm = filters.laplace(phi, mode='wrap') - curvature
            elif self.potential_function == 'double-well':
                distRegTerm = self.distReg_p2(phi)
            else:
                print(
                    'Error: Wrong choice of potential function. Please input the string "single-well" or "double-well" in the drlse_edge function.'
                )
            diracPhi = self.Dirac(phi)
            areaTerm = diracPhi * self.F
            edgeTerm = diracPhi * (vx * Nx +
                                   vy * Ny) + diracPhi * self.F * curvature
            x = (self.F1 - self.M2) / (self.M1 - self.M2)
            leakproofterm = self.F * areaTerm * self.sigmoid(x)
            y = self.dt * (self.mu * distRegTerm + self.lamda * edgeTerm +
                           self.alpha * areaTerm - leakproofterm * self.alpha)
            #print(np.unique(y))
            phi = phi + self.dt * (
                self.mu * distRegTerm + self.lamda * edgeTerm +
                self.alpha * areaTerm - leakproofterm * self.alpha)

        return phi
Exemple #25
0
def medial(image):
    """Creates a medial axis transform image

    Args
    ----
    image: ndarray
        The image of which the medial axis is to be calculated.
        This should be a binary image.
    visualise: bool
        Option to visualise the medial axis transform.

    Returns
    -------
    out: ndarray
        A boolean image with the medial axis pixels
    """
    # Remove noise and make sure it's thresholded
    im = thresholds(image)

    # Calculate distance to all border pixels for each non-border pixel
    dist = distance_transform_edt(im)

    # Calculate laplacian
    lap = laplace(dist, mode="constant")

    # Select items that are maximums and therefore less than 0
    out = lap < 0

    # Mask all items that are outside the boundaries 
    # using the original image
    resultImage = np.logical_and(np.logical_not(out), im )

    return dist, lap, resultImage
Exemple #26
0
def main(argv):

    try:
        file = argv[0]
    except:
        usage()
        sys.exit(1)

    g_name = 'unwrapPhase'
    g_name_out = 'unwrapPhase_laplace'

    print('calculate Laplace filter of {} based on approximate second derivatives.'.format(g_name))

    f = h5py.File(file, 'a')
    ds = f[g_name]
    if g_name_out in f.keys():
        ds_out = f[g_name_out]
    else:
        ds_out = f.create_dataset(g_name_out, shape=ds.shape, dtype=np.float32, chunks=True, compression=None)
    print('write to dataset /{}'.format(g_name_out))

    num_ifgram = ds.shape[0]
    prog_bar = ptime.progressBar(maxValue=num_ifgram)
    for i in range(num_ifgram):
        unw = ds[i, :, :]
        ds_out[i, :, :] = laplace(unw)
        prog_bar.update(i+1, suffix='{}/{}'.format(i+1, num_ifgram))
    prog_bar.close()
    f.close()
    print('finished writing to {}'.format(file))
    return
 def test_laplacian(self):
     laplacian_ref = laplace(self.image)
     # Laplacian = div(grad)
     self.la.gradient(self.image)
     laplacian_ocl = self.la.divergence(self.la.d_gradient,
                                        return_to_host=True)
     self.compare(laplacian_ocl, laplacian_ref, 1e-6, "laplacian")
    def sciPyLaplacian(self, print_out=True):
        """tests the laplacian function against expected values"""
        passed = True
        a = self.a1  # shortcut
        test = [
            [(1, 1), np.asarray([0., 0.]).sum()],  # 11
            [(3, 3), np.asarray([-40., -4.]).sum()],  # 44
            [(4, 4), np.asarray([40., 4.]).sum()],  # 11
            [(3, 4), np.asarray([-40., 4.]).sum()],  # 41
            [(4, 3), np.asarray([40., -4.]).sum()],  # 14
            [(2, 3), np.asarray([0., -4.]).sum()]
        ]  # 34

        store = []
        for pos, act in test:  # iterate test values
            res = laplace(a, mode='wrap').view(Periodic_Lattice)[pos]
            passed *= (res == act).all()
            if print_out: store.append([pos, res, act])

        if print_out:
            utils.display('SciPy Laplacian',
                          outcome=passed,
                          details={
                              'checked vs. known values (Mathematica)': [
                                  'pos: {}, res: {}, act: {}'.format(*vals)
                                  for vals in store
                              ]
                          })

        return passed
def downsample_f(pop_size,mu,s,m,num_intervals,dims,out):
    output = np.zeros(tuple([num_intervals])+dims)
    if s > 0:
        interval = int(1/s)
    else:
        interval = 100
    num_gens = interval * num_intervals
    f = np.zeros(dims)
    f[tuple(np.array(f.shape)-1)] = 1/pop_size
    ## pre-allocate list of when reset happens
    reset_gens = []
    for i in range(num_gens):
        ## update frequencies:
        ## Wright-Fisher diffusion w/Stepping Stone migration
        df = mu*(1-2*f)-s*f*(1-f) \
        +m*laplace(f,mode='wrap')
        ## bounds allele frequencies
        p = np.clip(a= f + df ,a_min=0,a_max=1)
        ## genetic drift sampling
        new_f = np.random.binomial(pop_size,p)/pop_size
        ## Check for implicit mu simulation and extinct allele
        if mu==0 and np.all(new_f==0):
            ## if extinct, store previous freqs and reset
            reset_gens.append(i)
            ## Add 1 allele to single element of
            ## an artbitrarily sized array
            new_f[tuple(np.array(new_f.shape)-1)] = 1/pop_size
        ## Assign next frequencies
        f = new_f
        ## choose freqs every 1/s and before reset happens
        if (i + 1) % interval == 0:
            output[i//interval] = f
    # Write freqmat as .npy
    np.save(out,output)
Exemple #30
0
def drlse_region_interaction(phi_0, I, P, lmda, mu, alfa, beta, epsilon,
                             timestep, iters,
                             potentialFunction):  # Updated Level Set Function
    """

    :param phi_0: level set function to be updated by level set evolution
    :param I: the input image to be segmented
    :param P: the probability of being foreground, based on user interaction
    :param lmda: weight of the weighted length term
    :param mu: weight of distance regularization term
    :param alfa: weight of the weighted area term
    :param beta: weight of user interaction term
    :param epsilon: width of Dirac Delta function
    :param timestep: time step
    :param iters: number of iterations
    :param potentialFunction: choice of potential function in distance regularization term.
%              As mentioned in the above paper, two choices are provided: potentialFunction='single-well' or
%              potentialFunction='double-well', which correspond to the potential functions p1 (single-well)
%              and p2 (double-well), respectively.
    """
    phi = phi_0.copy()
    # lu = (P - 0.5)*(P - 0.5)*(P - )
    lu = np.log(P) - np.log(1.0 - P)
    # [vy, vx] = np.gradient(g)
    for k in range(iters):
        phi = NeumannBoundCond(phi)
        [phi_y, phi_x] = np.gradient(phi)
        s = np.sqrt(np.square(phi_x) + np.square(phi_y))
        smallNumber = 1e-10
        Nx = phi_x / (
            s + smallNumber
        )  # add a small positive number to avoid division by zero
        Ny = phi_y / (s + smallNumber)
        curvature = div(Nx, Ny)
        if potentialFunction == 'single-well':
            distRegTerm = filters.laplace(
                phi, mode='wrap'
            ) - curvature  # compute distance regularization term in equation (13) with the single-well potential p1.
        elif potentialFunction == 'double-well':
            distRegTerm = distReg_p2(
                phi
            )  # compute the distance regularization term in eqaution (13) with the double-well potential p2.
        else:
            print(
                'Error: Wrong choice of potential function. Please input the string "single-well" or "double-well" in the drlse_edge function.'
            )
        diracPhi = Dirac(phi, epsilon)
        # areaTerm = diracPhi * g  # balloon/pressure force
        # edgeTerm = diracPhi * (vx * Nx + vy * Ny) + diracPhi * g * curvature
        mean_in = I[phi > 0].mean()
        mean_out = I[phi < 0].mean()

        areaTerm = np.square(I - mean_in) - np.square(I - mean_out)
        areaTerm = diracPhi * (areaTerm / abs(areaTerm.max()))

        edgeTerm = diracPhi * curvature
        phi = phi + timestep * (mu * distRegTerm + lmda * edgeTerm -
                                alfa * areaTerm + beta * lu)
    return phi
Exemple #31
0
def compute_accelerations(current_acceleration, current_velocities,
                          current_positions, simulation_parameters, forcers,
                          time, edge_conditions, edge_value):
    # First Laplace * E
    filters.laplace(current_positions, current_acceleration, edge_conditions,
                    edge_value)
    current_acceleration *= simulation_parameters[0, :, :]

    # Then -B * V
    current_acceleration -= current_velocities * simulation_parameters[2, :, :]

    # Then forcers forces
    for forcer in forcers:
        current_acceleration[forcer.position_y,
                             forcer.position_x] += forcer(time)

    current_acceleration *= simulation_parameters[1, :, :]
Exemple #32
0
    def _remove_dup_laplace(self, data, mask, size=5):
        laplacian = np.multiply(laplace(data, mode='wrap'), mask)

        return generic_filter(laplacian,
                              self._local_max_laplace,
                              size=size,
                              mode='wrap',
                              extra_keywords={'size': size})
Exemple #33
0
 def fast_odf(self,s):
     odf = np.zeros(self.odfn)        
     Eq=np.zeros((self.sz,self.sz,self.sz))
     #for i in range(self.dn):
     #    Eq[self.q[i][0],self.q[i][1],self.q[i][2]]+=s[i]/s[0]
     Eq[self.q[:,0],self.q[:,1],self.q[:,2]]=s[:]/s[0]
     #self.Eqs.append(Eq)
         
     if  self.operator=='2laplacian':       
         LEq=self.eit_operator(Eq,2)            
         sign=-1
     if  self.operator=='laplacian':
         #ZEq=zoom(Eq,zoom=5,order=self.order,mode=self.mode,cval=0.0,prefilter=True)
         #self.ZEqs.append(ZEq)
         #ZLEq=laplace(ZEq)
         #self.ZLEqs.append(ZLEq)
         #LEq=zoom(ZLEq,zoom=.2,order=self.order,mode=self.mode,cval=0.0,prefilter=True)         
         #LEq=laplace(Eq)
         #if self.zoom>1:
         #    ZEq=zoom(Eq,zoom=self.zoom,order=self.order,mode=self.mode)
         #    LEq=laplace(ZEq)
         #else:
         LEq=laplace(Eq)
         sign=-1
     if self.operator=='laplap':
         LEq=laplace(laplace(Eq))
         sign=1
     if  self.operator=='signal':
         LEq=Eq
         sign=1
     
     LEs=map_coordinates(LEq,self.Ys,order=1)
     #LEs=map_coordinates(LEq,self.zoom*self.Ys,order=1)                
     LEs=LEs.reshape(self.odfn,self.radiusn)
     LEs=LEs*self.radius
     #LEs=LEs*self.radius*self.zoom
     LEsum=np.sum(LEs,axis=1)
     #This is what the following code is doing        
     #for i in xrange(self.odfn):
     #    odf[i]=np.sum(LEsum[self.eqinds[i]])/self.eqinds_len[i]        
     #odf2=odf.copy()
     LES=LEsum[self.eqinds_com]        
     sum_on_blocks_1d(LES,self.eqinds_len,odf,self.odfn)
     odf=odf/self.eqinds_len       
     
     return sign*odf
Exemple #34
0
    def fast_odf(self, s):
        odf = np.zeros(self.odfn)
        Eq = np.zeros((self.sz, self.sz, self.sz))
        #for i in range(self.dn):
        #    Eq[self.q[i][0],self.q[i][1],self.q[i][2]]+=s[i]/s[0]
        Eq[self.q[:, 0], self.q[:, 1], self.q[:, 2]] = s[:] / s[0]
        #self.Eqs.append(Eq)

        if self.operator == '2laplacian':
            LEq = self.eit_operator(Eq, 2)
            sign = -1
        if self.operator == 'laplacian':
            #ZEq=zoom(Eq,zoom=5,order=self.order,mode=self.mode,cval=0.0,prefilter=True)
            #self.ZEqs.append(ZEq)
            #ZLEq=laplace(ZEq)
            #self.ZLEqs.append(ZLEq)
            #LEq=zoom(ZLEq,zoom=.2,order=self.order,mode=self.mode,cval=0.0,prefilter=True)
            #LEq=laplace(Eq)
            #if self.zoom>1:
            #    ZEq=zoom(Eq,zoom=self.zoom,order=self.order,mode=self.mode)
            #    LEq=laplace(ZEq)
            #else:
            LEq = laplace(Eq)
            sign = -1
        if self.operator == 'laplap':
            LEq = laplace(laplace(Eq))
            sign = 1
        if self.operator == 'signal':
            LEq = Eq
            sign = 1

        LEs = map_coordinates(LEq, self.Ys, order=1)
        #LEs=map_coordinates(LEq,self.zoom*self.Ys,order=1)
        LEs = LEs.reshape(self.odfn, self.radiusn)
        LEs = LEs * self.radius
        #LEs=LEs*self.radius*self.zoom
        LEsum = np.sum(LEs, axis=1)
        #This is what the following code is doing
        #for i in xrange(self.odfn):
        #    odf[i]=np.sum(LEsum[self.eqinds[i]])/self.eqinds_len[i]
        #odf2=odf.copy()
        LES = LEsum[self.eqinds_com]
        sum_on_blocks_1d(LES, self.eqinds_len, odf, self.odfn)
        odf = odf / self.eqinds_len

        return sign * odf
Exemple #35
0
def get_focus_measure(src, kind):
    if not isinstance(src, ndarray):
        src = asarray(src)

    dst = laplace(src.astype(float))
    d = dst.flatten()
    d = percentile(d, 99)
    return d.mean()
Exemple #36
0
 def update(self):
     self.t += self.dt
     self.current, self.previous = 2 * self.current - self.previous + laplace(
         self.current) * (self.c * self.dt / self.ds)**2, self.current
     # b = 1.
     # self.current, self.previous = (2 * self.current - (1 - b / 2 * self.dt) * self.previous + laplace(
     #     self.current) * (self.c * self.dt / self.ds) ** 2) / (1 + b / 2 * self.dt), self.current
     self.boundary_conditions(self.current)
Exemple #37
0
def errfun(coords, src, target, reg):
    coords = np.array(coords)
    coords = coords.reshape((2, ) + src.shape)

    mask = gen_mask(src.shape)

    offset = coords + np.meshgrid(
        range(src.shape[0]), range(src.shape[1]), indexing='ij')

    warped = map_coordinates(src, offset)

    laplace_sum = np.sum(
        filters.laplace(coords[0])**2 + filters.laplace(coords[1])**2)

    match_sum = np.sum((warped - target)[mask]**2)

    return match_sum + reg * laplace_sum
Exemple #38
0
 def update(self):
     self.t += self.dt
     self.current, self.previous = 2 * self.current - self.previous + laplace(self.current) * (
         self.c * self.dt / self.ds) ** 2, self.current
     # b = 1.
     # self.current, self.previous = (2 * self.current - (1 - b / 2 * self.dt) * self.previous + laplace(
     #     self.current) * (self.c * self.dt / self.ds) ** 2) / (1 + b / 2 * self.dt), self.current
     self.boundary_conditions(self.current)
Exemple #39
0
def get_laplacian_img(img,pool_size,padding='SAME'):
	
   #Convert image to greyscale.
   img = tf.image.rgb_to_grayscale(img)
    
   pool = tf.nn.max_pool(img, ksize=[1,pool_size,pool_size,1], strides=[1,pool_size,pool_size,1], padding=padding)
    
   return np.squeeze(laplace(pool))
Exemple #40
0
def get_focus_measure(src, kind):
    if not isinstance(src, ndarray):
        src = asarray(src)

    dst = laplace(src.astype(float))
    d = dst.flatten()
    d = percentile(d, 99)
    return d.mean()
Exemple #41
0
def Laplacian2d(d, boxsize=None):
    l = sft.laplace(d)

    if boxsize == None:
        dl = 1.
    else:
        dl = boxsize / d.shape[0]

    return l / dl**2.
Exemple #42
0
 def distReg_p2(self, phi):
     [phi_y, phi_x] = np.gradient(phi)
     s = np.sqrt(np.square(phi_x) + np.square(phi_y))
     a = (s >= 0) & (s <= 1)
     b = (s > 1)
     ps = a * np.sin(2 * np.pi * s) / (2 * np.pi) + b * (s - 1)
     dps = ((ps != 0) * ps + (ps == 0)) / ((s != 0) * s + (s == 0))
     return self.div(dps * phi_x - phi_x, dps * phi_y -
                     phi_y) + filters.laplace(phi, mode='wrap')
Exemple #43
0
def errfun_derivs(coords, src, target, reg):
	coords = coords.reshape((2,) + src.shape)
	offset = coords + np.meshgrid(range(src.shape[0]), range(src.shape[1]), indexing='ij')
	warped = map_coordinates(src, offset)
	diff_im = warped - target
	grad_im = np.gradient(src)
	grad_warped = np.zeros((2,) + src.shape)
	laplacian = np.empty(coords.shape)
	laplacian[0] = filters.laplace(coords[0])
	laplacian[1] = filters.laplace(coords[1])
	laplacian_deriv = -11.3*laplacian

	mask  = gen_mask(src.shape)
	for i in range(2):
		grad_warped[i] = map_coordinates(grad_im[i], offset)

	match_deriv = 0.1*4*grad_warped*diff_im*mask

	return (match_deriv + laplacian_deriv*reg).flatten()
Exemple #44
0
def main(argv):

  try:
    file=argv[0]
  except:
    Usage();sys.exit(1)

  h5file=h5py.File(file,'r')
  kh5=h5file.keys()
#  if 'interferograms' in kh5:
  ifgramList=h5file['interferograms'].keys()
 #    Igram_with_minBase=ifgramList[0]
 #    for ifgram in  ifgramList:
 #      Baseline = float(h5file['interferograms'][ifgram].attrs['P_BASELINE_BOTTOM_HDR'])
#
#       if abs(Baseline) <float(h5file['interferograms'][Igram_with_minBase].attrs['P_BASELINE_BOTTOM_HDR']):
#            Igram_with_minBase=ifgram
#
#     print Igram_with_minBase
  try:
    OutName=argv[1]
  except:
    OutName='Laplacian.h5'

  h5laplace=h5py.File(OutName,'w')
  group=h5laplace.create_group('interferograms')
  print 'Calculating the Discrete Laplacian Transform'   
  for ifgram in  ifgramList:
     print ifgram
     dset=h5file['interferograms'][ifgram].get(ifgram)
     unw=dset[0:dset.shape[0],0:dset.shape[1]]
     Lunw=laplace(unw)
     g=group.create_group(ifgram)
     g.create_dataset(ifgram,data=Lunw,compression='gzip')
     for key, value in h5file['interferograms'][ifgram].attrs.iteritems():
          g.attrs[key] = value

  gm = h5laplace.create_group('mask')
  mask = h5file['mask'].get('mask')
  dset = gm.create_dataset('mask', data=mask, compression='gzip')

  try:
     
     meanCoherence = h5file['meanCoherence'].get('meanCoherence')
     gc = h5laplace.create_group('meanCoherence')
     dset = gc.create_dataset('meanCoherence', data=meanCoherence, compression='gzip')
  
  except:
     print ''   
  
  
   
  print 'DONE!'
Exemple #45
0
def diffuse_check(cells=None, boundary=None, d=1.0, uptake=0.1, tol=1e-4, max_steps=5000, 
                  check_start=40):
    check_interval = 10
    dt = 1.0/(4*d)
    u = 1.0*boundary

    # dx = dy = 1
    u_next = np.empty_like(u)
    storage = np.empty_like(u)
    for step in range(max_steps):
        laplace(u, output=storage)
        u_next = u + d*dt*storage
        u_next[cells] *= 1 - uptake*dt
        u_next[boundary] = 1.0
        u, u_next = u_next, u

        if step >= check_start and step%check_interval == 0:
            error = np.abs(u_next-u).sum()/(dt*u.size)
            if error <= tol: break
            check_interval += 5

    return u, step
Exemple #46
0
 def fast_odf(self,s):
     odf = np.zeros(self.odfn)
     Eq=np.zeros((self.sz,self.sz,self.sz))
     for i in xrange(self.dn):
         Eq[self.q[i][0],self.q[i][1],self.q[i][2]]+=s[i]/s[0]
     LEq=laplace(Eq)
     LEs=map_coordinates(LEq,self.Ys.T,order=1)
     LEs=LEs.reshape(self.odfn,self.radiusn)
     LEs=LEs*self.radius
     LEsum=np.sum(LEs,axis=1)
     for i in xrange(self.odfn):
         odf[i]=np.sum(LEsum[self.eqinds[i]])/self.eqinds_len[i]
     return -odf
Exemple #47
0
 def slow_odf(self,s):
     """ Calculate the orientation distribution function
     """
     odf = np.zeros(self.odfn)
     Eq=np.zeros((self.sz,self.sz,self.sz))
     for i in range(self.dn):
         Eq[self.q[i][0],self.q[i][1],self.q[i][2]]=s[i]/np.float(s[0])
     LEq=laplace(Eq)
     self.Eq=Eq
     self.LEq=LEq
     LEs=map_coordinates(LEq,self.Xs,order=1)
     le_to_odf(odf,LEs,self.radius,self.odfn,self.radiusn,self.equatorn)
     return odf
Exemple #48
0
def get_focus_measure(src, kind):
    if not isinstance(src, ndarray):
        src = asarray(src)

#     w, h = GetSize(pychron)
#     dst = CreateMat(w, h, CV_16SC1)
#     Laplace(pychron, dst)

#     d = asarray(dst).flatten()
    dst = laplace(src.astype(float))
    d = dst.flatten()
    d = percentile(d, 99)
    return d.mean()
Exemple #49
0
def GVF(f, mu, ITER):
    f = f.astype('float')
    # height, width = f.shape[0], f.shape[1]
    # fmin = f.min()
    # fmax = f.max()
    # f = (f - fmin)/ (fmax - fmin)
    f = BoundMirrorExpand(f)
    fy, fx = np.gradient(f)
    u = fx
    v = fy
    sqrMagf = fx*fx + fy*fy

    for i in range(ITER):
        print i
        u = BoundMirrorEnsure(u)
        v = BoundMirrorEnsure(v)

        u = u + mu*laplace(u) - sqrMagf*(u-fx)
        v = v + mu*laplace(v) - sqrMagf*(v-fy)

    u = BoundMirrorShrink(u)
    v = BoundMirrorShrink(v)

    return u, v
Exemple #50
0
def Diffusion_operator(lamda,f,t):  
    """
    Diffusion Operator - 2D Spatially Discrete Non-Linear Diffusion
    ---------------------------------------------------------------------------
    This describes the synaptic states of diffusion processes and correspond to 
    It "models different types of electrical synapses (gap junctions).
    The linear version, Kλ=0 , describes the exchange of both polarizing and 
    de-polarizing". Thus the rectification found in the T operator serves to 
    dictate whether polizing (half-wave rectification) or de-polizing (inverse
    half-wave rectification) flow states are allowed to occur.

    Parameters
    ----------
    D : int                      diffusion coefficient
    h : int                      step size
    t0 : int                     stimulus injection point
    stimulus : array-like        luminance distribution     
    
    Returns
    ----------
    f : array-like               output of diffusion equation
    
    
    ---------------------------------------------------------------------
    |lamba |   state                 | result on input x                |
    |------|-------------------------|----------------------------------|
    |==0   | linearity  (T[0])       | Operator becomes Laplacian       |
    |<0    | positive K(lamda)       | Half-wave rectification          |
    |>0    | negative K(lamda)       | Inverse half-wave rectification  |
    ---------------------------------------------------------------------
    
    """
    
    if lamda == 0:  # linearity
        return flt.laplace(f)
    else:           # non-linearity (neighbour interactions up/down/left/right)
        f_new = T(lamda,np.roll(f,1, axis=0)-f) \
        +T(lamda,np.roll(f,-1, axis=0)-f) \
        +T(lamda,np.roll(f, 1, axis=1)-f) \
        +T(lamda,np.roll(f,-1, axis=1)-f)
        return f_new
def cost(image):
    return laplace(image)**2
Exemple #52
0
 def outline(self):
     from scipy.ndimage.filters import laplace    
     pbox = self.boxed(pad=1)
     return boolmask(laplace(pbox))
def gradient_diffusion(im_dx, im_dy, im_fgnd_mask,
                       mu=5, lamda=5, iterations=10, dt=0.05):
    """
    Diffusion of gradient field using Navier-Stokes equation. Used for
    smoothing/denoising a gradient field.

    Takes as input a gradient field image (dX, dY), and a mask of the
    foreground region, and then iteratively solves the Navier-Stokes equation
    to diffuse the vector field and align noisy gradient vectors with their
    surrounding signals.

    Parameters
    ----------
    im_dx : array_like
        Horizontal component of gradient image.
    im_dy : array_like
        Vertical component of gradient image.
    im_fgnd_mask : array_like
        Binary mask where foreground objects have value 1, and background
        objects have value 0. Used to restrict influence of background vectors
        on diffusion process.
    mu : float
        Weight parmeter from Navier-Stokes equation - weights divergence and
        Laplacian terms. Default value = 5.
    lamda : float
        Weight parameter from Navier-Stokes equation - used to weight
        divergence. Default value = 5.
    iterations : float
        Number of time-steps to use in solving Navier-Stokes. Default value =
        10.
    dt : float
        Timestep to be used in solving Navier-Stokes. Default value = 0.05.

    Returns
    -------
    im_vx : array_like
        Horizontal component of diffused gradient.
    im_vy : array_like
        Vertical component of diffused gradient.

    See Also
    --------
    histomicstk.segmentation.nuclear.GradientFlow

    References
    ----------
    .. [1] G. Li et al "3D cell nuclei segmentation based on gradient flow
           tracking" in BMC Cell Biology,vol.40,no.8, 2007.
    """

    # initialize solution
    im_vx = im_dx.copy()
    im_vy = im_dy.copy()

    # iterate for prescribed number of iterations
    for it in range(iterations):

        # calculate divergence of current solution
        vXY, vXX = np.gradient(im_vx)
        vYY, vYX = np.gradient(im_vy)
        Div = vXX + vYY
        DivY, DivX = np.gradient(Div)

        # calculate laplacians of current solution
        im_vx += dt * (mu * spf.laplace(im_vx) +
                       (lamda + mu) * DivX +
                       im_fgnd_mask * (im_dx - im_vx))
        im_vy += dt * (mu * spf.laplace(im_vy) +
                       (lamda + mu) * DivY +
                       im_fgnd_mask * (im_dy - im_vy))

    # return solution
    return im_vx, im_vy
Exemple #54
0
    def _remove_dup_laplace(self, data, mask, size=5):
        laplacian = np.multiply(laplace(data, mode='wrap'), mask)

        return generic_filter(laplacian, self._local_max_laplace, size=size, mode='wrap',
                extra_keywords={'size': size})
Exemple #55
0
# How often to add a raindrop (rate is a bad name, larger actually means less often)
rate = 40

# Set up a figure window with an array color plot 'im', using a logarithmic color scale
fig = pp.figure()
ax = fig.gca()
ax.set_xticks([])
ax.set_yticks([])
im = ax.imshow([[1]], norm=cl.LogNorm())

# Set up a 3xMxM array to hold the state of the system at the current, last and last-but-one timesteps
a = np.ones([3] + d * [M])

for i in range(t):
    # Iterate the system according the finite-difference algorithm
    a[0] = 2.0 * a[1] - a[2] + l * ft.laplace(a[1])

    # Every 'rate' iterations, add 1.0 to a random array index
    if i % rate == 0:
        a[0][tuple(np.random.randint(0, M, size=d))] += 1.0
        # Subtract a bit from all of the array to keep the overall sum constant
        a[0] -= 1.0 / a[0].size

    # Every 'every' iterations, update the plot and save an image
    if i % every == 0:
        im.set_data(a[0])
        fig.savefig('%08i.png' % i)
        print('%.2f%%' % (100.0 * float(i) / t))
        # Hack to make the colormap scaling work correctly
        if i == 0:
            im.autoscale()
params.append((0.16, 0.08, 0.060, 0.062))  # Coral
params.append((0.19, 0.05, 0.060, 0.062))  # Fingerprint
params.append((0.10, 0.10, 0.018, 0.050))  # Spirals
params.append((0.12, 0.08, 0.020, 0.050))  # Spirals Dense
params.append((0.10, 0.16, 0.020, 0.050))  # Spirals Fast
params.append((0.16, 0.08, 0.020, 0.055))  # Unstable
params.append((0.16, 0.08, 0.050, 0.065))  # Worms 1
params.append((0.16, 0.08, 0.054, 0.063))  # Worms 2
params.append((0.16, 0.08, 0.035, 0.060))  # Zebrafish
(du, dv, f, k) = params[2]

dt = 1.

ims = []
fig = figure()
axis('off')

N = 20000
for ind in range(N):
    u, v = u + (du * laplace(u, mode='wrap') - u * v ** 2 + f * (1. - u)) * dt, v + (
        dv * laplace(v, mode='wrap') + u * v ** 2 - (k + f) * v) * dt
    if ind % 10 == 0:
        print(str(ind) + "/" + str(N))
        ims.append([imshow(v)])

ani = ArtistAnimation(fig, ims, interval=10, blit=True, repeat_delay=1000)
Writer = writers['ffmpeg']
writer = Writer(fps=100, metadata=dict(artist='Laurent Garcin'), bitrate=18000)
ani.save('morpho.mp4', writer=writer)
show()
Exemple #57
0
def run(fileName,sequence=None,plot=False,verbose=False,referenceName='2OMZ'):
    from scipy.ndimage.filters import laplace
    import numpy
    upperValues = 5
    diagonalLength = 10
    filterBand = 25
    if verbose:
        print '<!--',fileName,'-->'
    try:
        m = parseFFASMatrix(fileName)
    except IOError:
        print 'Error reading file', fileName
        raise Exception
    
    if plot:
        pyplot.imshow(m,interpolation='nearest',cmap = cm.BrBG)
        pyplot.show()
    
#     pyplot.imshow(m,interpolation='nearest',cmap = cm.BrBG)
#     pyplot.show()
    
    m = filterDiagonal(m,diagonalLength)
    
    if plot:
        pyplot.imshow(m,interpolation='nearest',cmap = cm.BrBG)
        pyplot.show()
    m = compressMatrix(m,referenceName)
    if plot:
        pyplot.imshow(m,interpolation='nearest',cmap = cm.BrBG)
        pyplot.show()
        
    m = laplace(m)
    if plot:
        pyplot.imshow(m,interpolation='nearest',cmap = cm.BrBG)
        pyplot.show()
    
    signal = diagonalSum(m[:upperValues,:])
    signal = (signal - numpy.mean(signal)) / numpy.std(signal)
    
    irregularities = {}
    try:
        if verbose:
            print '<!--','Before parseFFASAlignment','-->' 
        referenceOffset,queryOffset,referenceAlignment,queryAlignment = parseFFASAlignment(fileName.replace('.mat','.txt'))
        if verbose:
            print '<!--','After parseFFASAlignment','-->'                
    except :
        queryOffset = 0
    
        
#     print signal
#     queryOffset = 0
    print '<!--','Query Offset', queryOffset,'-->'
    meanLength,sigmaScale = meanLengthFromSignal(signal[queryOffset:],verbose)
    print '<!--',sigmaScale,'-->'
    indexes = peaksFromSignal(signal,sigmaScale)

    units = getUnitsFromSignal(signal,queryOffset,12)

    unitStarts = [u[0] for u in units]
    unitEnds = [u[1] for u in units]
    
    irregularities = [unit[1] - unit[0] for unit in units]
    if sequence:
        subsequences = [sequence.seq[unit[0]:unit[1]] for unit in units] 
    else:
        subsequences = []
    return unitStarts, unitEnds, units,irregularities , subsequences,meanLength,signal
Exemple #58
0
                                              frame_number = ini_f + tt, 
                                              worm_index = w_ind, 
                                              roi_size=-1
                                              )
#%%
    w_roi = worm_roi.astype(np.float32)
    valid_pix = w_roi[w_roi!=0]
    bot = valid_pix.min()
    top = valid_pix.max()
    w_roi[w_roi==0] = top
    w_roi = (w_roi-bot)/(top-bot+1) + 1e-3
    
    
    dm = gaussian_filter(w_roi, 1, mode='reflect')
    #dm = median_filter(w_roi, 5, mode='reflect')
    dl = laplace(dm, mode='reflect')
    dl = np.abs(dl)
    w_roi_border = gaussian_filter(dl, 1, mode='reflect')
    
    dd = dm #+ w_roi_border
    dd = dd - dd.min()
    dd = dd/dd.max()
    #plt.imshow(dd)
    #%%
    w_roi = dd
    #%%
    #plt.imshow(w_roi_border, interpolation='none', cmap='gray')
    
    #%%
    w_roi = Variable(torch.from_numpy(w_roi))
    #w_roi_border = Variable(torch.from_numpy(w_roi_border))
Exemple #59
0
def test():

    # img=nib.load('/home/eg309/Data/project01_dsi/connectome_0001/tp1/RAWDATA/OUT/mr000001.nii.gz')
    btable = np.loadtxt(get_data("dsi515btable"))
    # volume size
    sz = 16
    # shifting
    origin = 8
    # hanning width
    filter_width = 32.0
    # number of signal sampling points
    n = 515
    # odf radius
    radius = np.arange(2.1, 6, 0.2)
    # create q-table
    bv = btable[:, 0]
    bmin = np.sort(bv)[1]
    bv = np.sqrt(bv / bmin)
    qtable = np.vstack((bv, bv, bv)).T * btable[:, 1:]
    qtable = np.floor(qtable + 0.5)
    # copy bvals and bvecs
    bvals = btable[:, 0]
    bvecs = btable[:, 1:]
    # S=img.get_data()[38,50,20]#[96/2,96/2,20]
    S, stics = SticksAndBall(
        bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (60, 0), (90, 90)], fractions=[0, 0, 0], snr=None
    )

    S2 = S.copy()
    S2 = S2.reshape(1, len(S))
    dn = DiffusionNabla(S2, bvals, bvecs, auto=False)
    pR = dn.equators
    odf = dn.odf(S)
    # Xs=dn.precompute_interp_coords()
    peaks, inds = peak_finding(odf.astype("f8"), dn.odf_faces.astype("uint16"))
    print peaks
    print peaks / peaks.min()
    # print dn.PK
    dn.fit()
    print dn.PK

    # """
    ren = fvtk.ren()
    colors = fvtk.colors(odf, "jet")
    fvtk.add(ren, fvtk.point(dn.odf_vertices, colors, point_radius=0.05, theta=8, phi=8))
    fvtk.show(ren)
    # """

    stop

    # ds=DiffusionSpectrum(S2,bvals,bvecs)
    # tpr=ds.pdf(S)
    # todf=ds.odf(tpr)

    """
    #show projected signal
    Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])
    X0=np.dot(np.diag(np.concatenate([S[1:],S[1:]])),Bvecs)    
    ren=fvtk.ren()
    fvtk.add(ren,fvtk.point(X0,fvtk.yellow,1,2,16,16))    
    fvtk.show(ren)
    """
    # qtable=5*matrix[:,1:]

    # calculate radius for the hanning filter
    r = np.sqrt(qtable[:, 0] ** 2 + qtable[:, 1] ** 2 + qtable[:, 2] ** 2)

    # setting hanning filter width and hanning
    hanning = 0.5 * np.cos(2 * np.pi * r / filter_width)

    # center and index in q space volume
    q = qtable + origin
    q = q.astype("i8")

    # apply the hanning filter
    values = S * hanning

    """
    #plot q-table
    ren=fvtk.ren()
    colors=fvtk.colors(values,'jet')
    fvtk.add(ren,fvtk.point(q,colors,1,0.1,6,6))
    fvtk.show(ren)
    """

    # create the signal volume
    Sq = np.zeros((sz, sz, sz))
    for i in range(n):
        Sq[q[i][0], q[i][1], q[i][2]] += values[i]

    # apply fourier transform
    Pr = fftshift(np.abs(np.real(fftn(fftshift(Sq), (sz, sz, sz)))))

    # """
    ren = fvtk.ren()
    vol = fvtk.volume(Pr)
    fvtk.add(ren, vol)
    fvtk.show(ren)
    # """

    """
    from enthought.mayavi import mlab
    mlab.pipeline.volume(mlab.pipeline.scalar_field(Sq))
    mlab.show()
    """

    # vertices, edges, faces  = create_unit_sphere(5)
    vertices, faces = sphere_vf_from("symmetric362")
    odf = np.zeros(len(vertices))

    for m in range(len(vertices)):

        xi = origin + radius * vertices[m, 0]
        yi = origin + radius * vertices[m, 1]
        zi = origin + radius * vertices[m, 2]
        PrI = map_coordinates(Pr, np.vstack((xi, yi, zi)), order=1)
        for i in range(len(radius)):
            odf[m] = odf[m] + PrI[i] * radius[i] ** 2

    """
    ren=fvtk.ren()
    colors=fvtk.colors(odf,'jet')
    fvtk.add(ren,fvtk.point(vertices,colors,point_radius=.05,theta=8,phi=8))
    fvtk.show(ren)
    """

    """
    #Pr[Pr<500]=0    
    ren=fvtk.ren()
    #ren.SetBackground(1,1,1)
    fvtk.add(ren,fvtk.volume(Pr))
    fvtk.show(ren)
    """

    peaks, inds = peak_finding(odf.astype("f8"), faces.astype("uint16"))

    Eq = np.zeros((sz, sz, sz))
    for i in range(n):
        Eq[q[i][0], q[i][1], q[i][2]] += S[i] / S[0]

    LEq = laplace(Eq)

    # Pr[Pr<500]=0
    ren = fvtk.ren()
    # ren.SetBackground(1,1,1)
    fvtk.add(ren, fvtk.volume(Eq))
    fvtk.show(ren)

    phis = np.linspace(0, 2 * np.pi, 100)

    planars = []
    for phi in phis:
        planars.append(sphere2cart(1, np.pi / 2, phi))
    planars = np.array(planars)

    planarsR = []
    for v in vertices:
        R = vec2vec_rotmat(np.array([0, 0, 1]), v)
        planarsR.append(np.dot(R, planars.T).T)

    """
    ren=fvtk.ren()
    fvtk.add(ren,fvtk.point(planarsR[0],fvtk.green,1,0.1,8,8))
    fvtk.add(ren,fvtk.point(2*planarsR[1],fvtk.red,1,0.1,8,8))
    fvtk.show(ren)
    """

    azimsums = []
    for disk in planarsR:
        diskshift = 4 * disk + origin
        # Sq0=map_coordinates(Sq,diskshift.T,order=1)
        # azimsums.append(np.sum(Sq0))
        # Eq0=map_coordinates(Eq,diskshift.T,order=1)
        # azimsums.append(np.sum(Eq0))
        LEq0 = map_coordinates(LEq, diskshift.T, order=1)
        azimsums.append(np.sum(LEq0))

    azimsums = np.array(azimsums)

    # """
    ren = fvtk.ren()
    colors = fvtk.colors(azimsums, "jet")
    fvtk.add(ren, fvtk.point(vertices, colors, point_radius=0.05, theta=8, phi=8))
    fvtk.show(ren)
    # """

    # for p in planarsR[0]:
    """
Exemple #60
0
    def _solvePoissonEq(self, I1, I2, iOutItr=0):
        """Solve the Poisson's equation by Fourier transform (differential) or
        serial expansion (integration).

        There is no convergence for fft actually. Need to add the difference
        comparison and X-alpha method. Need to discuss further for this.

        Parameters
        ----------
        I1 : Image
            Intra- or extra-focal image.
        I2 : Image
            Intra- or extra-focal image.
        iOutItr : int, optional
            ith number of outer loop iteration which is important in "fft"
            algorithm. (the default is 0.)

        Returns
        -------
        numpy.ndarray
            Coefficients of normal/ annular Zernike polynomials.
        numpy.ndarray
            Estimated wavefront.
        """

        # Calculate the aperature pixel size
        apertureDiameter = self._inst.getApertureDiameter()
        sensorFactor = self._inst.getSensorFactor()
        dimOfDonut = self._inst.getDimOfDonutOnSensor()
        aperturePixelSize = apertureDiameter*sensorFactor/dimOfDonut

        # Calculate the differential Omega
        dOmega = aperturePixelSize**2

        # Solve the Poisson's equation based on the type of algorithm
        numTerms = self.getNumOfZernikes()
        zobsR = self.getObsOfZernikes()
        PoissonSolver = self.getPoissonSolverName()
        if (PoissonSolver == "fft"):

            # Use the differential method by fft to solve the Poisson's
            # equation

            # Parameter to determine the threshold of calculating I0.
            sumclipSequence = self.getSignalClipSequence()
            cliplevel = sumclipSequence[iOutItr]

            # Generate the v, u-coordinates on pupil plane
            padDim = self.getFftDimension()
            v, u = np.mgrid[
                -0.5/aperturePixelSize: 0.5/aperturePixelSize: 1./padDim/aperturePixelSize,
                -0.5/aperturePixelSize: 0.5/aperturePixelSize: 1./padDim/aperturePixelSize]

            # Show the threshold and pupil coordinate information
            if (self.debugLevel >= 3):
                print("iOuter=%d, cliplevel=%4.2f" % (iOutItr, cliplevel))
                print(v.shape)

            # Calculate the const of fft:
            # FT{Delta W} = -4*pi^2*(u^2+v^2) * FT{W}
            u2v2 = -4 * (np.pi**2) * (u*u + v*v)

            # Set origin to Inf to result in 0 at origin after filtering
            ctrIdx = int(np.floor(padDim/2.0))
            u2v2[ctrIdx, ctrIdx] = np.inf

            # Calculate the wavefront signal
            Sini = self._createSignal(I1, I2, cliplevel)

            # Find the just-outside and just-inside indices of a ring in pixels
            # This is for the use in setting dWdn = 0
            boundaryT = self.getBoundaryThickness()

            struct = generate_binary_structure(2, 1)
            struct = iterate_structure(struct, boundaryT)

            ApringOut = np.logical_xor(binary_dilation(self.pMask, structure=struct),
                                       self.pMask).astype(int)
            ApringIn = np.logical_xor(binary_erosion(self.pMask, structure=struct),
                                      self.pMask).astype(int)

            bordery, borderx = np.nonzero(ApringOut)

            # Put the signal in boundary (since there's no existing Sestimate,
            # S just equals self.S as the initial condition of SCF
            S = Sini.copy()
            for jj in range(self.getNumOfInnerItr()):

                # Calculate FT{S}
                SFFT = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(S)))

                # Calculate W by W=IFT{ FT{S}/(-4*pi^2*(u^2+v^2)) }
                W = np.fft.fftshift(np.fft.irfft2(np.fft.fftshift(SFFT/u2v2), s=S.shape))

                # Estimate the wavefront (includes zeroing offset & masking to
                # the aperture size)

                # Take the estimated wavefront
                West = extractArray(W, dimOfDonut)

                # Calculate the offset
                offset = West[self.pMask == 1].mean()
                West = West - offset
                West[self.pMask == 0] = 0

                # Set dWestimate/dn = 0 around boundary
                WestdWdn0 = West.copy()

                # Do a 3x3 average around each border pixel, including only
                # those pixels inside the aperture
                for ii in range(len(borderx)):
                    reg = West[borderx[ii] - boundaryT:
                               borderx[ii] + boundaryT + 1,
                               bordery[ii] - boundaryT:
                               bordery[ii] + boundaryT + 1]

                    intersectIdx = ApringIn[borderx[ii] - boundaryT:
                                            borderx[ii] + boundaryT + 1,
                                            bordery[ii] - boundaryT:
                                            bordery[ii] + boundaryT + 1]

                    WestdWdn0[borderx[ii], bordery[ii]] = \
                        reg[np.nonzero(intersectIdx)].mean()

                # Take Laplacian to find sensor signal estimate (Delta W = S)
                del2W = laplace(WestdWdn0)/dOmega

                # Extend the dimension of signal to the order of 2 for "fft" to
                # use
                Sest = padArray(del2W, padDim)

                # Put signal back inside boundary, leaving the rest of
                # Sestimate
                Sest[self.pMaskPad == 1] = Sini[self.pMaskPad == 1]

                # Need to recheck this condition
                S = Sest

            # Define the estimated wavefront
            # self.West = West.copy()

            # Calculate the coefficient of normal/ annular Zernike polynomials
            if (self.getCompensatorMode() == "zer"):
                xSensor, ySensor = self._inst.getSensorCoor()
                zc = ZernikeMaskedFit(West, xSensor, ySensor, numTerms,
                                      self.pMask, zobsR)
            else:
                zc = np.zeros(numTerms)

        elif (PoissonSolver == "exp"):

            # Use the integration method by serial expansion to solve the
            # Poisson's equation

            # Calculate I0 and dI
            I0, dI = self._getdIandI(I1, I2)

            # Get the x, y coordinate in mask. The element outside mask is 0.
            xSensor, ySensor = self._inst.getSensorCoor()
            xSensor = xSensor * self.cMask
            ySensor = ySensor * self.cMask

            # Create the F matrix and Zernike-related matrixes
            F = np.zeros(numTerms)
            dZidx = np.zeros((numTerms, dimOfDonut, dimOfDonut))
            dZidy = dZidx.copy()

            zcCol = np.zeros(numTerms)
            for ii in range(int(numTerms)):

                # Calculate the matrix for each Zk related component
                # Set the specific Zk cofficient to be 1 for the calculation
                zcCol[ii] = 1

                F[ii] = np.sum(dI*ZernikeAnnularEval(zcCol, xSensor, ySensor, zobsR))*dOmega
                dZidx[ii, :, :] = ZernikeAnnularGrad(zcCol, xSensor, ySensor, zobsR, "dx")
                dZidy[ii, :, :] = ZernikeAnnularGrad(zcCol, xSensor, ySensor, zobsR, "dy")

                # Set the specific Zk cofficient back to 0 to avoid interfering
                # other Zk's calculation
                zcCol[ii] = 0

            # Calculate Mij matrix, need to check the stability of integration
            # and symmetry later
            Mij = np.zeros([numTerms, numTerms])
            for ii in range(numTerms):
                for jj in range(numTerms):
                    Mij[ii, jj] = np.sum(I0*(dZidx[ii, :, :].squeeze()*dZidx[jj, :, :].squeeze() +
                                             dZidy[ii, :, :].squeeze()*dZidy[jj, :, :].squeeze()))
            Mij = dOmega/(apertureDiameter/2.)**2 * Mij

            # Calculate dz
            focalLength = self._inst.getFocalLength()
            offset = self._inst.getDefocalDisOffset()
            dz = 2*focalLength*(focalLength-offset)/offset

            # Define zc
            zc = np.zeros(numTerms)

            # Consider specific Zk terms only
            idx = (self.getZernikeTerms() - 1).tolist()

            # Solve the equation: M*W = F => W = M^(-1)*F
            zc_tmp = np.linalg.lstsq(Mij[:, idx][idx], F[idx], rcond=None)[0]/dz
            zc[idx] = zc_tmp

            # Estimate the wavefront surface based on z4 - z22
            # z0 - z3 are set to be 0 instead
            West = ZernikeAnnularEval(np.concatenate(([0, 0, 0], zc[3:])),
                                      xSensor, ySensor, zobsR)

        return zc, West