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


Python numpy.pad方法代碼示例

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


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

示例1: test_bitmap_mask_pad

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def test_bitmap_mask_pad():
    # pad with empty bitmap masks
    raw_masks = dummy_raw_bitmap_masks((0, 28, 28))
    bitmap_masks = BitmapMasks(raw_masks, 28, 28)
    padded_masks = bitmap_masks.pad((56, 56))
    assert len(padded_masks) == 0
    assert padded_masks.height == 56
    assert padded_masks.width == 56

    # pad with bitmap masks contain 3 instances
    raw_masks = dummy_raw_bitmap_masks((3, 28, 28))
    bitmap_masks = BitmapMasks(raw_masks, 28, 28)
    padded_masks = bitmap_masks.pad((56, 56))
    assert len(padded_masks) == 3
    assert padded_masks.height == 56
    assert padded_masks.width == 56
    assert (padded_masks.masks[:, 28:, 28:] == 0).all() 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:19,代碼來源:test_masks.py

示例2: __call__

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def __call__(self, video):
    """
    Args:
        video (np.ndarray): Video to be cropped.
    Returns:
        np.ndarray: Cropped video.
    """
    if self.padding > 0:
      pad = Pad(self.padding, 0)
      video = pad(video)

    w, h = video.shape[-2], video.shape[-3]
    th, tw = self.size
    if w == tw and h == th:
      return video

    x1 = random.randint(0, w-tw)
    y1 = random.randint(0, h-th)
    return video[..., y1:y1+th, x1:x1+tw, :] 
開發者ID:jthsieh,項目名稱:DDPAE-video-prediction,代碼行數:21,代碼來源:video_transforms.py

示例3: convert

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def convert(story):
    # import pdb; pdb.set_trace()
    sentence_arr, graphs, query_arr, answer_arr = story
    node_id_w = graphs[2].shape[2]
    edge_type_w = graphs[3].shape[3]

    all_node_strengths = [np.zeros([1])]
    all_node_ids = [np.zeros([1,node_id_w])]
    for num_new_nodes, new_node_strengths, new_node_ids, _ in zip(*graphs):
        last_strengths = all_node_strengths[-1]
        last_ids = all_node_ids[-1]

        cur_strengths = np.concatenate([last_strengths, new_node_strengths], 0)
        cur_ids = np.concatenate([last_ids, new_node_ids], 0)

        all_node_strengths.append(cur_strengths)
        all_node_ids.append(cur_ids)

    all_edges = graphs[3]
    full_n_nodes = all_edges.shape[1]
    all_node_strengths = np.stack([np.pad(x, ((0, full_n_nodes-x.shape[0])), 'constant') for x in all_node_strengths[1:]])
    all_node_ids = np.stack([np.pad(x, ((0, full_n_nodes-x.shape[0]), (0, 0)), 'constant') for x in all_node_ids[1:]])
    all_node_states = np.zeros([len(all_node_strengths), full_n_nodes,0])

    return tuple(x[np.newaxis,...] for x in (all_node_strengths, all_node_ids, all_node_states, all_edges)) 
開發者ID:hexahedria,項目名稱:gated-graph-transformer-network,代碼行數:27,代碼來源:convert_story.py

示例4: create_mnist

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def create_mnist(tfrecord_dir, mnist_dir):
    print('Loading MNIST from "%s"' % mnist_dir)
    import gzip
    with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:
        images = np.frombuffer(file.read(), np.uint8, offset=16)
    with gzip.open(os.path.join(mnist_dir, 'train-labels-idx1-ubyte.gz'), 'rb') as file:
        labels = np.frombuffer(file.read(), np.uint8, offset=8)
    images = images.reshape(-1, 1, 28, 28)
    images = np.pad(images, [(0,0), (0,0), (2,2), (2,2)], 'constant', constant_values=0)
    assert images.shape == (60000, 1, 32, 32) and images.dtype == np.uint8
    assert labels.shape == (60000,) and labels.dtype == np.uint8
    assert np.min(images) == 0 and np.max(images) == 255
    assert np.min(labels) == 0 and np.max(labels) == 9
    onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
    onehot[np.arange(labels.size), labels] = 1.0
    
    with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
        order = tfr.choose_shuffled_order()
        for idx in range(order.size):
            tfr.add_image(images[order[idx]])
        tfr.add_labels(onehot[order])

#---------------------------------------------------------------------------- 
開發者ID:zalandoresearch,項目名稱:disentangling_conditional_gans,代碼行數:25,代碼來源:dataset_tool.py

示例5: create_mnistrgb

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def create_mnistrgb(tfrecord_dir, mnist_dir, num_images=1000000, random_seed=123):
    print('Loading MNIST from "%s"' % mnist_dir)
    import gzip
    with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:
        images = np.frombuffer(file.read(), np.uint8, offset=16)
    images = images.reshape(-1, 28, 28)
    images = np.pad(images, [(0,0), (2,2), (2,2)], 'constant', constant_values=0)
    assert images.shape == (60000, 32, 32) and images.dtype == np.uint8
    assert np.min(images) == 0 and np.max(images) == 255
    
    with TFRecordExporter(tfrecord_dir, num_images) as tfr:
        rnd = np.random.RandomState(random_seed)
        for idx in range(num_images):
            tfr.add_image(images[rnd.randint(images.shape[0], size=3)])

#---------------------------------------------------------------------------- 
開發者ID:zalandoresearch,項目名稱:disentangling_conditional_gans,代碼行數:18,代碼來源:dataset_tool.py

示例6: load_spectrograms

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def load_spectrograms(fpath):
    '''Read the wave file in `fpath`
    and extracts spectrograms'''

    fname = os.path.basename(fpath)
    mel, mag = get_spectrograms(fpath)
    t = mel.shape[0]

    # Marginal padding for reduction shape sync.
    num_paddings = hp.r - (t % hp.r) if t % hp.r != 0 else 0
    mel = np.pad(mel, [[0, num_paddings], [0, 0]], mode="constant")
    mag = np.pad(mag, [[0, num_paddings], [0, 0]], mode="constant")

    # Reduction
    mel = mel[::hp.r, :]
    return fname, mel, mag 
開發者ID:Kyubyong,項目名稱:dc_tts,代碼行數:18,代碼來源:utils.py

示例7: test_polygon_mask_pad

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def test_polygon_mask_pad():
    # pad with empty polygon masks
    raw_masks = dummy_raw_polygon_masks((0, 28, 28))
    polygon_masks = PolygonMasks(raw_masks, 28, 28)
    padded_masks = polygon_masks.pad((56, 56))
    assert len(padded_masks) == 0
    assert padded_masks.height == 56
    assert padded_masks.width == 56
    assert padded_masks.to_ndarray().shape == (0, 56, 56)

    # pad with polygon masks contain 3 instances
    raw_masks = dummy_raw_polygon_masks((3, 28, 28))
    polygon_masks = PolygonMasks(raw_masks, 28, 28)
    padded_masks = polygon_masks.pad((56, 56))
    assert len(padded_masks) == 3
    assert padded_masks.height == 56
    assert padded_masks.width == 56
    assert padded_masks.to_ndarray().shape == (3, 56, 56)
    assert (padded_masks.to_ndarray()[:, 28:, 28:] == 0).all() 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:21,代碼來源:test_masks.py

示例8: mask_to_rle

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def mask_to_rle(img, mask_value=255, transpose=True):
    img = np.int32(img)
    if transpose:
      img = img.T
    img = img.flatten()
    img[img == mask_value] = 1
    pimg = np.pad(img, 1, mode='constant')
    diff = np.diff(pimg)
    starts = np.where(diff == 1)[0]
    ends = np.where(diff == -1)[0]
    rle = []
    previous_end = 0
    for start, end in zip(starts, ends):
      relative_start = start - previous_end
      length = end - start
      previous_end = end
      rle.append(str(relative_start))
      rle.append(str(length))
    if len(rle) == 0:
      return "-1"
    return " ".join(rle) 
開發者ID:see--,項目名稱:kuzushiji-recognition,代碼行數:23,代碼來源:data.py

示例9: get_paddings

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def get_paddings(h, w, ratio):
    current_ratio = h / w
    # pad height
    if current_ratio < ratio:
      pad_h = int(w * ratio - h)
      pad_top = pad_h // 2
      pad_bottom = pad_h - pad_top
      pad_left, pad_right = 0, 0
    # pad width
    else:
      pad_w = int(h / ratio - w)
      pad_left = pad_w // 2
      pad_right = pad_w - pad_left
      pad_top, pad_bottom = 0, 0

    return pad_top, pad_bottom, pad_left, pad_right 
開發者ID:see--,項目名稱:kuzushiji-recognition,代碼行數:18,代碼來源:data.py

示例10: load_spectrograms

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def load_spectrograms(fpath):
    '''Read the wave file in `fpath`
    and extracts spectrograms'''

    fname = os.path.basename(fpath)
    mel, mag = get_spectrograms(fpath)
    t = mel.shape[0]

    # Marginal padding for reduction shape sync.
    num_paddings = hp.r - (t % hp.r) if t % hp.r != 0 else 0
    mel = np.pad(mel, [[0, num_paddings], [0, 0]], mode="constant")
    mag = np.pad(mag, [[0, num_paddings], [0, 0]], mode="constant")

    # Reduction
    mel = mel[::hp.r, :]
    return fname, mel, mag

#This is adapted by
# https://github.com/keithito/tacotron/blob/master/util/audio.py#L55-62 
開發者ID:Kyubyong,項目名稱:kss,代碼行數:21,代碼來源:utils.py

示例11: scale_and_crop

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def scale_and_crop(image, scale, center, img_size):
    image_scaled, scale_factors = resize_img(image, scale)
    # Swap so it's [x, y]
    scale_factors = [scale_factors[1], scale_factors[0]]
    center_scaled = np.round(center * scale_factors).astype(np.int)

    margin = int(img_size / 2)
    image_pad = np.pad(
        image_scaled, ((margin, ), (margin, ), (0, )), mode='edge')
    center_pad = center_scaled + margin
    # figure out starting point
    start_pt = center_pad - margin
    end_pt = center_pad + margin
    # crop:
    crop = image_pad[start_pt[1]:end_pt[1], start_pt[0]:end_pt[0], :]
    proc_param = {
        'scale': scale,
        'start_pt': start_pt,
        'end_pt': end_pt,
        'img_size': img_size
    }

    return crop, proc_param 
開發者ID:soubhiksanyal,項目名稱:RingNet,代碼行數:25,代碼來源:image.py

示例12: add_padding

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def add_padding(self, im):
            # TODO: use undo pad when saving images to disk
            w, h, chan = im.shape
            if chan == 4:
                print('*** Ditching alpha channel...')
                return self.add_padding(im[:, :, :3])
            if w % self.pad == 0 and h % self.pad == 0:
                return im, lambda x: x

            wp = (self.pad - w % self.pad) % self.pad
            hp = (self.pad - h % self.pad) % self.pad
            wp_left = wp // 2
            wp_right = wp - wp_left
            hp_left = hp // 2
            hp_right = hp - hp_left
            paddings = [[wp_left, wp_right], [hp_left, hp_right], [0, 0]]
            im = np.pad(im, paddings, mode='constant')

            def _undo_pad(img_data_):
                return img_data_[wp_left:(-wp_right or None), hp_left:(-hp_right or None), :]
            return im, _undo_pad 
開發者ID:fab-jul,項目名稱:imgcomp-cvpr,代碼行數:23,代碼來源:images_iterator.py

示例13: pad_for_probclass3d

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def pad_for_probclass3d(x, context_size, pad_value=0, learn_pad_var=False):
    """
    :param x: NCHW tensorflow Tensor or numpy array
    """
    input_is_tf = not isinstance(x, np.ndarray)
    if not input_is_tf and x.ndim == 3:  # for bit_counter
        return remove_batch_dim(pad_for_probclass3d(
                add_batch_dim(x), context_size, pad_value, learn_pad_var))

    with tf.name_scope('pad_cs' + str(context_size)):
        pad = context_size // 2
        assert pad >= 1
        if learn_pad_var:
            if not isinstance(pad_value, tf.Variable):
                print('Warn: Expected tf.Variable for padding, got {}'.format(pad_value))
            return pc_pad_grad(x, pad, pad_value)

        pads = [[0, 0],  # don't pad batch dimension
                [pad, 0],  # don't pad depth_future, it's not seen by any filter
                [pad, pad],
                [pad, pad]]
        assert len(pads) == _get_ndims(x), '{} != {}'.format(len(pads), x.shape)

        pad_fn = tf.pad if input_is_tf else get_np_pad_fn()
        return pad_fn(x, pads, constant_values=pad_value) 
開發者ID:fab-jul,項目名稱:imgcomp-cvpr,代碼行數:27,代碼來源:probclass.py

示例14: split4

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def split4(data,  max_stride, margin):
    splits = []
    data = torch.Tensor.numpy(data)
    _,c, z, h, w = data.shape

    w_width = np.ceil(float(w / 2 + margin)/max_stride).astype('int')*max_stride
    h_width = np.ceil(float(h / 2 + margin)/max_stride).astype('int')*max_stride
    pad = int(np.ceil(float(z)/max_stride)*max_stride)-z
    leftpad = pad/2
    pad = [[0,0],[0,0],[leftpad,pad-leftpad],[0,0],[0,0]]
    data = np.pad(data,pad,'constant',constant_values=-1)
    data = torch.from_numpy(data)
    splits.append(data[:, :, :, :h_width, :w_width])
    splits.append(data[:, :, :, :h_width, -w_width:])
    splits.append(data[:, :, :, -h_width:, :w_width])
    splits.append(data[:, :, :, -h_width:, -w_width:])
    
    return torch.cat(splits, 0) 
開發者ID:uci-cbcl,項目名稱:DeepLung,代碼行數:20,代碼來源:utils.py

示例15: read_audio

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import pad [as 別名]
def read_audio(file_path):
    min_samples = int(config.min_seconds * config.sampling_rate)
    try:
        y, sr = librosa.load(file_path, sr=config.sampling_rate)
        trim_y, trim_idx = librosa.effects.trim(y)  # trim, top_db=default(60)

        if len(trim_y) < min_samples:
            center = (trim_idx[1] - trim_idx[0]) // 2
            left_idx = max(0, center - min_samples // 2)
            right_idx = min(len(y), center + min_samples // 2)
            trim_y = y[left_idx:right_idx]

            if len(trim_y) < min_samples:
                padding = min_samples - len(trim_y)
                offset = padding // 2
                trim_y = np.pad(trim_y, (offset, padding - offset), 'constant')
        return trim_y
    except BaseException as e:
        print(f"Exception while reading file {e}")
        return np.zeros(min_samples, dtype=np.float32) 
開發者ID:lRomul,項目名稱:argus-freesound,代碼行數:22,代碼來源:audio.py


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