def calculateVideoGradients_noMotion(self, h, w):
     
     # Get height (h) and width (w) of the given image
     # What is ~, K (They are normally ones) [may be color and video frames]
     K = 1
     
     # Calculate Number of pixels in entire video (N)
     N = h * w * K
     
     ## Calculate Horizontal adjacencies (Gx)
     # left: 1D array of size N filled by -1
     left = -np.ones((N, 1), dtype=np.int64)
     # a: 2D array h*k each row(i) w*h*(i+1)
     a = w * h * np.transpose(np.tile(np.arange(1, K+1), (h, 1)))
     # b: produce 2D array h*k each row(i) from 1 to h
     b = np.tile(np.arange(1, h+1), (K, 1))
     # set some indices in left by 0 (indices in a-b)
     left[a - b] = 0
     d = np.concatenate((left, np.ones((N, 1), dtype=np.int64)), axis=1)
     # Gx: sparse matrix of left on diagonal -h and ones on diagonal 0
     self.Gx = spdiags(np.transpose(d), np.array([-h, 0]), N, N, "csc") # we can also try "csc"
     # for spdiags number of columns must be equal to the number of diagonals to be extracted :3 
     
     ## Calculate Vertical adjacencies (Gy)
     # top: 1D array of size N filled by -1
     top = -np.ones((N, 1), dtype=np.int64)
     # set some indices in top by 0 (each h element)
     top[h-1::h] = 0;
     e = np.concatenate((top, np.ones((N, 1), dtype=np.int64)), axis=1)
     # Gy: sparse matrix of top on diagonal -1 and ones on diagonal 0
     self.Gy = spdiags(np.transpose(e), np.array([-1, 0]), N, N, "csc") # we can also try "csr"
 def test_log_det_exact_toy_large_shogun(self):
     n = 1e6
     d = abs(randn(n))
     Q = spdiags(d, 0, n, n)
                 
     self.assertAlmostEqual(OzonePosterior.log_det_shogun_exact(Q), sum(log(d)),
                            delta=1e-5)
 def test_log_det_exact_toy_small_scikits(self):
     n = 3
     d = abs(randn(n))
     Q = spdiags(d, 0, n, n)
                 
     self.assertAlmostEqual(OzonePosterior.log_det_scikits(Q), sum(log(d)),
                            delta=1e-15)
Example #4
0
def sym_sqrt(A):
    """
    Returns Q such that A = QQ in a matrix multiplication sense,
    where A is an input Hermitian numpy ndarray.
    
    Adapted from A. Bolton, Utah
    """
    w, V = N.linalg.eigh(A)    
    wx = spdiags(N.sqrt(w), 0, len(w), len(w))
    Q = V.dot( wx.dot(V.T) )
    return Q
Example #5
0
def stereoWarpK_noMotion_singleSided(curImageInfo, conversionParam, globalParam):
    """
        This function warps an image sequence (with corresponding flow and depth) to a stereo sequence
        
            1) First of all it uses a heuristic to calculate initial depth
            2) Then, It smooth this initial depth by spatial smoothness if needed
            4) After that, it warps the image and does interpolation to generate the right image \
               it pushes the pixels [to the right] as the depth increases 
        
    """    
    h, w, u = curImageInfo.originalImageResized.shape # shape after resize
    K = 1
    N = h * w * K
    gr = np.mean(curImageInfo.originalImageResized, 2) # not 3 as it is zero based :3
    grs = cv2.GaussianBlur(gr, (5, 5), 1)
    
    # One heuristic for converting depth to disparity
    disparity0 = imnormalize(1/(1+imnormalize(curImageInfo.depthResized)))*conversionParam.maxDisp - conversionParam.maxDisp/2;
    
    if conversionParam.spatialSmoothnessSwitch == True:
        # Smoothing the depth spatially according to adjacent pixels by using Gx, Gy gradients
        # Vertical and Horizontal Edges
        dx = cv2.filter2D(grs, -1, np.transpose(np.array([[-1, 1, 0]])))
        dy = cv2.filter2D(grs, -1, np.array([[-1, 1, 0]]))
        
        W = ( imnormalize(disparity0) + sigmoid(np.sqrt(np.power(dx, 2) + np.power(dy, 2)), 0.01, 500) ) / 2  
        
        A = np.transpose(spdiags(np.transpose(W).flatten(), 0, N, N, "csc") \
            + (conversionParam.spatialSmoothCoeff_x * globalParam.Gx.transpose() * globalParam.Gx) \
            + (conversionParam.spatialSmoothCoeff_y * globalParam.Gy.transpose() * globalParam.Gy))
        
        b = np.transpose(W).flatten() * np.transpose(disparity0).flatten()
        
        [x, flag] = cg(A, b, np.transpose(disparity0).flatten(), 5e-1, 50)
        
        disparity = np.transpose(np.reshape(x, (w, h))) # remove (h, w, 1, K)
    else:
        disparity = disparity0
    
    curImageInfo.leftImage = curImageInfo.originalImage
    
    # The -ve sign to convert the white to black and black to white 
    warpright = -disparity
            
    # only the warping interp2 is done on the original size image with no resizing to have good estimation
    warpright = cv2.resize(warpright, (curImageInfo.originalImage.shape[1], curImageInfo.originalImage.shape[0]), 
                           interpolation=cv2.INTER_LINEAR)
    
    curImageInfo.rightImage = (clip(warpImage_v2((curImageInfo.originalImage), (warpright), 
              conversionParam.resizeFactor, globalParam.xx, globalParam.yy, globalParam.YY)))
    
    return disparity
Example #6
0
    def test_spdiags(self):
        diags1 = array([[1, 2, 3, 4, 5]])
        diags2 = array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
        diags3 = array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],
                        [11, 12, 13, 14, 15]])

        cases = []
        cases.append((diags1, 0, 1, 1, [[1]]))
        cases.append((diags1, [0], 1, 1, [[1]]))
        cases.append((diags1, [0], 2, 1, [[1], [0]]))
        cases.append((diags1, [0], 1, 2, [[1, 0]]))
        cases.append((diags1, [1], 1, 2, [[0, 2]]))
        cases.append((diags1, [-1], 1, 2, [[0, 0]]))
        cases.append((diags1, [0], 2, 2, [[1, 0], [0, 2]]))
        cases.append((diags1, [-1], 2, 2, [[0, 0], [1, 0]]))
        cases.append((diags1, [3], 2, 2, [[0, 0], [0, 0]]))
        cases.append((diags1, [0], 3, 4, [[1, 0, 0, 0], [0, 2, 0, 0],
                                          [0, 0, 3, 0]]))
        cases.append((diags1, [1], 3, 4, [[0, 2, 0, 0], [0, 0, 3, 0],
                                          [0, 0, 0, 4]]))
        cases.append((diags1, [2], 3, 5, [[0, 0, 3, 0, 0], [0, 0, 0, 4, 0],
                                          [0, 0, 0, 0, 5]]))

        cases.append((diags2, [0, 2], 3, 3, [[1, 0, 8], [0, 2, 0], [0, 0, 3]]))
        cases.append((diags2, [-1, 0], 3, 4, [[6, 0, 0, 0], [1, 7, 0, 0],
                                              [0, 2, 8, 0]]))
        cases.append((diags2, [2, -3], 6, 6, [[0, 0, 3, 0, 0, 0],
                                              [0, 0, 0, 4, 0, 0],
                                              [0, 0, 0, 0, 5, 0],
                                              [6, 0, 0, 0, 0, 0],
                                              [0, 7, 0, 0, 0, 0],
                                              [0, 0, 8, 0, 0, 0]]))

        cases.append((diags3, [-1, 0, 1], 6, 6, [[6, 12, 0, 0, 0, 0],
                                                 [1, 7, 13, 0, 0, 0],
                                                 [0, 2, 8, 14, 0, 0],
                                                 [0, 0, 3, 9, 15, 0],
                                                 [0, 0, 0, 4, 10, 0],
                                                 [0, 0, 0, 0, 5, 0]]))
        cases.append((diags3, [-4, 2, -1], 6, 5, [[0, 0, 8, 0, 0],
                                                  [11, 0, 0, 9, 0],
                                                  [0, 12, 0, 0, 10],
                                                  [0, 0, 13, 0, 0],
                                                  [1, 0, 0, 14, 0],
                                                  [0, 2, 0, 0, 15]]))

        for d, o, m, n, result in cases:
            assert_equal(construct.spdiags(d, o, m, n).todense(), result)
Example #7
0
    def test_spdiags(self):
        diags1 = array([[1, 2, 3, 4, 5]])
        diags2 = array([[1, 2, 3, 4, 5],
                         [6, 7, 8, 9,10]])
        diags3 = array([[1, 2, 3, 4, 5],
                         [6, 7, 8, 9,10],
                         [11,12,13,14,15]])

        cases = []
        cases.append((diags1, 0, 1, 1, [[1]]))
        cases.append((diags1, [0], 1, 1, [[1]]))
        cases.append((diags1, [0], 2, 1, [[1],[0]]))
        cases.append((diags1, [0], 1, 2, [[1,0]]))
        cases.append((diags1, [1], 1, 2, [[0,2]]))
        cases.append((diags1,[-1], 1, 2, [[0,0]]))
        cases.append((diags1, [0], 2, 2, [[1,0],[0,2]]))
        cases.append((diags1,[-1], 2, 2, [[0,0],[1,0]]))
        cases.append((diags1, [3], 2, 2, [[0,0],[0,0]]))
        cases.append((diags1, [0], 3, 4, [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
        cases.append((diags1, [1], 3, 4, [[0,2,0,0],[0,0,3,0],[0,0,0,4]]))
        cases.append((diags1, [2], 3, 5, [[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]]))

        cases.append((diags2, [0,2], 3, 3, [[1,0,8],[0,2,0],[0,0,3]]))
        cases.append((diags2, [-1,0], 3, 4, [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
        cases.append((diags2, [2,-3], 6, 6, [[0,0,3,0,0,0],
                                              [0,0,0,4,0,0],
                                              [0,0,0,0,5,0],
                                              [6,0,0,0,0,0],
                                              [0,7,0,0,0,0],
                                              [0,0,8,0,0,0]]))

        cases.append((diags3, [-1,0,1], 6, 6, [[6,12, 0, 0, 0, 0],
                                                [1, 7,13, 0, 0, 0],
                                                [0, 2, 8,14, 0, 0],
                                                [0, 0, 3, 9,15, 0],
                                                [0, 0, 0, 4,10, 0],
                                                [0, 0, 0, 0, 5, 0]]))
        cases.append((diags3, [-4,2,-1], 6, 5, [[0, 0, 8, 0, 0],
                                                 [11, 0, 0, 9, 0],
                                                 [0,12, 0, 0,10],
                                                 [0, 0,13, 0, 0],
                                                 [1, 0, 0,14, 0],
                                                 [0, 2, 0, 0,15]]))

        for d,o,m,n,result in cases:
            assert_equal(construct.spdiags(d,o,m,n).todense(), result)
Example #8
0
def laplacian(g, nodelist=None, weight='weight', dtype=None, form='csr'):
    '''Return the sparse graph Laplacian of a graph g.'''
    A = sym_adjacency(g, nodelist=nodelist, weight=weight, dtype=dtype, form=form)
    n = g.number_of_nodes()
    D = spdiags(np.asarray(A.sum(axis=1).T), 0, n, n, format=form)
    return D - A
Example #9
0
def spline_fit(x, y, weights, xfit):
    """
    Fit a cubic b-spline to y vs. x with weights and full error propagation.
    Return fit with diagonalized errors.

    Inputs:
        x, y, weights : numpy arrays sorted by ascending x
    
    Returns 1D arrays:
        coadd_y[]
        coadd_ivar[]
        
    Where coadd_ivar is the diagonal inverse variance of coadd_y.
    """
    #- Setup cubic b-spline basis matrix: y = A coeff
    t0 = time()
    ny = len(y)
    dxfit = N.gradient(xfit)
    A = N.zeros( (ny, len(xfit)) )
    for i in range(A.shape[0]):
        A[i] = bspline((x[i] - xfit)/dxfit, 3)

    t0 = timeit("Setup A", t0)

    #- Convert to sparse matrices
    A = scipy.sparse.dia_matrix(A)
    W = spdiags(weights, 0, ny, ny)
    t0 = timeit("Sparsify A", t0)

    #- Generate inverse covariance matrix
    iCovCoeff = A.T.dot(W.dot(A))

    #- Solve "y = A coeff" with weights -> (A.T W) y = (A.T W A) coeff
    wy = A.T.dot(W.dot(y))
    t0 = timeit("Apply weights", t0)
    # coeff = scipy.sparse.linalg.lsqr(iCovCoeff, wy)[0]   
    # t0 = timeit("Solve", t0)

    #- Solve with banded matrices
    iCovDiag = iCovCoeff.todia().data[-1::-1, :]  #- have to flip for solver
    ndiag = iCovDiag.shape[0]/2
    coeff = scipy.linalg.solve_banded((ndiag, ndiag), iCovDiag, wy)
    t0 = timeit("Solve", t0)

    #- Evaluate b-spline solution at xfit
    B = N.zeros( (len(xfit), len(xfit)) )
    for i in range(B.shape[0]):
        B[i] = bspline((xfit[i] - xfit)/dxfit, 3)

    coadd = B.dot(coeff)
    t0 = timeit("Evaluate", t0)
    
    ### This is the expensive step as matrices get larger
    ### could use eig_banded and invert with that
    #- Convert iCov for coefficients into iCov for the coadd itself
    #-   coadd = B coeff
    #-   CovCoadd = B CovCoeff B.T
    #-   iCovCoadd = iB.T iCovCoeff iB,  since B is square and invertable
    iB = N.linalg.inv(B)
    iCovCoadd = iB.T.dot( iCovCoeff.dot(iB) )
    t0 = timeit("Get iCov(coadd)", t0)
    
    ### This is the next most expensive step as matrices get larger
    #- Diagonalize errors
    try:
        R, coivar = resolution_from_icov(iCovCoadd)
        Rc = R.dot(coadd)
    except:
        print "ERROR: Unable to find R for range", xfit[0], xfit[1]
        return N.zeros(len(coadd)), N.zeros(len(coadd))
    t0 = timeit("Diagonalize", t0)
        
    return Rc, coivar