Python numpy.mgrid() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def get_points():

    # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
    objp = np.zeros((6*8,3), np.float32)
    objp[:,:2] = np.mgrid[0:8, 0:6].T.reshape(-1 , 2)

    # Arrays to store object points and image points from all the images.
    objpoints = [] # 3d points in real world space
    imgpoints = [] # 2d points in image plane.

    # Make a list of calibration images
    images = glob.glob('calibration_wide/GO*.jpg')

    # Step through the list and search for chessboard corners
    for idx, fname in enumerate(images):
        img = cv2.imread(fname)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # Find the chessboard corners
        ret, corners = cv2.findChessboardCorners(gray, (8,6), None)

        # If found, add object points, image points
        if ret == True:
            objpoints.append(objp)
            imgpoints.append(corners)

            # Draw and display the corners
            cv2.drawChessboardCorners(img, (8,6), corners, ret)
            #write_name = 'corners_found'+str(idx)+'.jpg'
            #cv2.imwrite(write_name, img)
            cv2.imshow('img', img)
            cv2.waitKey(500)

    cv2.destroyAllWindows()
    return objpoints, imgpoints 

Example 2

def find_points(images):
    pattern_size = (9, 6)
    obj_points = []
    img_points = []

    # Assumed object points relation
    a_object_point = np.zeros((PATTERN_SIZE[1] * PATTERN_SIZE[0], 3),
                              np.float32)
    a_object_point[:, :2] = np.mgrid[0:PATTERN_SIZE[0],
                                     0:PATTERN_SIZE[1]].T.reshape(-1, 2)

    # Termination criteria for sub pixel corners refinement
    stop_criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER,
                     30, 0.001)

    print('Finding points ', end='')
    debug_images = []
    for (image, color_image) in images:
        found, corners = cv.findChessboardCorners(image, PATTERN_SIZE, None)
        if found:
            obj_points.append(a_object_point)
            cv.cornerSubPix(image, corners, (11, 11), (-1, -1), stop_criteria)
            img_points.append(corners)

            print('.', end='')
        else:
            print('-', end='')

        if DEBUG:
            cv.drawChessboardCorners(color_image, PATTERN_SIZE, corners, found)
            debug_images.append(color_image)

        sys.stdout.flush()

    if DEBUG:
        display_images(debug_images, DISPLAY_SCALE)

    print('\nWas able to find points in %s images' % len(img_points))
    return obj_points, img_points


# images is a lis of tuples: (gray_image, color_image) 

Example 3

def draw_flow(img, flow, step=16):
    h, w = img.shape[:2]
    y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1)
    fx, fy = flow[y,x].T
    m = np.bitwise_and(np.isfinite(fx), np.isfinite(fy))
    lines = np.vstack([x[m], y[m], x[m]+fx[m], y[m]+fy[m]]).T.reshape(-1, 2, 2)
    lines = np.int32(lines + 0.5)
    vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.polylines(vis, lines, 0, (0, 255, 0))
    for (x1, y1), (x2, y2) in lines:
        cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
    return vis 

Example 4

def draw_flow(img, flow, step=8):
    h, w = img.shape[:2]
    y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1).astype(int)
    fx, fy = flow[y,x].T
    lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)
    lines = np.int32(lines + 0.5)
    vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.polylines(vis, lines, 0, (0, 255, 0))
    for (x1, y1), (x2, y2) in lines:
        cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
    return vis

#####################################################################

# define video capture object 

Example 5

def calculateExtrinsics(self, cameraParameters):
        '''
        Inputs:
        cameraParameters is CameraParameters object

        Calculate: rotate vector and transform vector

        >>> marker.calculateExtrinsics(camera_matrix, dist_coeff)
        >>> print(marker.rvec, marker.tvec)
        '''
        object_points = np.zeros((4,3), dtype=np.float32)
        object_points[:,:2] = np.mgrid[0:2,0:2].T.reshape(-1,2)
        # Test Code.
        # object_points[:] -= 0.5
        marker_points = self.corners
        if marker_points is None: raise TypeError('The marker.corners is None')
        camera_matrix = cameraParameters.camera_matrix
        dist_coeff = cameraParameters.dist_coeff
        ret, rvec, tvec = cv2.solvePnP(object_points, marker_points,
                                       camera_matrix, dist_coeff)
        if ret: self.rvec, self.tvec = rvec, tvec
        return ret 

Example 6

def __init__(self, pos, size):
        """
        pos is (...,3) array of the bar positions (the corner of each bar)
        size is (...,3) array of the sizes of each bar
        """
        nCubes = reduce(lambda a,b: a*b, pos.shape[:-1])
        cubeVerts = np.mgrid[0:2,0:2,0:2].reshape(3,8).transpose().reshape(1,8,3)
        cubeFaces = np.array([
            [0,1,2], [3,2,1],
            [4,5,6], [7,6,5],
            [0,1,4], [5,4,1],
            [2,3,6], [7,6,3],
            [0,2,4], [6,4,2],
            [1,3,5], [7,5,3]]).reshape(1,12,3)
        size = size.reshape((nCubes, 1, 3))
        pos = pos.reshape((nCubes, 1, 3))
        verts = cubeVerts * size + pos
        faces = cubeFaces + (np.arange(nCubes) * 8).reshape(nCubes,1,1)
        md = MeshData(verts.reshape(nCubes*8,3), faces.reshape(nCubes*12,3))
        
        GLMeshItem.__init__(self, meshdata=md, shader='shaded', smooth=False) 

Example 7

def __init__(self, pos, size):
        """
        pos is (...,3) array of the bar positions (the corner of each bar)
        size is (...,3) array of the sizes of each bar
        """
        nCubes = reduce(lambda a,b: a*b, pos.shape[:-1])
        cubeVerts = np.mgrid[0:2,0:2,0:2].reshape(3,8).transpose().reshape(1,8,3)
        cubeFaces = np.array([
            [0,1,2], [3,2,1],
            [4,5,6], [7,6,5],
            [0,1,4], [5,4,1],
            [2,3,6], [7,6,3],
            [0,2,4], [6,4,2],
            [1,3,5], [7,5,3]]).reshape(1,12,3)
        size = size.reshape((nCubes, 1, 3))
        pos = pos.reshape((nCubes, 1, 3))
        verts = cubeVerts * size + pos
        faces = cubeFaces + (np.arange(nCubes) * 8).reshape(nCubes,1,1)
        md = MeshData(verts.reshape(nCubes*8,3), faces.reshape(nCubes*12,3))
        
        GLMeshItem.__init__(self, meshdata=md, shader='shaded', smooth=False) 

Example 8

def make3dplot(ax, sample, density):
    ax.scatter(sample[:,0], sample[:,1], zdir='z')
    ax.set_aspect('equal', 'datalim')

    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    gridsize=50
    xs, ys = np.mgrid[xlim[0]:xlim[1]:(xlim[1]-xlim[0])/float(gridsize), ylim[0]:ylim[1]:(ylim[1]-ylim[0])/float(gridsize)]
    pos = np.empty(xs.shape + (2,))
    pos[:, :, 0] = xs; pos[:, :, 1] = ys

    zs = density(pos)

    surf = ax.plot_surface(xs, ys, zs, rstride=1, cstride=1, linewidth=0, antialiased=False, alpha=.3)

    ax.set_xlabel('x')
    ax.set_ylabel('y') 

Example 9

def nufft_T(N, J, K, alpha, beta):
    '''
     equation (29) and (26)Fessler's paper
     create the overlapping matrix CSSC (diagonal dominent matrix)
     of J points
     and then find out the pseudo-inverse of CSSC '''

#     import scipy.linalg
    L = numpy.size(alpha) - 1
#     print('L = ', L, 'J = ',J, 'a b', alpha,beta )
    cssc = numpy.zeros((J, J))
    [j1, j2] = numpy.mgrid[1:J + 1, 1:J + 1]
    overlapping_mat = j2 - j1

    for l1 in range(-L, L + 1):
        for l2 in range(-L, L + 1):
            alf1 = alpha[abs(l1)]
#             if l1 < 0: alf1 = numpy.conj(alf1)
            alf2 = alpha[abs(l2)]
#             if l2 < 0: alf2 = numpy.conj(alf2)
            tmp = overlapping_mat + beta * (l1 - l2)

            tmp = dirichlet(1.0 * tmp / (1.0 * K / N))
            cssc = cssc + alf1 * numpy.conj(alf2) * tmp
    return mat_inv(cssc) 

Example 10

def nufft_T(N, J, K, alpha, beta):
    '''
     The Equation (29) and (26) in Fessler and Sutton 2003.
     Create the overlapping matrix CSSC (diagonal dominent matrix)
     of J points and find out the pseudo-inverse of CSSC '''

#     import scipy.linalg
    L = numpy.size(alpha) - 1
#     print('L = ', L, 'J = ',J, 'a b', alpha,beta )
    cssc = numpy.zeros((J, J))
    [j1, j2] = numpy.mgrid[1:J + 1, 1:J + 1]
    overlapping_mat = j2 - j1
    for l1 in range(-L, L + 1):
        for l2 in range(-L, L + 1):
            alf1 = alpha[abs(l1)]
#             if l1 < 0: alf1 = numpy.conj(alf1)
            alf2 = alpha[abs(l2)]
#             if l2 < 0: alf2 = numpy.conj(alf2)
            tmp = overlapping_mat + beta * (l1 - l2)

            tmp = dirichlet(1.0 * tmp / (1.0 * K / N))
            cssc = cssc + alf1 * alf2 * tmp
       
    return mat_inv(cssc) 

Example 11

def x_frame2D(X, plot_limits=None, resolution=None):
    """
    Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits
    """

    assert X.shape[1] == 2, \
        'x_frame2D is defined for two-dimensional inputs'
    if plot_limits is None:
        (xmin, xmax) = (X.min(0), X.max(0))
        (xmin, xmax) = (xmin - 0.2 * (xmax - xmin), xmax + 0.2 * (xmax
                        - xmin))
    elif len(plot_limits) == 2:
        (xmin, xmax) = plot_limits
    else:
        raise ValueError, 'Bad limits for plotting'

    resolution = resolution or 50
    (xx, yy) = np.mgrid[xmin[0]:xmax[0]:1j * resolution, xmin[1]:
                        xmax[1]:1j * resolution]
    Xnew = np.vstack((xx.flatten(), yy.flatten())).T
    return (Xnew, xx, yy, xmin, xmax) 

Example 12

def test_pdf(self):
        '''
        Tests the probability density function.
        '''
        # Calculate probability density function on lattice
        bnds = np.empty((3), dtype=object)
        bnds[0] = [-1, 1]
        bnds[1] = [0, 2]
        bnds[2] = [0.5, 2]
        (x0g, x1g, x2g) = np.mgrid[bnds[0][0]:bnds[0][1],
                                   bnds[1][0]:bnds[1][1],
                                   bnds[2][0]:bnds[2][1]]
        points = np.array([x0g.ravel(), x1g.ravel(), x2g.ravel()]).T
        r_logpdf = np.array([-6.313469, -17.406428, -4.375992, -6.226508,
                             -8.836115, -20.430739, -5.107053, -6.687987])
        p_logpdf = self.vine.logpdf(points)
        assert_allclose(p_logpdf, r_logpdf)
        r_pdf = np.array([1.811738e-03, 2.757302e-08, 1.257566e-02,
                          1.976342e-03, 1.453865e-04, 1.339808e-09,
                          6.053895e-03, 1.245788e-03])
        p_pdf = self.vine.pdf(points)
        assert_allclose(p_pdf, r_pdf, rtol=1e-5) 

Example 13

def plotImage(dta, saveFigName):
    plt.clf()
    dx, dy = 1, 1
    # generate 2 2d grids for the x & y bounds
    with np.errstate(invalid='ignore'):
        y, x = np.mgrid[
            slice(0, len(dta)   , dx),
            slice(0, len(dta[0]), dy)
        ]
        z = dta
        z_min, z_max = -np.abs(z).max(), np.abs(z).max()

        #try:
        c = plt.pcolormesh(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max)
        #except ??? as err:  # data not regular?
        #   c = plt.pcolor(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max)
        d = plt.colorbar(c, orientation='vertical')
        lx = plt.xlabel("index")
        ly = plt.ylabel("season length")
        plt.savefig(str(saveFigName)) 

Example 14

def areaxy(self, lowerbound=-np.inf, upperbound=np.inf, spacing=0.1):
        mask = (self.coord[:,2] > lowerbound) & (self.coord[:,2] < upperbound)
        points = self.coord[mask, :2]
        # The magic number factor 1.1 is not critical at all
        # Just a number to set a margin to the bounding box and 
        # have all points fall within the boundaries
        bbmin, bbmax = 1.1*points.min(axis=0), 1.1*points.max(axis=0)
        size = bbmax - bbmin
        cells = (size / spacing + 0.5).astype('int')
        # Grid points over bounding box with specified spacing
        grid = np.mgrid[bbmin[0]:bbmax[0]:(cells[0]*1j),
                        bbmin[1]:bbmax[1]:(cells[1]*1j)].reshape((2,-1)).T
        # Occupied cells is approximately equal to grid points within
        # gridspacing distance of points
        occupied = occupancy(grid, points, spacing)
        # The occupied area follows from the fraction of occupied
        # cells times the area spanned by the bounding box
        return size[0]*size[1]*sum(occupied > 0)/occupied.size 

Example 15

def generate_hills(width, height, nhills):
    '''
    @param width float, terrain width
    @param height float, terrain height
    @param nhills int, #hills to gen. #hills actually generted is sqrt(nhills)^2
    '''
    # setup coordinate grid
    xmin, xmax = -width/2.0, width/2.0
    ymin, ymax = -height/2.0, height/2.0
    x, y = np.mgrid[xmin:xmax:STEP, ymin:ymax:STEP]
    pos = np.empty(x.shape + (2,))
    pos[:, :, 0] = x; pos[:, :, 1] = y
    
    # generate hilltops
    xm, ym = np.mgrid[xmin:xmax:width/np.sqrt(nhills), ymin:ymax:height/np.sqrt(nhills)]
    mu = np.c_[xm.flat, ym.flat]
    sigma = float(width*height)/(nhills*8)
    for i in range(mu.shape[0]):
        mu[i] = multivariate_normal.rvs(mean=mu[i], cov=sigma)
    
    # generate hills
    sigma = sigma + sigma*np.random.rand(mu.shape[0])
    rvs = [ multivariate_normal(mu[i,:], cov=sigma[i]) for i in range(mu.shape[0]) ]
    hfield = np.max([ rv.pdf(pos) for rv in rvs ], axis=0)
    return x, y, hfield 

Example 16

def joint_density(X, Y, bounds=None):
	"""
Plots joint distribution of variables.
Inherited from method in src/graphics.py module in project 
git://github.com/aflaxman/pymc-example-tfr-hdi.git
	"""
	if bounds:
		X_min, X_max, Y_min, Y_max = bounds
	else:
		X_min = X.min()
		X_max = X.max()
		Y_min = Y.min()
		Y_max = Y.max()

	pylab.plot(X, Y, linestyle='none', marker='o', color='green', mec='green', alpha=.2, zorder=-99)

	gkde = scipy.stats.gaussian_kde([X, Y])
	x,y = pylab.mgrid[X_min:X_max:(X_max-X_min)/25.,Y_min:Y_max:(Y_max-Y_min)/25.]
	z = pylab.array(gkde.evaluate([x.flatten(), y.flatten()])).reshape(x.shape)
	pylab.contour(x, y, z, linewidths=2)

	pylab.axis([X_min, X_max, Y_min, Y_max]) 

Example 17

def hyperball(ndim, radius):
    """Return a binary morphological filter containing pixels within `radius`.

    Parameters
    ----------
    ndim : int
        The number of dimensions of the filter.
    radius : int
        The radius of the filter.

    Returns
    -------
    ball : array of bool, shape [2 * radius + 1,] * ndim
        The required structural element
    """
    size = 2 * radius + 1
    center = [(radius,) * ndim]

    coords = np.mgrid[[slice(None, size),] * ndim].reshape(ndim, -1).T
    distances = np.ravel(spatial.distance_matrix(coords, center))
    selector = distances <= radius

    ball = np.zeros((size,) * ndim, dtype=bool)
    ball.ravel()[selector] = True
    return ball 

Example 18

def _generate_random_grids(self):
        if self.num_grids > 40:
            starter = np.random.randint(0, 20)
            random_sample = np.mgrid[starter:len(self.grids)-1:20j].astype("int32")
            # We also add in a bit to make sure that some of the grids have
            # particles
            gwp = self.grid_particle_count > 0
            if np.any(gwp) and not np.any(gwp[(random_sample,)]):
                # We just add one grid.  This is not terribly efficient.
                first_grid = np.where(gwp)[0][0]
                random_sample.resize((21,))
                random_sample[-1] = first_grid
                mylog.debug("Added additional grid %s", first_grid)
            mylog.debug("Checking grids: %s", random_sample.tolist())
        else:
            random_sample = np.mgrid[0:max(len(self.grids),1)].astype("int32")
        return self.grids[(random_sample,)] 

Example 19

def test_linear_interpolator_2d():
    random_data = np.random.random((64, 64))
    # evenly spaced bins
    fv = dict((ax, v) for ax, v in zip("xyz",
               np.mgrid[0.0:1.0:64j, 0.0:1.0:64j]))
    bfi = lin.BilinearFieldInterpolator(random_data,
            (0.0, 1.0, 0.0, 1.0), "xy", True)
    assert_array_equal(bfi(fv), random_data)

    # randomly spaced bins
    size = 64
    bins = np.linspace(0.0, 1.0, size)
    shifts = dict((ax, (1. / size) * np.random.random(size) - (0.5 / size)) \
                  for ax in "xy")
    fv["x"] += shifts["x"][:, np.newaxis]
    fv["y"] += shifts["y"]
    bfi = lin.BilinearFieldInterpolator(random_data,
            (bins + shifts["x"], bins + shifts["y"]), "xy", True)
    assert_array_almost_equal(bfi(fv), random_data, 15) 

Example 20

def test_linear_interpolator_3d():
    random_data = np.random.random((64, 64, 64))
    # evenly spaced bins
    fv = dict((ax, v) for ax, v in zip("xyz",
               np.mgrid[0.0:1.0:64j, 0.0:1.0:64j, 0.0:1.0:64j]))
    tfi = lin.TrilinearFieldInterpolator(random_data,
            (0.0, 1.0, 0.0, 1.0, 0.0, 1.0), "xyz", True)
    assert_array_almost_equal(tfi(fv), random_data)

    # randomly spaced bins
    size = 64
    bins = np.linspace(0.0, 1.0, size)
    shifts = dict((ax, (1. / size) * np.random.random(size) - (0.5 / size)) \
                  for ax in "xyz")
    fv["x"] += shifts["x"][:, np.newaxis, np.newaxis]
    fv["y"] += shifts["y"][:, np.newaxis]
    fv["z"] += shifts["z"]
    tfi = lin.TrilinearFieldInterpolator(random_data,
            (bins + shifts["x"], bins + shifts["y"], 
             bins + shifts["z"]), "xyz", True)
    assert_array_almost_equal(tfi(fv), random_data, 15) 

Example 21

def partition_index_2d(self, axis):
        if not self._distributed:
           return False, self.index.grid_collection(self.center,
                                                        self.index.grids)

        xax = self.ds.coordinates.x_axis[axis]
        yax = self.ds.coordinates.y_axis[axis]
        cc = MPI.Compute_dims(self.comm.size, 2)
        mi = self.comm.rank
        cx, cy = np.unravel_index(mi, cc)
        x = np.mgrid[0:1:(cc[0]+1)*1j][cx:cx+2]
        y = np.mgrid[0:1:(cc[1]+1)*1j][cy:cy+2]

        DLE, DRE = self.ds.domain_left_edge.copy(), self.ds.domain_right_edge.copy()
        LE = np.ones(3, dtype='float64') * DLE
        RE = np.ones(3, dtype='float64') * DRE
        LE[xax] = x[0] * (DRE[xax]-DLE[xax]) + DLE[xax]
        RE[xax] = x[1] * (DRE[xax]-DLE[xax]) + DLE[xax]
        LE[yax] = y[0] * (DRE[yax]-DLE[yax]) + DLE[yax]
        RE[yax] = y[1] * (DRE[yax]-DLE[yax]) + DLE[yax]
        mylog.debug("Dimensions: %s %s", LE, RE)

        reg = self.ds.region(self.center, LE, RE)
        return True, reg 

Example 22

def init_fill(self):
        rext = 1.0
        Ns = 51
        x, y = np.mgrid[ -rext:rext:1j*Ns, -rext:rext:1j*Ns ]
        z = np.zeros_like(x)
        
        self.controller.ax_xstress.pcolor(x,y,z, cmap=plt.cm.coolwarm)
        self.controller.ax_ystress.pcolor(x,y,z, cmap=plt.cm.coolwarm)
        self.controller.ax_xystress.pcolor(x,y,z, cmap=plt.cm.coolwarm)
        
        self.controller.ax_rstress.pcolor(x,y,z, cmap=plt.cm.coolwarm)
        self.controller.ax_tstress.pcolor(x,y,z, cmap=plt.cm.coolwarm)
        
        return
    
# ======================= 

Example 23

def evaluate_model(self, model):

        """
        This function ...
        :param model:
        :return:
        """

        # Make a local copy of the model so that we can adapt its position to be relative to this box
        rel_model = fitting.shifted_model(model, -self.x_min, -self.y_min)

        # Create x and y meshgrid for evaluating
        y_values, x_values = np.mgrid[:self.ysize, :self.xsize]

        # Evaluate the model
        data = rel_model(x_values, y_values)

        # Return a new box
        return Box(data, self.x_min, self.x_max, self.y_min, self.y_max)

    # ----------------------------------------------------------------- 

Example 24

def evaluate_model(self, model):

        """
        This function ...
        :param model:
        :return:
        """

        # Make a local copy of the model so that we can adapt its position to be relative to this box
        rel_model = fitting.shifted_model(model, -self.x_min, -self.y_min)

        # Create x and y meshgrid for evaluating
        y_values, x_values = np.mgrid[:self.ysize, :self.xsize]

        # Evaluate the model
        data = rel_model(x_values, y_values)

        # Return a new box
        return Box(data, self.x_min, self.x_max, self.y_min, self.y_max)

    # ----------------------------------------------------------------- 

Example 25

def polarToLinearMaps(orig_shape, out_shape=None, center=None):
    s0, s1 = orig_shape
    if out_shape is None:
        out_shape = (int(round(2 * s0 / 2**0.5)) - (1 - s0 % 2),
                     int(round(2 * s1 / (2 * np.pi) / 2**0.5)))
    ss0, ss1 = out_shape

    if center is None:
        center = ss1 // 2, ss0 // 2

    yy, xx = np.mgrid[0:ss0:1., 0:ss1:1.]
    r, phi = _cart2polar(xx, yy, center)
    # scale-pi...pi->0...s1:
    phi = (phi + np.pi) / (2 * np.pi) * (s1 - 2)

    return phi.astype(np.float32), r.astype(np.float32) 

Example 26

def calculateExtrinsics(self, cameraParameters):
        '''
        Inputs:
        cameraParameters is CameraParameters object

        Calculate: rotate vector and transform vector

        >>> marker.calculateExtrinsics(camera_matrix, dist_coeff)
        >>> print(marker.rvec, marker.tvec)
        '''
        object_points = np.zeros((4,3), dtype=np.float32)
        object_points[:,:2] = np.mgrid[0:2,0:2].T.reshape(-1,2)
        # Test Code.
        # object_points[:] -= 0.5
        marker_points = self.corners
        if marker_points is None: raise TypeError('The marker.corners is None')
        camera_matrix = cameraParameters.camera_matrix
        dist_coeff = cameraParameters.dist_coeff
        ret, rvec, tvec = cv2.solvePnP(object_points, marker_points,
                                       camera_matrix, dist_coeff)
        if ret: self.rvec, self.tvec = rvec, tvec
        return ret 

Example 27

def calculateExtrinsics(self, cameraParameters):
        '''
        Inputs:
        cameraParameters is CameraParameters object

        Calculate: rotate vector and transform vector

        >>> marker.calculateExtrinsics(camera_matrix, dist_coeff)
        >>> print(marker.rvec, marker.tvec)
        '''
        object_points = np.zeros((4,3), dtype=np.float32)
        object_points[:,:2] = np.mgrid[0:2,0:2].T.reshape(-1,2)
        # Test Code.
        # object_points[:] -= 0.5
        marker_points = self.corners
        if marker_points is None: raise TypeError('The marker.corners is None')
        camera_matrix = cameraParameters.camera_matrix
        dist_coeff = cameraParameters.dist_coeff
        ret, rvec, tvec = cv2.solvePnP(object_points, marker_points,
                                       camera_matrix, dist_coeff)
        if ret: self.rvec, self.tvec = rvec, tvec
        return ret 

Example 28

def calculateExtrinsics(self, cameraParameters):
        '''
        Inputs:
        cameraParameters is CameraParameters object

        Calculate: rotate vector and transform vector

        >>> marker.calculateExtrinsics(camera_matrix, dist_coeff)
        >>> print(marker.rvec, marker.tvec)
        '''
        object_points = np.zeros((4,3), dtype=np.float32)
        object_points[:,:2] = np.mgrid[0:2,0:2].T.reshape(-1,2)
        # Test Code.
        # object_points[:] -= 0.5
        marker_points = self.corners
        if marker_points is None: raise TypeError('The marker.corners is None')
        camera_matrix = cameraParameters.camera_matrix
        dist_coeff = cameraParameters.dist_coeff
        ret, rvec, tvec = cv2.solvePnP(object_points, marker_points,
                                       camera_matrix, dist_coeff)
        if ret: self.rvec, self.tvec = rvec, tvec
        return ret 

Example 29

def _compute_gaussian_kernel(histogram_shape, relative_bw):
    """Compute a gaussian kernel double the size of the histogram matrix"""
    if len(histogram_shape) == 2:
        kernel_shape = [2 * n for n in histogram_shape]
        # Create a scaled grid in which the kernel is symmetric to avoid matrix
        # inversion problems when the bandwiths are very different
        bw_ratio = relative_bw[0] / relative_bw[1]
        bw = relative_bw[0]
        X, Y = np.mgrid[-bw_ratio:bw_ratio:kernel_shape[0] * 1j,
                        -1:1:kernel_shape[1] * 1j]
        grid_points = np.vstack([X.ravel(), Y.ravel()]).T
        Cov = np.array(((bw, 0), (0, bw)))**2
        K = stats.multivariate_normal.pdf(grid_points, mean=(0, 0), cov=Cov)

        return K.reshape(kernel_shape)
    else:
        grid = np.mgrid[-1:1:histogram_shape[0] * 2j]
        return stats.norm.pdf(grid, loc=0, scale=relative_bw) 

Example 30

def draw_flow(img, flow, step=16):
    h, w = img.shape[:2]
    y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2, -1).astype(int)  # ????????????????????????16?reshape?2??array
    fx, fy = flow[y, x].T  # ???????????????
    lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)  # ????????????2*2???
    lines = np.int32(lines + 0.5)  # ????????????
    vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.polylines(vis, lines, 0, (0, 255, 0))  # ???????????????
    for (x1, y1), (x2, y2) in lines:
        cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)  # ???????????????????
    return vis 

Example 31

def flow2parallax(u,v,q):
    """
    Given the flow fields (after correction!) and the epipole,
    return:
    - The normalized parallax (HxW array)
    - The vectors pointing to the epipoles (HxWx2 array)
    - The distances of all points to the epipole (HxW array)
    """
    h,w = u.shape
    y,x = np.mgrid[:h,:w]

    u_f = q[0] - x
    v_f = q[1] - y

    dists = np.sqrt(u_f**2 + v_f**2)
    u_f_n = u_f / np.maximum(dists,1e-3)
    v_f_n = v_f / np.maximum(dists,1e-3)

    parallax = u * u_f_n + v * v_f_n

    return parallax, np.dstack((u_f_n, v_f_n)), dists 

Example 32

def create_test_dataset(image_shape, n, circle_radius, donut_radius):
    img = np.zeros((image_shape[0], image_shape[1]))
    y_pixels = np.arange(0, image_shape[0], 1)
    x_pixels = np.arange(0, image_shape[1], 1)
    cell_y_coords = np.random.choice(y_pixels, n, replace=False)
    cell_x_coords = np.random.choice(x_pixels, n, replace=False)

    for x, y in zip(cell_x_coords, cell_y_coords):
        xx, yy = np.mgrid[:512, :512]  # create mesh grid of image dimensions
        circle = (xx - x) ** 2 + (yy - y) ** 2  # apply circle formula
        donut = np.logical_and(circle < (circle_radius+donut_radius),
                               circle > (circle_radius-5))  # donuts are thresholded circles
        thresholded_circle = circle < circle_radius
        img[np.where(thresholded_circle)] = 1
        img[np.where(donut)] = 2
    return img 

Example 33

def test_square_grid():
    X = np.mgrid[0:16, 0:16]
    X = X.reshape((len(X), -1)).T

    name = 'square'
    D, Q = test_toy_embedding(X, 32, 2, name, palette='hls')

    def plot_mat_on_data(mat, sample):
        plt.figure()
        plot_data_embedded(X, palette='w')
        alpha = np.maximum(mat[sample], 0) / mat[sample].max()
        plot_data_embedded(X, palette='#FF0000', alpha=alpha)

    pdf_file_name = '{}{}_plot_{}_on_data_{}{}'

    plot_mat_on_data(D, 7 * 16 + 7)
    plt.savefig(pdf_file_name.format(dir_name, name, 'D', 'middle', '.pdf'))
    plot_mat_on_data(Q, 7 * 16 + 7)
    plt.savefig(pdf_file_name.format(dir_name, name, 'Q', 'middle', '.pdf'))

    # for s in range(len(X)):
    #     plot_mat_on_data(Q, s)
    #     plt.savefig(pdf_file_name.format(dir_name, name, 'Q', s, '.png'))
    #     plt.close() 

Example 34

def plot(self, ax, idx1, idx2, range1, range2, n=100):
        assert len(range1) == len(range2) == 2 and idx1 != idx2
        x, y = np.mgrid[range1[0]:range1[1]:(n+0j), range2[0]:range2[1]:(n+0j)]

        if isinstance(self.action_space, ContinuousSpace):
            points_B_Doa = np.zeros((n*n, self.obsfeat_space.storage_size + self.action_space.storage_size))
            points_B_Doa[:,idx1] = x.ravel()
            points_B_Doa[:,idx2] = y.ravel()
            obsfeat_B_Df, a_B_Da = points_B_Doa[:,:self.obsfeat_space.storage_size], points_B_Doa[:,self.obsfeat_space.storage_size:]
            assert a_B_Da.shape[1] == self.action_space.storage_size
            t_B = np.zeros(a_B_Da.shape[0]) # XXX make customizable
            z = self.compute_reward(obsfeat_B_Df, a_B_Da, t_B).reshape(x.shape)
        else:
            obsfeat_B_Df = np.zeros((n*n, self.obsfeat_space.storage_size))
            obsfeat_B_Df[:,idx1] = x.ravel()
            obsfeat_B_Df[:,idx2] = y.ravel()
            a_B_Da = np.zeros((obsfeat_B_Df.shape[0], 1), dtype=np.int32) # XXX make customizable
            t_B = np.zeros(a_B_Da.shape[0]) # XXX make customizable
            z = self.compute_reward(obsfeat_B_Df, a_B_Da, t_B).reshape(x.shape)

        ax.pcolormesh(x, y, z, cmap='viridis')
        ax.contour(x, y, z, levels=np.log(np.linspace(2., 3., 10)))
        # ax.contourf(x, y, z, levels=[np.log(2.), np.log(2.)+.5], alpha=.5) # high-reward region is highlighted 

Example 35

def calculate_scalar_matrix(values_a, values_b):
    """
    convenience function wrapper of py:function:`calculate_scalar_product_matrix` for the case of scalar elements.

    :param values_a:
    :param values_b:
    :return:
    """
    return calculate_scalar_product_matrix(np.multiply,
                                           sanitize_input(values_a, Number),
                                           sanitize_input(values_b, Number))

    # i, j = np.mgrid[0:values_a.shape[0], 0:values_b.shape[0]]
    # vals_i = values_a[i]
    # vals_j = values_b[j]
    # return np.multiply(vals_i, vals_j) 

Example 36

def gabor_2d(M, N, sigma, theta, xi, slant=1.0, offset=0, fft_shift=None):
    gab = np.zeros((M, N), np.complex64)
    R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]], np.float32)
    R_inv = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]], np.float32)
    D = np.array([[1, 0], [0, slant * slant]])
    curv = np.dot(R, np.dot(D, R_inv)) / ( 2 * sigma * sigma)

    for ex in [-2, -1, 0, 1, 2]:
        for ey in [-2, -1, 0, 1, 2]:
            [xx, yy] = np.mgrid[offset + ex * M:offset + M + ex * M, offset + ey * N:offset + N + ey * N]
            arg = -(curv[0, 0] * np.multiply(xx, xx) + (curv[0, 1] + curv[1, 0]) * np.multiply(xx, yy) + curv[
                1, 1] * np.multiply(yy, yy)) + 1.j * (xx * xi * np.cos(theta) + yy * xi * np.sin(theta))
            gab = gab + np.exp(arg)

    norm_factor = (2 * 3.1415 * sigma * sigma / slant)
    gab = gab / norm_factor

    if (fft_shift):
        gab = np.fft.fftshift(gab, axes=(0, 1))
    return gab 

Example 37

def test():

    import PIL.Image

    y, x = np.mgrid[0:256, 0:256]
    z = np.ones((256,256)) * 128
    img0 = np.dstack((x, y, z)).astype(np.uint8)
    img1 = y.astype(np.uint8)
    img2 = np.arange(256, dtype=np.uint8)
    img3 = PIL.Image.open("pics/RGB.png")
    img3 = np.array(img3)[:,:,0:3]
    img4 = PIL.Image.open("pics/banff.jpg")
    img4 = np.array(img4)[:,:,0:3]
    img5, _ = (np.mgrid[0:1242, 0:1276] / 1242. * 255.).astype(np.uint8)
    img6, _ = (np.mgrid[0:1007, 0:12] / 1007. * 255.).astype(np.uint8)

    for i in (1, 2, 4, 8):

        write_tiff("Test0_" + str(i) + ".TIF", img0, bit_depth=i)
        write_tiff("Test1_" + str(i) + ".TIF", img1, bit_depth=i)
        write_tiff("Test2_" + str(i) + ".TIF", img2, bit_depth=i)
        write_tiff("Test3_" + str(i) + ".TIF", img3, bit_depth=i)
        write_tiff("Test4_" + str(i) + ".TIF", img4, bit_depth=i)
        write_tiff("Test5_" + str(i) + ".TIF", img5, bit_depth=i)
        write_tiff("Test6_" + str(i) + ".TIF", img6, bit_depth=i) 

Example 38

def gauss_kernel(size, sigma=None, size_y=None, sigma_y=None):
    """
    Generates a 2D Gaussian kernel as a numpy array
        Args:
            size (int): 1/2 the width of the kernel; total width := 2*size+1
            sigma (float): spread of the gaussian in the width direction
            size_y (int): 1/2 the height of the kernel; defaults to size
            sigma_y (float): spread of the gaussian in the height direction; defaults to sigma
        Returns:
            numpy array: normalized 2D gaussian array
    """
    size = int(size)
    if not size_y:
        size_y = size
    else:
        size_y = int(size_y)
    if not sigma:
        sigma = 0.5 * size + .1
    if not sigma_y:
        sigma_y = sigma
    x, y = np.mgrid[-size:size+1, -size_y:size_y+1]
    g = np.exp(-0.5 * (x ** 2 / sigma ** 2 + y ** 2 / sigma_y ** 2))
    return g / g.sum() 

Example 39

def __init__(self, im, sigma_spatial=12, sigma_luma=4, sigma_chroma=4):
        im_yuv = rgb2yuv(im)
        # Compute 5-dimensional XYLUV bilateral-space coordinates
        Iy, Ix = np.mgrid[:im.shape[0], :im.shape[1]]
        x_coords = (Ix / sigma_spatial).astype(int)
        y_coords = (Iy / sigma_spatial).astype(int)
        luma_coords = (im_yuv[..., 0] /sigma_luma).astype(int)
        chroma_coords = (im_yuv[..., 1:] / sigma_chroma).astype(int)
        coords = np.dstack((x_coords, y_coords, luma_coords, chroma_coords))
        coords_flat = coords.reshape(-1, coords.shape[-1])
        self.npixels, self.dim = coords_flat.shape
        # Hacky "hash vector" for coordinates,
        # Requires all scaled coordinates be < MAX_VAL
        self.hash_vec = (MAX_VAL**np.arange(self.dim))
        # Construct S and B matrix
        self._compute_factorization(coords_flat) 

Example 40

def get_local_mesh(self):
        # Create the mesh
        X = np.mgrid[self.rank*self.Np[0]:(self.rank+1)*self.Np[0], :self.N[1]].astype(self.float)
        X[0] *= self.L[0]/self.N[0]
        X[1] *= self.L[1]/self.N[1]
        return X 

Example 41

def get_local_mesh(self):
        xyrank = self.comm0.Get_rank() # Local rank in xz-plane
        yzrank = self.comm1.Get_rank() # Local rank in xy-plane

        # Create the physical mesh
        x1 = slice(xyrank * self.N1[0], (xyrank+1) * self.N1[0], 1)
        x2 = slice(yzrank * self.N2[1], (yzrank+1) * self.N2[1], 1)
        X = np.mgrid[x1, x2, :self.N[2]].astype(self.float)
        X[0] *= self.L[0]/self.N[0]
        X[1] *= self.L[1]/self.N[1]
        X[2] *= self.L[2]/self.N[2]
        return X 

Example 42

def get_tform_coords(im_size):
    coords0, coords1, coords2 = np.mgrid[:im_size[0], :im_size[1], :im_size[2]]
    coords = np.array([coords0 - im_size[0] / 2, coords1 - im_size[1] / 2, coords2 - im_size[2] / 2])
    return np.append(coords.reshape(3, -1), np.ones((1, np.prod(im_size))), axis=0) 

Example 43

def _FSpecialGauss(size, sigma):
    """Function to mimic the 'fspecial' gaussian MATLAB function."""
    radius = size // 2
    offset = 0.0
    start, stop = -radius, radius + 1
    if size % 2 == 0:
        offset = 0.5
        stop -= 1
    x, y = np.mgrid[offset + start:stop, offset + start:stop]
    assert len(x) == size
    g = np.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2)))
    return g / g.sum() 

Example 44

def replace_field(f, mask):
    """Interpolates positions in field according to mask with a 2D cubic interpolator"""
    lx, ly = f.shape
    x, y = np.mgrid[0:lx, 0:ly]
    C = CT_intp((x[~mask],y[~mask]),f[~mask], fill_value=0)
    return C(x, y) 

Example 45

def get_frame(self, i, j):
        """
        Perform interpolation to produce the deformed window for correlation.

        This function takes the previously set displacement and interpolates the image for these coordinates.
        If the cubic interpolation method is chosen, the cubic interpolation of this API is use.
        For the bilinear method the build in scipy method `map_coordinates <https://goo.gl/wucmUO>`_ is used with *order* set to 1.

        :param int i: first index in grid coordinates
        :param int j: second index in grid coordinates
        :returns: interpolated window for the grid coordinates i,j and the image set in initialization
        """
        dws = self._shape[-1]
        offset_x, offset_y = np.mgrid[-dws/2+0.5:dws/2+0.5, -dws/2+0.5:dws/2+0.5]

        gx, gy = np.mgrid[0:dws, 0:dws]

        grid_x = gx + self._distance*i
        grid_y = gy + self._distance*j

        ptsax = (grid_x + self._u_disp(i, j, offset_x, offset_y)).ravel()
        ptsay = (grid_y + self._v_disp(i, j, offset_x, offset_y)).ravel()
        p, q = self._shape[-2:]

        if self._ipmethod == 'bilinear':
            return map_coordinates(self._frame, [ptsax, ptsay], order=1).reshape(p, q)
        if self._ipmethod == 'cubic':
            return  self._cube_ip.interpolate(ptsax, ptsay).reshape(p, q) 

Example 46

def makeMTX(spat_coeffs, radial_filter, kr_IDX, viz_order=None, stepsize_deg=1):
    """Returns a plane wave decomposition over a full sphere

    Parameters
    ----------
    spat_coeffs : array_like
       Spatial fourier coefficients
    radial_filter : array_like
       Modal radial filters
    kr_IDX : int
       Index of kr to be computed
    viz_order : int, optional
       Order of the spatial fourier transform [Default: Highest available]
    stepsize_deg : float, optional
       Integer Factor to increase the resolution. [Default: 1]

    Returns
    -------
    mtxData : array_like
       Plane wave decomposition (frequency domain)

    Note
    ----
    The file generates a Matrix of 181x360 pixels for the
    visualisation with visualize3D() in 1[deg] Steps (65160 plane waves).
    """

    if not viz_order:
        viz_order = _np.int(_np.ceil(_np.sqrt(spat_coeffs.shape[0]) - 1))

    angles = _np.mgrid[0:360:stepsize_deg, 0:181:stepsize_deg].reshape((2, -1)) * _np.pi / 180
    Y = plane_wave_decomp(viz_order, angles, spat_coeffs[:, kr_IDX], radial_filter[:, kr_IDX])

    return Y.reshape((360, -1)).T  # Return pwd data as [181, 360] matrix 

Example 47

def plot3Dgrid(rows, cols, viz_data, style, normalize=True, title=None):
    if len(viz_data) > rows * cols:
        raise ValueError('Number of plot data is more than the specified rows and columns.')
    fig = tools.make_subplots(rows, cols, specs=[[{'is_3d': True}] * cols] * rows, print_grid=False)

    if style == 'flat':
        layout_3D = dict(
            xaxis=dict(range=[0, 360]),
            yaxis=dict(range=[0, 181]),
            aspectmode='manual',
            aspectratio=dict(x=3.6, y=1.81, z=1)
        )
    else:
        layout_3D = dict(
            xaxis=dict(range=[-1, 1]),
            yaxis=dict(range=[-1, 1]),
            zaxis=dict(range=[-1, 1]),
            aspectmode='cube'
        )

    rows, cols = _np.mgrid[1:rows + 1, 1: cols + 1]
    rows = rows.flatten()
    cols = cols.flatten()
    for IDX in range(0, len(viz_data)):
        cur_row = rows[IDX]
        cur_col = cols[IDX]
        fig.append_trace(genVisual(viz_data[IDX], style=style, normalize=normalize), cur_row, cur_col)
        fig.layout['scene' + str(IDX + 1)].update(layout_3D)

    if title is not None:
        fig.layout.update(title=title)
        filename = title + '.html'
    else:
        filename = str(current_time()) + '.html'

    if env_info() == 'jupyter_notebook':
        plotly_off.iplot(fig)
    else:
        plotly_off.plot(fig, filename=filename) 

Example 48

def gk(c1,r1,c2,r2):
    # First, create X and Y arrays indicating distance to the boundaries of the paintbrush
    # In this current context, im is the ordinal number of pixels (64 typically)
    sigma = 0.3
    im = 64
    x = np.repeat([np.concatenate([np.mgrid[-c1:0],np.zeros(c2-c1),np.mgrid[1:1+im-c2]])],im,axis=0)
    y = np.repeat(np.vstack(np.concatenate([np.mgrid[-r1:0],np.zeros(r2-r1),np.mgrid[1:1+im-r2]])),im,axis=1)
    g = np.exp(-(x**2/float(im)+y**2/float(im))/(2*sigma**2))
    return np.repeat([g],3,axis=0) # remove the 3 if you want to apply this to mask rather than an RGB channel  
# This function reduces the likelihood of a change based on how close each individual pixel is to a maximal value.
# Consider conditioning this based on the gK value and the requested color. I.E. instead of just a flat distance from 128,
# have it be a difference from the expected color at a given location. This could also be used to "weight" the image towards staying the same. 

Example 49

def fcn_FDEM_InductionSpherePlaneWidget(xtx,ytx,ztx,m,orient,x0,y0,z0,a,sig,mur,xrx,yrx,zrx,logf,Comp,Phase):

    sig = 10**sig
    f = 10**logf

    fvec = np.logspace(0,8,41)

    xmin, xmax, dx, ymin, ymax, dy = -30., 30., 0.3, -30., 30., 0.4
    X,Y = np.mgrid[xmin:xmax+dx:dx, ymin:ymax+dy:dy]
    X = np.transpose(X)
    Y = np.transpose(Y)

    Obj = SphereFEM(m,orient,xtx,ytx,ztx)

    Hx,Hy,Hz,Habs = Obj.fcn_ComputeFrequencyResponse(f,sig,mur,a,x0,y0,z0,X,Y,zrx)
    Hxi,Hyi,Hzi,Habsi = Obj.fcn_ComputeFrequencyResponse(fvec,sig,mur,a,x0,y0,z0,xrx,yrx,zrx)

    fig1 = plt.figure(figsize=(17,6))
    Ax1 = fig1.add_axes([0.04,0,0.43,1])
    Ax2 = fig1.add_axes([0.6,0,0.4,1])

    if Comp == 'x':
        Ax1 = plotAnomalyXYplane(Ax1,f,X,Y,ztx,Hx,Comp,Phase)
        Ax1 = plotPlaceTxRxSphereXY(Ax1,xtx,ytx,xrx,yrx,x0,y0,a)
        Ax2 = plotResponseFEM(Ax2,f,fvec,Hxi,Comp)
    elif Comp == 'y':
        Ax1 = plotAnomalyXYplane(Ax1,f,X,Y,ztx,Hy,Comp,Phase)
        Ax1 = plotPlaceTxRxSphereXY(Ax1,xtx,ytx,xrx,yrx,x0,y0,a)
        Ax2 = plotResponseFEM(Ax2,f,fvec,Hyi,Comp)
    elif Comp == 'z':
        Ax1 = plotAnomalyXYplane(Ax1,f,X,Y,ztx,Hz,Comp,Phase)
        Ax1 = plotPlaceTxRxSphereXY(Ax1,xtx,ytx,xrx,yrx,x0,y0,a)
        Ax2 = plotResponseFEM(Ax2,f,fvec,Hzi,Comp)
    elif Comp == 'abs':
        Ax1 = plotAnomalyXYplane(Ax1,f,X,Y,ztx,Habs,Comp,Phase)
        Ax1 = plotPlaceTxRxSphereXY(Ax1,xtx,ytx,xrx,yrx,x0,y0,a)
        Ax2 = plotResponseFEM(Ax2,f,fvec,Habsi,Comp)

    plt.show(fig1) 

Example 50

def rebin(a, newshape):
    """Rebin an array to a new shape."""
    assert len(a.shape) == len(newshape)

    slices = [slice(0, old, float(old) / new)
              for old, new in zip(a.shape, newshape)]
    coordinates = np.mgrid[slices]
    indices = coordinates.astype('i')
    return a[tuple(indices)] 
点赞