當前位置: 首頁>>代碼示例>>Python>>正文


Python torch.meshgrid方法代碼示例

本文整理匯總了Python中torch.meshgrid方法的典型用法代碼示例。如果您正苦於以下問題:Python torch.meshgrid方法的具體用法?Python torch.meshgrid怎麽用?Python torch.meshgrid使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在torch的用法示例。


在下文中一共展示了torch.meshgrid方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: grid_anchors

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def grid_anchors(self, grid_sizes):
        anchors = []
        for size, stride, base_anchors in zip(
            grid_sizes, self.strides, self.cell_anchors
        ):
            grid_height, grid_width = size
            device = base_anchors.device
            shifts_x = torch.arange(
                0, grid_width * stride, step=stride, dtype=torch.float32, device=device
            )
            shifts_y = torch.arange(
                0, grid_height * stride, step=stride, dtype=torch.float32, device=device
            )
            shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)
            shift_x = shift_x.reshape(-1)
            shift_y = shift_y.reshape(-1)
            shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1)

            anchors.append(
                (shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4)
            )

        return anchors 
開發者ID:Res2Net,項目名稱:Res2Net-maskrcnn,代碼行數:25,代碼來源:anchor_generator.py

示例2: grid_anchors

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def grid_anchors(self, grid_sizes):
        anchors = []
        for size, stride, base_anchors in zip(grid_sizes, self.strides, self.cell_anchors):
            grid_height, grid_width = size
            device = base_anchors.device
            shifts_x = torch.arange(
                0, grid_width * stride, step=stride, dtype=torch.float32, device=device
            )
            shifts_y = torch.arange(
                0, grid_height * stride, step=stride, dtype=torch.float32, device=device
            )
            shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)
            shift_x = shift_x.reshape(-1)
            shift_y = shift_y.reshape(-1)
            shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1)

            anchors.append(
                (shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4)
            )

        return anchors 
開發者ID:soeaver,項目名稱:Parsing-R-CNN,代碼行數:23,代碼來源:anchor_generator.py

示例3: __init__

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def __init__(self, W, H, device, dtype=torch.float): # pylint: disable=E1101
    """
    Parameters
    ----------
      W : int
        width of the image.
      H : int
        height of the image.
      device : device
        computation device (cpu/cuda).
    """
    super(backWarp, self).__init__()
    # create a grid
    gridX, gridY = torch.meshgrid(torch.arange(W), torch.arange(H)) # pylint: disable=E1101
    self.W = W
    self.H = H
    self.gridX = gridX.t().to(dtype=dtype, device=device) # pylint: disable=E1101
    self.gridY = gridY.t().to(dtype=dtype, device=device) # pylint: disable=E1101 
開發者ID:opteroncx,項目名稱:MoePhoto,代碼行數:20,代碼來源:slomo.py

示例4: flow_warp

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def flow_warp(x, flow, interp_mode='bilinear', padding_mode='zeros'):
    """Warp an image or feature map with optical flow
    Args:
        x (Tensor): size (N, C, H, W)
        flow (Tensor): size (N, H, W, 2), normal value
        interp_mode (str): 'nearest' or 'bilinear'
        padding_mode (str): 'zeros' or 'border' or 'reflection'

    Returns:
        Tensor: warped image or feature map
    """
    assert x.size()[-2:] == flow.size()[1:3]
    B, C, H, W = x.size()
    # mesh grid
    grid_y, grid_x = torch.meshgrid(torch.arange(0, H), torch.arange(0, W))
    grid = torch.stack((grid_x, grid_y), 2).float()  # W(x), H(y), 2
    grid.requires_grad = False
    grid = grid.type_as(x)
    vgrid = grid + flow
    # scale grid to [-1,1]
    vgrid_x = 2.0 * vgrid[:, :, :, 0] / max(W - 1, 1) - 1.0
    vgrid_y = 2.0 * vgrid[:, :, :, 1] / max(H - 1, 1) - 1.0
    vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3)
    output = F.grid_sample(x, vgrid_scaled, mode=interp_mode, padding_mode=padding_mode)
    return output 
開發者ID:xinntao,項目名稱:BasicSR,代碼行數:27,代碼來源:module_util.py

示例5: rfftfreqs

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def rfftfreqs(res, dtype=torch.float32, exact=True):
    """
    Helper function to return frequency tensors
    :param res: n_dims int tuple of number of frequency modes
    :return: frequency tensor of shape [dim, res, res, res/2+1]
    """
    # print("res",res)
    n_dims = len(res)
    freqs = []
    for dim in range(n_dims - 1):
        r_ = res[dim]
        freq = np.fft.fftfreq(r_, d=1/r_)
        freqs.append(torch.tensor(freq, dtype=dtype))
    r_ = res[-1]
    if exact:
        freqs.append(torch.tensor(np.fft.rfftfreq(r_, d=1/r_), dtype=dtype))
    else:
        freqs.append(torch.tensor(np.fft.rfftfreq(r_, d=1/r_)[:-1], dtype=dtype))
    omega = torch.meshgrid(freqs)
    omega = list(omega)
    omega = torch.stack(omega, dim=0)

    # print("omega.shape",omega.shape)
    return omega 
開發者ID:maxjiang93,項目名稱:space_time_pde,代碼行數:26,代碼來源:torch_spec_operator.py

示例6: fftfreqs

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def fftfreqs(res, dtype=torch.float32):
    """
    Helper function to return frequency tensors
    :param res: n_dims int tuple of number of frequency modes
    :return: frequency tensor of shape [dim, res, res, res]
    """

    n_dims = len(res)
    freqs = []
    for dim in range(n_dims):
        r_ = res[dim]
        freq = np.fft.fftfreq(r_, d=1/r_)
        freqs.append(torch.tensor(freq, dtype=dtype))
    omega = torch.meshgrid(freqs)
    omega = list(omega)
    omega = torch.stack(omega, dim=0)

    return omega 
開發者ID:maxjiang93,項目名稱:space_time_pde,代碼行數:20,代碼來源:torch_spec_operator.py

示例7: grid_anchors

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def grid_anchors(self, grid_sizes, strides):
        anchors = []
        for size, stride, base_anchors in zip(
            grid_sizes, strides, self.cell_anchors
        ):
            grid_height, grid_width = size
            stride_height, stride_width = stride
            device = base_anchors.device
            shifts_x = torch.arange(
                0, grid_width, dtype=torch.float32, device=device
            ) * stride_width
            shifts_y = torch.arange(
                0, grid_height, dtype=torch.float32, device=device
            ) * stride_height
            shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)
            shift_x = shift_x.reshape(-1)
            shift_y = shift_y.reshape(-1)
            shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1)

            anchors.append(
                (shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4)
            )

        return anchors 
開發者ID:lopuhin,項目名稱:kaggle-kuzushiji-2019,代碼行數:26,代碼來源:rpn.py

示例8: offset_flow

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def offset_flow(img, flow):
    '''
    :param img: torch.FloatTensor of shape NxCxHxW
    :param flow: torch.FloatTensor of shape NxHxWx2
    :return: torch.FloatTensor of shape NxCxHxW
    '''
    N, C, H, W = img.shape
    # generate identity sampling grid
    gx, gy = torch.meshgrid(torch.arange(H), torch.arange(W))
    gx = gx.float().div(gx.max() - 1).view(1, H, W, 1)
    gy = gy.float().div(gy.max() - 1).view(1, H, W, 1)
    grid = torch.cat([gy, gx], dim=-1).mul(2.).sub(1)
    # generate normalized flow field
    flown = flow.clone()
    flown[..., 0] /= W
    flown[..., 1] /= H
    # calculate offset field
    grid += flown
    return F.grid_sample(img, grid), grid 
開發者ID:orsic,項目名稱:swiftnet,代碼行數:21,代碼來源:flow_utils.py

示例9: forward

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def forward(self, input_, target_seq=None, teacher_forcing_ratio=0):
        device = input_.device
        b, c, h, w = input_.size()
        encoder_outputs = self.incept(input_)

        b, fc, fh, fw = encoder_outputs.size()

        x, y = torch.meshgrid(torch.arange(fh, device=device), torch.arange(fw, device=device))

        h_loc = self.onehot_x(x)
        w_loc = self.onehot_y(y)

        loc = torch.cat([h_loc, w_loc], dim=2).unsqueeze(0).expand(b, -1, -1, -1)

        encoder_outputs = torch.cat([encoder_outputs.permute(0, 2, 3, 1), loc], dim=3)
        encoder_outputs = encoder_outputs.contiguous().view(b, -1, 288 + self._fh + self._fw)

        encoder_outputs = self.encode_emb(encoder_outputs)

        decoder_outputs, decoder_hidden = self.decoder(target_seq, encoder_outputs=encoder_outputs,
                                                       teacher_forcing_ratio=teacher_forcing_ratio)

        return decoder_outputs 
開發者ID:wptoux,項目名稱:attention-ocr,代碼行數:25,代碼來源:attention_ocr.py

示例10: grid_anchors

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def grid_anchors(self, grid_sizes):
        anchors = []
        for size, stride, base_anchors in zip(
            grid_sizes, self.strides, self.cell_anchors
        ):
            grid_height, grid_width = size
            device = base_anchors.device
            shifts_x = torch.arange(
                0, grid_width * stride, step=stride, dtype=torch.float32, device=device
            )
            shifts_y = torch.arange(
                0, grid_height * stride, step=stride, dtype=torch.float32, device=device
            )
            shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)
            shift_x = shift_x.reshape(-1)
            shift_y = shift_y.reshape(-1)
            # shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1)
            shifts = torch.stack((shift_x, shift_y, torch.zeros(grid_width * grid_height, device=shift_x.device), torch.zeros(grid_width * grid_height, device=shift_x.device), torch.zeros(grid_width * grid_height, device=shift_x.device)), dim=1)
            anchors.append(
                (shifts.view(-1, 1, 5) + base_anchors.view(1, -1, 5)).reshape(-1, 5)
            )


        return anchors 
開發者ID:clw5180,項目名稱:remote_sensing_object_detection_2019,代碼行數:26,代碼來源:anchor_generator.py

示例11: __init__

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def __init__(self, n_tasks, max_iter=250, stop_crit=1e-6):
        super().__init__()
        self.n = n_tasks
        self.linear_solver = MinNormLinearSolver()
        self.planar_solver = MinNormPlanarSolver(n_tasks)

        n_grid = torch.arange(n_tasks)
        i_grid = torch.arange(n_tasks, dtype=torch.float32) + 1
        ii_grid, jj_grid = torch.meshgrid(n_grid, n_grid)

        self.register_buffer('n_ts', torch.tensor(n_tasks))
        self.register_buffer('i_grid', i_grid)
        self.register_buffer('ii_grid', ii_grid)
        self.register_buffer('jj_grid', jj_grid)
        self.register_buffer('zero', torch.zeros(n_tasks))
        self.register_buffer('stop_crit', torch.tensor(stop_crit))

        self.max_iter = max_iter
        self.two_sol = nn.Parameter(torch.zeros(2))
        self.two_sol.require_grad = False 
開發者ID:hav4ik,項目名稱:Hydra,代碼行數:22,代碼來源:min_norm_solver.py

示例12: __init__

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def __init__(self, size, mode='bilinear'):
        """
        Instiatiate the block
            :param size: size of input to the spatial transformer block
            :param mode: method of interpolation for grid_sampler
        """
        super(SpatialTransformer, self).__init__()

        # Create sampling grid
        vectors = [ torch.arange(0, s) for s in size ] 
        grids = torch.meshgrid(vectors) 
        grid  = torch.stack(grids) # y, x, z
        grid  = torch.unsqueeze(grid, 0)  #add batch
        grid = grid.type(torch.FloatTensor)
        self.register_buffer('grid', grid)

        self.mode = mode 
開發者ID:voxelmorph,項目名稱:voxelmorph,代碼行數:19,代碼來源:model.py

示例13: render_points_as_2d_gaussians

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def render_points_as_2d_gaussians(points, sigmas, image_shape, normalize=True):
    device = points.device
    n_points = points.shape[0]

    yy, xx = torch.meshgrid(torch.arange(image_shape[0]).to(device), torch.arange(image_shape[1]).to(device))
    grid = torch.stack([xx, yy], dim=-1).type(torch.float32)
    grid = grid.unsqueeze(0).repeat(n_points, 1, 1, 1)  # (n_points, h, w, 2)
    grid = grid.reshape((-1, 2))

    points = points.unsqueeze(1).unsqueeze(1).repeat(1, image_shape[0], image_shape[1], 1)
    points = points.reshape(-1, 2)

    sigmas = sigmas.unsqueeze(1).unsqueeze(1).repeat(1, image_shape[0], image_shape[1], 1)
    sigmas = sigmas.reshape(-1, 2)

    images = gaussian_2d_pdf(grid, points, sigmas, normalize=normalize)
    images = images.reshape(n_points, *image_shape)

    return images 
開發者ID:karfly,項目名稱:learnable-triangulation-pytorch,代碼行數:21,代碼來源:op.py

示例14: grid_generator

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def grid_generator(k, r, n):
    """grid_generator
    Parameters
    ---------
    f : filter_size, int
    k: kernel_size, int
    n: number of grid, int
    Returns
    -------
    torch.Tensor. shape = (n, 2, k, k)
    """
    grid_x, grid_y = torch.meshgrid([torch.linspace(k//2, k//2+r-1, steps=r),
                                     torch.linspace(k//2, k//2+r-1, steps=r)])
    grid = torch.stack([grid_x,grid_y],2).view(r,r,2)

    return grid.unsqueeze(0).repeat(n,1,1,1).cuda() 
開發者ID:jun0kim,項目名稱:DKN,代碼行數:18,代碼來源:models.py

示例15: grid_anchors

# 需要導入模塊: import torch [as 別名]
# 或者: from torch import meshgrid [as 別名]
def grid_anchors(self, grid_sizes):
        anchors = []
        for size, stride, base_anchors in zip(
            grid_sizes, self.strides, self.cell_anchors
        ):
            grid_height, grid_width = size
            device = base_anchors.device
            shifts_x = torch.arange(
                0, grid_width * stride, step=stride, dtype=torch.float32, device=device
            ).type_as(base_anchors)
            shifts_y = torch.arange(
                0, grid_height * stride, step=stride, dtype=torch.float32, device=device
            ).type_as(base_anchors)
            shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)
            shift_x = shift_x.reshape(-1)
            shift_y = shift_y.reshape(-1)
            shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1)

            anchors.append(
                (shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4)
            )

        return anchors 
開發者ID:HRNet,項目名稱:HRNet-MaskRCNN-Benchmark,代碼行數:25,代碼來源:anchor_generator.py


注:本文中的torch.meshgrid方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。