本文整理汇总了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()
示例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, :]
示例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))
示例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])
#----------------------------------------------------------------------------
示例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)])
#----------------------------------------------------------------------------
示例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
示例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()
示例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)
示例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
示例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
示例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
示例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
示例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)
示例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)
示例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)