示例#1
0
文件: bfgs.py 项目: BRML/climin
    def find_direction(self, grad_diffs, steps, grad, hessian_diag, idxs):
        grad = grad.copy()  # We will change this.
        n_current_factors = len(idxs)

        # TODO: find a good name for this variable.
        rho = scipy.empty(n_current_factors)

        # TODO: vectorize this function
        for i in idxs:
            rho[i] = 1 / scipy.inner(grad_diffs[i], steps[i])

        # TODO: find a good name for this variable as well.
        alpha = scipy.empty(n_current_factors)

        for i in idxs[::-1]:
            alpha[i] = rho[i] * scipy.inner(steps[i], grad)
            grad -= alpha[i] * grad_diffs[i]
        z = hessian_diag * grad

        # TODO: find a good name for this variable (surprise!)
        beta = scipy.empty(n_current_factors)

        for i in idxs:
            beta[i] = rho[i] * scipy.inner(grad_diffs[i], z)
            z += steps[i] * (alpha[i] - beta[i])

        return z, {}
def HMC_Stepper(epsilon, L, q_current):
    q = q_current
    p = scipy.random.normal(0.0, 1.0, scipy.size(q_current)) #choose fictitious momentum variables that are normally distributed
    p_current = p
    #START LEAPFROG METHOD
    #make half step for momentum at the beginning of the Leapfrog method
    p = p - epsilon*UDE.gradV(q)/2.0
    #alternate full steps for microscopic state and momentum
    for l in range (1,L): #We take L-1 steps, last step is done explicitly below the loop
        #make full step for the microscopic state
        q = q + epsilon*p
        #make full step for the momentum
        p = p - epsilon * UDE.gradV(q)
    #final (L-th) step: full step for q, half step for p
    q = q+epsilon*p
    p = p-epsilon * UDE.gradV(q)/2.0
    #END LEAPFROG METHOD

    #negate momentum at end of trajectory to make the proposal symmetric
    p = -p
    #evaluate potential and kinetic energies at start and end of trajectory
    currentV = UDE.V(q_current)
    currentK = scipy.inner(p_current,p_current)/2.0
    proposedV = UDE.V(q)
    proposedK = scipy.inner(p,p)/2.0

    #Accept or reject the state at end of trajectory, returning either
    #the position at the end of the trajectory or the initial position
    U = math.log(scipy.random.uniform(0.0, 1.0))  # generate uniform distributed random number and take logarithm
    testvalue = currentV-proposedV+currentK-proposedK
    if U > testvalue:
        #print("reject")
        q = q_current
    return q
示例#3
0
文件: bfgs.py 项目: zphilip/climin
    def find_direction(self, grad_diffs, steps, grad, hessian_diag, idxs):
        grad = grad.copy()  # We will change this.
        n_current_factors = len(idxs)

        # TODO: find a good name for this variable.
        rho = scipy.empty(n_current_factors)

        # TODO: vectorize this function
        for i in idxs:
            rho[i] = 1 / scipy.inner(grad_diffs[i], steps[i])

        # TODO: find a good name for this variable as well.
        alpha = scipy.empty(n_current_factors)

        for i in idxs[::-1]:
            alpha[i] = rho[i] * scipy.inner(steps[i], grad)
            grad -= alpha[i] * grad_diffs[i]
        z = hessian_diag * grad

        # TODO: find a good name for this variable (surprise!)
        beta = scipy.empty(n_current_factors)

        for i in idxs:
            beta[i] = rho[i] * scipy.inner(grad_diffs[i], z)
            z += steps[i] * (alpha[i] - beta[i])

        return z, {}
示例#4
0
def onMousePointViewer(event, _x, _y, flags, param):
    x = _x / SHOW_IMAGE_SCALE
    y = _y / SHOW_IMAGE_SCALE

    if event == cv2.EVENT_MOUSEMOVE:
        return
    elif event == cv2.EVENT_RBUTTONDOWN:
        return
    elif event == cv2.EVENT_LBUTTONDOWN:
        global curKeypoint2DLists
        global curKeypointIdLists
        if len(curKeypoint2DLists) > 0:
            query = np.array([x, y])
            nearestIndex = scipy.argmin([
                scipy.inner(query - point, query - point)
                for point in curKeypoint2DLists
            ])
            nearest = curKeypoint2DLists[nearestIndex]
            if (math.sqrt(scipy.inner(query - nearest, query - nearest)) <
                    THRESHOLD_FIND_CLICKED_KEYPOINT):
                print "selected point index : " + str(nearestIndex)
                print "selected point id : " + str(
                    curKeypointIdLists[nearestIndex])
                print "selected point : " + str(nearest[0]) + "," + str(
                    nearest[1])
                showPointViewer(curKeypointIdLists[nearestIndex])
                return
        print "There is no keypoint around clicked points. Clicked point is (" + str(
            x) + "," + str(y) + ")"
        return
示例#5
0
def precomputation(z_grid, solver):
    b_grid = scipy.zeros(scipy.size(z_grid))
    sigma_grid = scipy.zeros(scipy.size(z_grid))
    Ahat_grid = scipy.zeros(scipy.size(z_grid))
    for j in range(0, solver.J):
        b = 0.0
        sigma = 0.0
        Ahat_temp = 0.0
        eta = z_grid[j]
        x_current = solver.x_init
        for n in range(0, solver.N_prec):
            #take a biased step
            x_new = stepper.indirect(x_current, eta, solver)
            #accept-reject
            x_new = AR.indirect(x_current, x_new, eta, solver)
            #calculate contribution step
            b = b + (1.0/solver.N_prec)*(-scipy.inner(UDE.totalgradPot(x_new,solver),UDE.gradRestriction(x_new)) +\
                (1.0/solver.beta)*UDE.lapRestriction(x_new))
            sigma = sigma + (1.0 / solver.N_prec) * (linalg.norm(
                UDE.gradRestriction(x_new)))**2
            Ahat_temp = Ahat_temp + (1.0/solver.N_prec)*(math.exp(-solver.beta*UDE.totalPot(x_new,solver)) * \
                        (scipy.inner(UDE.gradRestriction(x_new),UDE.gradRestriction(x_new)))**(-0.5))
            #reset x_current for next iteration in n-loop
            x_current = x_new
        #save contribution in right register
        b_grid[j] = b
        sigma_grid[j] = sigma
        Ahat_grid[j] = -(1.0 / (solver.beta)) * math.log(Ahat_temp)
    return b_grid, sigma_grid, Ahat_grid
示例#6
0
 def corelationImage1Image2(imageArray1, imageArray2):
     image1 = scipy.inner(numpy.asarray(imageArray1), [299, 587, 114]) / 1000.0
     image2 = scipy.inner(numpy.asarray(imageArray2), [299, 587, 114]) / 1000.0
     
     image1 = (image1 - image1.mean())/ image1.std()
     image2 = (image2 - image2.mean())/ image2.std()
     
     corelationimage1Withimage2 = c2d(image1, image2, mode = 'same')
     return corelationimage1Withimage2.max()
示例#7
0
def par_perp(u, v):
    #Returns the components of u parallel to and perpendicular to v, as cartesian vectors.
    if (u[0], u[1]) == (0., 0.):
        print('zero wind')
        return 0, 0
    par = (scipy.inner(u, v)) / (scipy.inner(v, v)) * v
    if scipy.isnan(par[0]):
        print(u, v)
        raise ValueError('there is a par/perp Nan problem')
        # sys.exit()
    perp = u - par
    return par, perp
示例#8
0
文件: utils.py 项目: kurapan/ImgHash
def convert_to_grayscale(img):
	shape = img.shape(img)
	if len(shape) == 1:
		return img
	elif len(shape) == 3:
		return sp.inner(img, [299, 587, 114]) / 1000
	elif len(shape) == 4:
		return sp.inner(img, [299, 587, 114, 0] / 1000)
	elif len(shape) == 2:
		return sp.inner(img, [1, 0])
	else:
		raise ValueError("The image has a non-standard bit-depth which is not supported.")
示例#9
0
def get_ray_detector_intercept(ray, plane):
    n = plane['normal']
    d = ray['direction']
    denominator = sp.inner(d, n)
    if denominator==0:
        return None
    else:
        P_0p = plane['point']
        P_0r = ray['origin']
        numerator = sp.inner(P_0p-P_0r, n)
        t = numerator/denominator
        if t<0: return None
        point = P_0r + t*d
        return point
    return
示例#10
0
 def f(self, x):
     self.net.params[:] = x
     correct_answers_A = 0
     correct_answers_B = 0
     error = 0
     for (inpt, target_vec) in self.dataset:
         # print inpt
         output = self.net.activate(inpt)
         indic = output.reshape(
             self.width * self.height / self.net.blocksize, 1).sum(axis=0)
         klass = 1 if output[0] > 0.5 else 0
         target = target_vec.argmax()
         if klass == target == 0:
             correct_answers_A += 1
         elif klass == target == 1:
             correct_answers_B += 1
         diff = output - target
         error += scipy.inner(diff, diff)
         l = 0.1
         # error += scipy.inner(x, x) * l / 2  # regularization
         # print error
         # print indic
         # print target, klass
     # print "%i/%i" % (correct_answers_A, correct_answers_B)
     # print error / len(self.dataset)
     return error / len(self.dataset)
示例#11
0
def get(i):
    # get JPG image as Scipy array, RGB (3 layer)
    data = imread('/Users/kalaivanikubendran/Documents/Sideprojects/kalai-kaggle-code/train_sm/set175_%s.jpeg' % i)
    # convert to grey-scale using W3C luminance calc
    data = sp.inner(data, [299, 587, 114]) / 1000.0
    # normalize per http://en.wikipedia.org/wiki/Cross-correlation
    return (data - data.mean()) / data.std()
    def grad_f1(self, a):
        "Define the gradient for each convex inequality."

        # Initialize the output vector
        out = sp.zeros((self.M, self.Na))

        # Preliminary calculation
        _xx = sp.einsum('mi,mj->mij', self.xarray, self.xarray)

        # Compute the four terms
        _Da = sp.tensordot(self.D, a, axes=[(0,), (0,)])
        _DDa = sp.tensordot(self.D, _Da, axes=[(1,), (0,)])
        xxDDa = sp.tensordot(_xx.reshape(self.M, self.ndim**2),
                             _DDa.reshape(self.Na, self.ndim**2),
                             axes=[(-1,), (-1,)])

        _BDa = sp.dot(self.B, _Da)
        xBDa = sp.inner(self.xarray, _BDa)

        _Ba = sp.dot(a, self.B)
        _DBa = sp.dot(_Ba, self.D)
        xDBa = sp.tensordot(self.xarray,
                            _DBa, axes=[(-1,), (-1,)])

        BBa = sp.dot(self.B, _Ba)
        
        # compute the gradient by summing the four terms
        out[:, :] = 2.0 * (xxDDa + xBDa + xDBa + BBa)

        return out
def prepare_image_for_correlation(im):
    letterArray = fromimage(im.convert('RGB'))
    # Black and white
    letterArray = scipy.inner(letterArray, [299, 587, 114]) / 1000.0
    # Normalize
    letterArray = (letterArray - letterArray.mean()) / letterArray.std()
    return letterArray
示例#14
0
def adot_noconj(a, b):
    """
    Calculates the scalar product for the ancilla, expecting
    the arguments in matrix form.
    Equivalent to trace(dot(a, b))
    """    
    return sp.inner(a.T.ravel(), b.ravel())
示例#15
0
def prepare_image_for_correlation(im):
    letterArray = fromimage(im.convert('RGB'))
    # Black and white
    letterArray = scipy.inner(letterArray, [299, 587, 114]) / 1000.0
    # Normalize
    letterArray = (letterArray - letterArray.mean()) / letterArray.std()
    return letterArray
示例#16
0
文件: td.py 项目: hbhzwj/librl
 def stateActionValue(self, feature):
     r = self.tao(self.r) * self.r
     if self.enableOnlyEssentialFeatureInCritic:
         feature = self.module.decodeFeature(feature,
                                             self.essentialFeature)
     assert len(r) == self.criticdim, 'Wrong dimension of r'
     return scipy.inner(r, feature)
示例#17
0
def normalize(x):
    n = scipy.sqrt(scipy.inner(x,x))
    #n = sl.norm(x, scipy.inf)
    if n > 0:
        return x/n
    else:
        return x
示例#18
0
    def __predict(self, test_data, training_model_data, training_model_metadata):
        print 'Predict for test data', test_data;
        assignment = [];
        n_test_samples, nfeatures = test_data.shape;
        n_training_samples, nfeatures = training_model_data.shape;
        for i in range(n_test_samples):
            assignment.append([]);

            # Compute the distance of test sample to all training samples in the training model
            distances = np.array([ ( k, scipy.inner(test_data[i] - training_model_data[k],test_data[i] - training_model_data[k]) )
                                   for k in range(n_training_samples) ], dtype=[('index', int),('distance', float)]);

            distances.sort(order='distance');

            # Find the k best different labels
            j = 1;
            k = 1;
            k_best_labels = [];
            k_label = self.__find_instance_label(distances[0][0], training_model_metadata);
            k_best_labels.append(k_label);
            assignment[i].append([k_label, distances[0][1]]);
            while j < len(distances):
                k_label = self.__find_instance_label(distances[j][0], training_model_metadata);
                if k_label not in k_best_labels:
                    k_best_labels.append(k_label);
                    assignment[i].append([k_label, distances[j][1]]);
                    k += 1;
                j += 1;

            # Freeing memory
            del k_best_labels;
            del distances;

        return assignment;
示例#19
0
def get(i):
   # get JPG image as Scipy array, RGB (3 layer)
  data = imread(i)
  # convert to grey-scale using W3C luminance calc
  data = sp.inner(data, [299, 587, 114]) / 1000.0
  # normalize per http://en.wikipedia.org/wiki/Cross-correlation
  return (data - data.mean()) / data.std()
示例#20
0
def get(path):
        # get JPG image as Scipy array, RGB (3 layer)
        data = imread(path)
        # convert to grey-scale using W3C luminance calc
        data = sp.inner(data, [299, 587, 114]) / 1000.0
        # normalize per http://en.wikipedia.org/wiki/Cross-correlation
        return (data - data.mean()) / data.std()
示例#21
0
def norm(x):
    """2-norm of x
    """

    y = ravel(x)
    p = sqrt(inner(y, y))
    return p
示例#22
0
def norm(x):
    """2-norm of x
    """

    y = ravel(x)
    p = sqrt(inner(y, y))
    return p
示例#23
0
def cqtfft(X, fs=44100, lo=12, hi=None):
    """
    q, p = cqtfft(X, fs)

    Returns the complex constant-Q transform vector of fft vector X
    with sampling rate FS. Like chroma, but unwrapped.
    Here, Q = 16.817.
    """
    #Q = 16.817
    Q = 8.1658
    if X.ndim == 2:
        X = X[:, 0].squeeze()
    if hi is None:
        hi = int(hz2midi(fs / 2))
    p = scipy.arange(lo, hi)
    q = scipy.zeros(hi - lo)

    for i, midi in enumerate(p):
        center = X.size * midi2hz(midi) / fs
        width = int(center / Q)
        center = int(center)
        w = ss.triang(2 * width + 1)
        q[i] = scipy.inner(w, X[center - width:center + width + 1])

    return q, p
示例#24
0
def adot_noconj(a, b):
    """
    Calculates the scalar product for the ancilla, expecting
    the arguments in matrix form.
    Equivalent to trace(dot(a, b))
    """
    return sp.inner(a.T.ravel(), b.ravel())
示例#25
0
def compare_meanshift(dir_mainfolder):
    ##Compare_ls: Store score of comparation between images
    compare_ls = []
    ##Base_img: Image draw from user
    print "get base"
    base_img = cv2.imread(dir_mainfolder + '/img_result/0.jpg')
    img0 = cv2.cvtColor(base_img,cv2.COLOR_BGR2RGB)
    hist_base = cv2.calcHist([img0], [0, 1, 2], None, [8, 8, 8],
		[0, 256, 0, 256, 0, 256])
    hist_base = cv2.normalize(hist_base).flatten()
    base_img = cv2.resize(base_img, (100, 100))

    ##Get inner product user draw image
    base_img = sp.inner(base_img, [299, 587, 114]) / 1000.0
    base_img = (base_img - base_img.mean()) / base_img.std()
    base_img.shape
    num = 1
    ##Compare the user draw image to all images
    list_img =[]
    for img2 in glob.glob(dir_mainfolder + "/*.jpg"):
        n= cv2.imread(img2)
        list_img.append(n)
    for img2 in glob.glob(dir_mainfolder + "/*.png"):
        n= cv2.imread(img2)
        list_img.append(n)
    print "jump for"
    for img in list_img:
        img = get(num,dir_mainfolder,0)
        img.shape

        print "compare: " + num
        ##Use correlation 2d to compare between image
        compare_img = c2d(base_img, img, mode='same')
        value_c2d_pixel = compare_img.max()*0.4/1000
        
        ##Read image and calculated image histogram
        data = imread(dir_mainfolder+'/img_meanshift/%s.jpg' % num)
        img_1= cv2.cvtColor(data,cv2.COLOR_BGR2RGB)
        hist_img = cv2.calcHist([img_1], [0, 1, 2], None, [8, 8, 8],
		[0, 256, 0, 256, 0, 256])
        hist_img = cv2.normalize(hist_img).flatten()

        ##Comare histograms
        compare = cv2.compareHist(hist_base,hist_img,cv2.cv.CV_COMP_CORREL)
        compare = compare*0.6
        avg_value = (compare + value_c2d_pixel)/2
        compare_ls.append((num,avg_value))
        
        print "compare done"
        num = num + 1

    ##Sorting the score of comparation DESC
    compare_ls = sorted(compare_ls,key = itemgetter(1), reverse = True)
    i = 1
    
    ##Write ranking image to folder
    for ls in compare_ls:
        cv2.imwrite(dir_mainfolder+"/img_rank/"+str(i)+".jpg",list_img[ls[0] - 1])
        i = i+1
示例#26
0
def get_resized_data(origdata, size):
	'''Resize image data'''
	tmp = imresize(origdata, (size, size), interp="bilinear", mode=None)
	# convert to grey-scale using W3C luminance calc
	lum = [299, 587, 114]
	tmp = sp.inner(tmp, lum) / 1000.0
	# normalize per http://en.wikipedia.org/wiki/Cross-correlation
	return ((tmp - tmp.mean()) / tmp.std())
示例#27
0
def get(i):
    # get JPG image as Scipy array, RGB (3 layer)
    data = imread('im%s.jpg' % i)
    # convert to grey-scale using W3C luminance calc
    data = sp.inner(data, [299, 587, 114]) / 1000.0
    # normalize per http://en.wikipedia.org/wiki/Cross-correlation
    cross =(data - data.mean()) / data.std() #calcula a correlacao cruzada
    return cross
示例#28
0
 def f(self, x):
     self.net['mdrnn'].params[:] = x
     error = 0
     for (inpt, target) in self.trainds:
         output = self.net.activate(inpt)
         indic = output.reshape(self.width * self.height, 10).sum(axis=0)
         diff = indic - target
         error += scipy.inner(diff, diff)
     return error / len(self.trainds)
示例#29
0
def get(i,dir_mainfolder, flag):
    if flag == 1:
        data = imread(dir_mainfolder+'/img_kmean_handwrite/%s.jpg' % i)
    elif flag == 0:
        data = imread(dir_mainfolder+'/img_meanshift/%s.jpg' % i)

    data = cv2.resize(data, (100, 100))
    data = sp.inner(data, [299, 587, 114]) / 1000.0
    return (data - data.mean()) / data.std()
示例#30
0
def cluster(C, X_train, y_predict, k):
    sum = [0, 0, 0, 0] * k
    count = [0] * k
    newC = []
    for i in range(len(X_train)):
        min = 32768
        minj = -1
        for j in range(k):
            if scipy.inner(C[j] - X_train[i], C[j] - X_train[i]) < min:
                min = scipy.inner(C[j] - X_train[i], C[j] - X_train[i])
                minj = j
        y_predict[i] = (minj + 1) % k
    for i in range(len(X_train)):
        sum[y_predict[i]] += X_train[i]
        count[y_predict[i]] += 1
    for i in range(k):
        newC.append(sum[i] / count[i])
    return y_predict, newC
示例#31
0
def intercept_sphere_ray(sphere, ray):
    center = sphere['center']
    radius = sphere['radius']
    print '\nSphere center and radius: ', center, radius

    p0 = ray['origin']
    d  = ray['direction']
    print 'Ray origin and direction: ', p0, d

    # Solve the equation
    A = sp.inner(d,d)
    B = 2 * sp.inner(d,p0-center)
    C = sp.inner(p0-center,p0-center)-radius**2
    t = solve_quadratic(A, B, C)
    print 'solution', t
    if t!=None:
        intercept = p0 + t*d
    return None
示例#32
0
def get(pics,i):
    #global pics
    # get JPG image as Scipy array, RGB (3 layer)
    data = imread('%s%d.jpeg' %(pics,i))
    data = imresize(data,0.4)   
    #im2 = imresize(im22,0.5)
    #im3 = imresize(im33,0.5)
    # convert to grey-scale using W3C luminance calc
    data = sp.inner(data, [299, 587, 114]) / 1000.0
    # normalize as in http://en.wikipedia.org/wiki/Cross-correlation
    return (data - data.mean()) / data.std()
示例#33
0
文件: volume.py 项目: woodscn/pydec
def unsigned_volume(pts):
    """Unsigned volume of a simplex    
    
    Computes the unsigned volume of an M-simplex embedded in N-dimensional 
    space. The points are stored row-wise in an array with shape (M+1,N).
    
    Parameters
    ----------
    pts : array
        Array with shape (M+1,N) containing the coordinates
        of the (M+1) vertices of the M-simplex.

    Returns
    -------
    volume : scalar
        Unsigned volume of the simplex

    Notes
    -----
    Zero-dimensional simplices (points) are assigned unit volumes.
        

    Examples
    --------
    >>> # 0-simplex point 
    >>> unsigned_volume( [[0,0]] )
    1.0
    >>> # 1-simplex line segment
    >>> unsigned_volume( [[0,0],[1,0]] )             
    1.0
    >>> # 2-simplex triangle 
    >>> unsigned_volume( [[0,0,0],[0,1,0],[1,0,0]] ) 
    0.5


    References
    ----------
    [1] http://www.math.niu.edu/~rusin/known-math/97/volumes.polyh

    """

    pts = asarray(pts)

    M, N = pts.shape
    M -= 1

    if M < 0 or M > N:
        raise ValueError('array has invalid shape')

    if M == 0:
        return 1.0

    A = pts[1:] - pts[0]
    return sqrt(abs(det(inner(A, A)))) / factorial(M)
示例#34
0
def unsigned_volume(pts):
    """Unsigned volume of a simplex    
    
    Computes the unsigned volume of an M-simplex embedded in N-dimensional 
    space. The points are stored row-wise in an array with shape (M+1,N).
    
    Parameters
    ----------
    pts : array
        Array with shape (M+1,N) containing the coordinates
        of the (M+1) vertices of the M-simplex.

    Returns
    -------
    volume : scalar
        Unsigned volume of the simplex

    Notes
    -----
    Zero-dimensional simplices (points) are assigned unit volumes.
        

    Examples
    --------
    >>> # 0-simplex point 
    >>> unsigned_volume( [[0,0]] )
    1.0
    >>> # 1-simplex line segment
    >>> unsigned_volume( [[0,0],[1,0]] )             
    1.0
    >>> # 2-simplex triangle 
    >>> unsigned_volume( [[0,0,0],[0,1,0],[1,0,0]] ) 
    0.5


    References
    ----------
    [1] http://www.math.niu.edu/~rusin/known-math/97/volumes.polyh

    """       
    
    pts = asarray(pts)
    
    M,N = pts.shape
    M -= 1

    if M < 0 or M > N:
        raise ValueError('array has invalid shape')
    
    if M == 0:
        return 1.0 
        
    A = pts[1:] - pts[0]
    return sqrt(det(inner(A,A)))/factorial(M)
示例#35
0
def barycentric_gradients(pts):
    """
    Compute the gradients of the barycentric basis functions over a given simplex
    """            
    V = asarray(pts[1:] - pts[0])
    
    ##all gradients except the first are computed
    grads = dot(inv(inner(V,V)),V) #safer, but slower: grads = scipy.linalg.pinv2(V).T 
    
    ##since sum of all gradients is zero, simply compute the first from the others        
    return vstack((atleast_2d(-numpy.sum(grads,axis=0)),grads))
 def get_data(self, str_name):
     try:
         self.image_data=numpy.array(str_name)
         self.image_data=sp.inner(self.image_data, [299, 587, 114])/1000.0
         std_deviation=self.image_data.std()
         if std_deviation==0.0:
             return 103
         return ((self.image_data-self.image_data.mean())/std_deviation)
     except Exception, e:
         flash("failed:"+str(e))
         return 104
 def get_data(self, str_name):
     try:
         self.image_data = numpy.array(str_name)
         self.image_data = sp.inner(self.image_data,
                                    [299, 587, 114]) / 1000.0
         std_deviation = self.image_data.std()
         if std_deviation == 0.0:
             return 103
         return ((self.image_data - self.image_data.mean()) / std_deviation)
     except Exception, e:
         flash("failed:" + str(e))
         return 104
 def get_data(self, str_name):
     try:
         self.image_data=numpy.array(str_name)
         self.image_data=sp.inner(self.image_data, [299, 587, 114])/1000.0
         std_deviation=self.image_data.std()
         if std_deviation==0.0:
             print "\nImage error! Please retry!\n"
             exit()
         return ((self.image_data-self.image_data.mean())/std_deviation)
     except:
         print "\nAwwh, somethings not right! Try again\n"
         exit()
示例#39
0
    def k_nearest_neighbors(self,data,nsamples,k=1):
        kneighbors = []
        dtype = [('index', int), ('distance', float)]
        #k = k if k < nsamples else int(nsamples/2)+1
        for j in range(nsamples):
            sample = data[j]
            distances = np.array([(i, scipy.inner(sample-data[i],sample-data[i])) for i in range(len(data))],dtype=dtype)
            distances.sort(order='distance')
            kneighbors.append(distances[1:k+1])
            #print repr(kneighbors)

        return kneighbors
示例#40
0
def get(i):
    data = cv2.imread('im%s.jpg' % i)
    img = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
    short_edge = min(img.shape[0], img.shape[1])
    #                 print(short_edge)
    yy = int((img.shape[0] - short_edge) // 2)
    xx = int((img.shape[1] - short_edge) // 2)
    img = img[yy: yy + short_edge, xx: xx + short_edge]
    # 缩放图片统一尺寸
    img = cv2.resize(img, (160, 160))
    img = sp.inner(img, [299, 587, 114]) / 1000.0
    print('done')
    return (img - img.mean()) / img.std()
示例#41
0
def initialize(X, K):
    C = [X[0]]
    for k in range(1, K):
        D2 = scipy.array([min([scipy.inner(c-x, c-x) for c in C]) for x in X])
        probs = D2/D2.sum()
        cumprobs = probs.cumsum()
        r = scipy.rand()
        for j, p in enumerate(cumprobs):
            if r < p:
                i = j
                break
        C.append(X[i])
    return C
示例#42
0
def get(file_name):
	
	# get JPG image as Scipy array, RGB (3 layer)
	data = Image.open(file_name + '.png')
	data.save(file_name + '.jpg')

	data = imread(file_name + '.jpg')

	# convert to grey-scale using W3C luminance calc
	data = scipy.inner(data, [299, 587, 114]) / 1000.0

	# normalize per http://en.wikipedia.org/wiki/Cross-correlation
	return (data - data.mean()) / data.std()
示例#43
0
def get(file_name):

    # get JPG image as Scipy array, RGB (3 layer)
    data = Image.open(file_name + '.png')
    data.save(file_name + '.jpg')

    data = imread(file_name + '.jpg')

    # convert to grey-scale using W3C luminance calc
    data = scipy.inner(data, [299, 587, 114]) / 1000.0

    # normalize per http://en.wikipedia.org/wiki/Cross-correlation
    return (data - data.mean()) / data.std()
def onMouseFrameViewer(event, _x, _y, flags, param):
    x = _x/SHOW_IMAGE_SCALE
    y = _y/SHOW_IMAGE_SCALE    
    
    if event == cv2.EVENT_MOUSEMOVE:
        return
    if event == cv2.EVENT_RBUTTONDOWN:
        return
    if event == cv2.EVENT_LBUTTONDOWN:
        #print "clicked point : " + str(x) + "," + str(y)
        global curKeypoint2DLists
        global curKeypointIdLists
        if len(curKeypoint2DLists)>0:
            query = np.array([x,y])
            nearestIndex = scipy.argmin([scipy.inner(query-point,query-point) for point in curKeypoint2DLists])
            nearest = curKeypoint2DLists[nearestIndex]
            if (math.sqrt(scipy.inner(query-nearest,query-nearest)) < THRESHOLD_FIND_CLICKED_KEYPOINT):
                #print "selected point index : " + str(nearestIndex)
                #print "selected point id : " + str(curKeypointIdLists[nearestIndex])
                #print "selected point : " + str(nearest[0]) + "," + str(nearest[1])
                showPointViewer(curKeypointIdLists[nearestIndex])
        return
示例#45
0
def collectX(X, K):
    C = [X[0]]
    for k in range(1, K):
        D2 = scipy.array([min([scipy.inner(c-x,c-x) for c in C]) for x in X])
        probs = D2/D2.sum()
        cumprobs = probs.cumsum()
        r = scipy.rand()
        for j,p in enumerate(cumprobs):
            if r < p:
                i = j
                break
        C.append(X[i])
    return C    
 def get_data(self, str_name):
     try:
         self.image_data = numpy.array(str_name)
         self.image_data = sp.inner(self.image_data,
                                    [299, 587, 114]) / 1000.0
         std_deviation = self.image_data.std()
         if std_deviation == 0.0:
             print "\nImage error! Please retry!\n"
             exit()
         return ((self.image_data - self.image_data.mean()) / std_deviation)
     except:
         print "\nAwwh, somethings not right! Try again\n"
         exit()
示例#47
0
def initk(X_train, k):
    C = [X_train[0]]
    for i in range(1, k):
        D2 = scipy.array(
            [min([scipy.inner(c - x, c - x) for c in C]) for x in X_train])
        probs = D2 / D2.sum()
        cumprobs = probs.cumsum()
        r = scipy.rand()
        for j, p in enumerate(cumprobs):
            if r < p:
                i = j
                break
        C.append(X_train[i])
    return C
示例#48
0
def extract_features(image_path_list):
    feature_list = []
    for image_path in image_path_list:
        image_array = imread(image_path)
        img_size = image_array.size
        red_channel_mean= image_array[...,0].mean()
        green_channel_mean= image_array[...,1].mean()
        blue_channel_mean= image_array[...,2].mean()
        red_channel_sd= image_array[...,0].std()
        green_channel_sd= image_array[...,1].std()
        blue_channel_sd= image_array[...,2].std()

        #Calculating grayscale value
        imgarray1_gray = sp.inner(image_array, [299, 587, 114])
        #Location x and y treated as different features
        max_gray_x_loc = np.argwhere(imgarray1_gray.max() == imgarray1_gray)[...,0].mean()
        max_gray_y_loc = np.argwhere(imgarray1_gray.max() == imgarray1_gray)[...,1].mean()
        min_gray_x_loc = np.argwhere(imgarray1_gray.min() == imgarray1_gray)[...,0].mean()
        min_gray_y_loc = np.argwhere(imgarray1_gray.min() == imgarray1_gray)[...,1].mean()
        min_gray_x_loc_std = np.argwhere(imgarray1_gray.min() == imgarray1_gray)[...,0].std()
        min_gray_y_loc_std = np.argwhere(imgarray1_gray.min() == imgarray1_gray)[...,1].std()
        max_gray_x_loc_std = np.argwhere(imgarray1_gray.max() == imgarray1_gray)[...,0].std()
        max_gray_y_loc_std = np.argwhere(imgarray1_gray.max() == imgarray1_gray)[...,1].std()
        
        imgarray1_gray = np.array(imgarray1_gray, dtype=np.float64)
        edges = sobel(imgarray1_gray)
        edges_height = edges.shape[0]
        edges_width = edges.shape[1]
        
        
        feature_list.append([image_path.split("/")[-2],image_path.split("/")[-1], 
                             img_size,
                             red_channel_mean,
                             green_channel_mean,
                             blue_channel_mean,
                             red_channel_sd,
                             green_channel_sd,
                             blue_channel_sd,
                             max_gray_x_loc,
                             max_gray_y_loc,
                             min_gray_x_loc,
                             min_gray_y_loc,
                             max_gray_x_loc_std,
                             max_gray_y_loc_std,
                             min_gray_x_loc_std,
                             min_gray_y_loc_std,
                             edges_height,
                             edges_width                              
                             ])
    return feature_list
示例#49
0
def angle(v1, v2=None):
    """Compute angle between 2D vectors v1 and v2.

    If v2 is not specified it will default
    to e1 (the unit vector in the x-direction)

    The angle is measured as a number in [0, 2pi] from v2 to v1.
    """
    from math import acos, pi, sqrt

    # Prepare two Numeric vectors
    if v2 is None:
        v2 = [1.0, 0.0]  # Unit vector along the x-axis

    v1 = ensure_numeric(v1, float)
    v2 = ensure_numeric(v2, float)

    # Normalise
    v1 = v1 / sqrt(sum(v1 ** 2))
    v2 = v2 / sqrt(sum(v2 ** 2))

    # Compute angle
    p = inner(v1, v2)
    c = inner(v1, normal_vector(v2))  # Projection onto normal
                                            # (negative cross product)

    theta = acos(p)

    # Correct if v1 is in quadrant 3 or 4 with respect to v2 (as the x-axis)
    # If v2 was the unit vector [1,0] this would correspond to the test
    # if v1[1] < 0: theta = 2*pi-theta
    # In general we use the sign of the projection onto the normal.
    if c < 0:
        # Quadrant 3 or 4
        theta = 2 * pi - theta

    return theta
示例#50
0
文件: td.py 项目: hbhzwj/librl
    def critic(self, lastreward, lastfeature, reward, feature):
        if self.enableOnlyEssentialFeatureInCritic:
            lastfeature = self.module.decodeFeature(lastfeature, self.essentialFeature)
            feature = self.module.decodeFeature(feature, self.essentialFeature)

        # Estimate of avg reward.
        rweight = self.rdecay * self.gamma()
        self.alpha = (1 - rweight) * self.alpha + rweight * reward

        # Update critic parameter
        self.d = lastreward - self.alpha + scipy.inner(self.r, feature - lastfeature)
        self.r += self.gamma() * self.d * self.z

        # Update eligiblity trace
        self.z = self.tracestepsize * self.z + feature
示例#51
0
 def getLabels_ij(self):
     '''
     gets labels for each state/curve in terms of mi,mj
     '''
     self.diagonalize(self.FINE_STRUCTURE_SEPARATION_FIELD)
     j = []
     self.sorted_ijstates = []
     for i in self.indices:#scipy.sort(self.indices):
         vj = scipy.inner(self.cg_coef,self.evecs[i])
         ji = scipy.argmax(vj*vj)
         mi,mj = self.jstates[ji]
         self.sorted_ijstates.append((mi,mj))
         s = '%d:: mi,mj = %s = %.1f'%(i,self.jstates[ji],mi+mj)
         j.append(s)
     return j
示例#52
0
def rgb2CIELAB(RGB):
    def f(t):
        if t>(6/29)**3:
            return t**(1/3)
        else:
            return t*(1/3)*(29/6)**2 + (4/29)
            
    b = scipy.array([[.49,.31,.2],[.17697,.81240,.01063],[0.0,.01,.99]])/.17697
    X,Y,Z = scipy.inner(b,scipy.array(RGB))
    Xn,Yn,Zn = [95.047,100,108.883]
    
    L = 116*f(Y/Yn)-16
    a = 500*(f(X/Xn)-f(Y/Yn))
    b = 200*(f(Y/Yn)-f(Z/Zn))
    
    return scipy.array([L,a,b])
def get(i, gauss):
    # get JPG image as Scipy array, RGB (3 layer)
    data = imread(i)

    print 'image', i, 'read'

    # convert to grey-scale using W3C luminance calc
    data = sp.inner(data, [299, 587, 114]) / 1000.0

    print 'image converted to grey-scale'

    if gauss:
        data = ndimage.gaussian_filter(data, 4)
        print 'image smoothed'
        imsave(i + '_gauss.png', data)
    # normalize per http://en.wikipedia.org/wiki/Cross-correlation
    return (data - data.mean()) / data.std()
示例#54
0
 def Aq(self, A, q):
     """
     Aq simply returns the product of A on q.  This method is included to 
     simplify customizing this feature.  It currently adds a noise 
     proportional to self.Noise.
     """
     if self.Noise != 0:
         if self.NoiseShape == 'normal':
             NoiseVector = scipy.stats.norm(0,self.Noise).rvs(len(q))
         elif self.NoiseShape == 'uniform':
             NoiseVector = scipy.stats.uniform(-self.Noise/2.0, self.Noise).rvs(len(q))
         else: 
             raise Errors.NoiseShapeError(
                     "NoiseShape unknown.  Please add NoiseShape to code.")
     else:
         NoiseVector = 0.0
     return scipy.inner(A, q) + NoiseVector
示例#55
0
def cov(x, y=None):
    """Covariance of vectors x and y.

    If y is None: return cov(x, x)
    """

    if y is None:
        y = x

    assert(len(x) == len(y))
    N = len(x)

    cx = x - mean(x)
    cy = y - mean(y)

    p = inner(cx, cy) / N
    return(p)
def st_inner(
        a, b, smoothing_filter, sampling_rate,
        filter_area_fraction=sigproc.default_kernel_area_fraction):
    """ Calculates the inner product of spike trains given a smoothing
    filter.

    Let :math:`v_a(t)` and :math:`v_b(t)` with :math:`t \\in \\mathcal{T}` be
    the spike trains convolved with some smoothing filter. Then, the inner
    product of the spike trains is defined as :math:`\\int_{\\mathcal{T}}
    v_a(t)v_b(t) dt`.

    Further information can be found in *Paiva, A. R. C., Park, I., & Principe,
    J. (2010). Inner products for representation and learning in the spike
    train domain. Statistical Signal Processing for Neuroscience and
    Neurotechnology, Academic Press, New York.*

    :param sequence a: Sequence of :class:`neo.core.SpikeTrain` objects.
    :param sequence b: Sequence of :class:`neo.core.SpikeTrain` objects.
    :param smoothing_filter: A smoothing filter to be convolved with the spike
        trains.
    :type smoothing_filter: :class:`.signal_processing.Kernel`
    :param sampling_rate: The sampling rate which will be used to bin
        the spike train as inverse time scalar.
    :type sampling_rate: Quantity scalar
    :param float filter_area_fraction: A value between 0 and 1 which controls
        the interval over which the `smoothing_filter` will be discretized. At
        least the given fraction of the complete `smoothing_filter` area will be
        covered. Higher values can lead to more accurate results (besides the
        sampling rate).
    :returns: Matrix containing the inner product for each pair of spike trains
        with one spike train from `a` and the other one from `b`.
    :rtype: Quantity 2D with units depending on the smoothing filter (usually
        temporal frequency units)
    """

    if all((x is y for x, y in zip(a, b))):
        convolved, sampling_rate = _prepare_for_inner_prod(
            a, smoothing_filter, sampling_rate, filter_area_fraction)
        convolved = convolved + convolved
    else:
        convolved, sampling_rate = _prepare_for_inner_prod(
            a + b, smoothing_filter, sampling_rate, filter_area_fraction)
    return (sp.inner(convolved[:len(a)], convolved[len(a):]) *
            convolved[0].units * convolved[1].units / sampling_rate)