本文整理汇总了Python中mxnet.nd.flip方法的典型用法代码示例。如果您正苦于以下问题:Python nd.flip方法的具体用法?Python nd.flip怎么用?Python nd.flip使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mxnet.nd
的用法示例。
在下文中一共展示了nd.flip方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: transform
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def transform(data, target_wd, target_ht, is_train, box):
"""Crop and normnalize an image nd array."""
if box is not None:
x, y, w, h = box
data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])]
# Resize to target_wd * target_ht.
data = mx.image.imresize(data, target_wd, target_ht)
# Normalize in the same way as the pre-trained model.
data = data.astype(np.float32) / 255.0
data = (data - mx.nd.array([0.485, 0.456, 0.406])) / mx.nd.array([0.229, 0.224, 0.225])
if is_train:
if random.random() < 0.5:
data = nd.flip(data, axis=1)
data, _ = mx.image.random_crop(data, (224, 224))
else:
data, _ = mx.image.center_crop(data, (224, 224))
# Transpose from (target_wd, target_ht, 3)
# to (3, target_wd, target_ht).
data = nd.transpose(data, (2, 0, 1))
# If image is greyscale, repeat 3 times to get RGB image.
if data.shape[0] == 1:
data = nd.tile(data, (3, 1, 1))
return data.reshape((1,) + data.shape)
示例2: test_layer_bidirectional
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def test_layer_bidirectional():
class RefBiLSTM(gluon.Block):
def __init__(self, size, **kwargs):
super(RefBiLSTM, self).__init__(**kwargs)
with self.name_scope():
self._lstm_fwd = gluon.rnn.LSTM(size, bidirectional=False, prefix='l0')
self._lstm_bwd = gluon.rnn.LSTM(size, bidirectional=False, prefix='r0')
def forward(self, inpt):
fwd = self._lstm_fwd(inpt)
bwd_inpt = nd.flip(inpt, 0)
bwd = self._lstm_bwd(bwd_inpt)
bwd = nd.flip(bwd, 0)
return nd.concat(fwd, bwd, dim=2)
size = 7
in_size = 5
weights = {}
for d in ['l', 'r']:
weights['lstm_{}0_i2h_weight'.format(d)] = mx.random.uniform(shape=(size*4, in_size))
weights['lstm_{}0_h2h_weight'.format(d)] = mx.random.uniform(shape=(size*4, size))
weights['lstm_{}0_i2h_bias'.format(d)] = mx.random.uniform(shape=(size*4,))
weights['lstm_{}0_h2h_bias'.format(d)] = mx.random.uniform(shape=(size*4,))
net = gluon.rnn.LSTM(size, bidirectional=True, prefix='lstm_')
ref_net = RefBiLSTM(size, prefix='lstm_')
net.initialize()
ref_net.initialize()
net_params = net.collect_params()
ref_net_params = ref_net.collect_params()
for k in weights:
net_params[k].set_data(weights[k])
ref_net_params[k.replace('l0', 'l0l0').replace('r0', 'r0l0')].set_data(weights[k])
data = mx.random.uniform(shape=(3, 10, in_size))
assert_allclose(net(data).asnumpy(), ref_net(data).asnumpy())
示例3: fliplr
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def fliplr(img):
'''flip horizontal'''
img_flip = nd.flip(img, axis=3)
return img_flip
示例4: validate
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def validate(val_data, val_dataset, net, ctx):
if isinstance(ctx, mx.Context):
ctx = [ctx]
val_metric.reset()
from tqdm import tqdm
for batch in tqdm(val_data):
data, scale, center, score, imgid = val_batch_fn(batch, ctx)
outputs = [net(X) for X in data]
if opt.flip_test:
data_flip = [nd.flip(X, axis=3) for X in data]
outputs_flip = [net(X) for X in data_flip]
outputs_flipback = [flip_heatmap(o, val_dataset.joint_pairs, shift=True) for o in outputs_flip]
outputs = [(o + o_flip)/2 for o, o_flip in zip(outputs, outputs_flipback)]
if opt.dsnt:
outputs = [net_dsnt(X)[0] for X in outputs]
if len(outputs) > 1:
outputs_stack = nd.concat(*[o.as_in_context(mx.cpu()) for o in outputs], dim=0)
else:
outputs_stack = outputs[0].as_in_context(mx.cpu())
if opt.dsnt:
preds = (outputs_stack - 0.5) * scale.expand_dims(axis=1) + center.expand_dims(axis=1)
maxvals = nd.ones(preds.shape[0:2]+(1, ))
else:
preds, maxvals = get_final_preds(outputs_stack, center.asnumpy(), scale.asnumpy())
val_metric.update(preds, maxvals, score, imgid)
metric_name, metric_score = val_metric.get()
print("Inference Completed! %s = %.4f" % (metric_name, metric_score))
return
示例5: validate
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def validate(val_data, val_dataset, net, ctx):
if isinstance(ctx, mx.Context):
ctx = [ctx]
val_metric.reset()
from tqdm import tqdm
for batch in tqdm(val_data):
# data, scale, center, score, imgid = val_batch_fn(batch, ctx)
data, scale_box, score, imgid = val_batch_fn(batch, ctx)
outputs = [net(X) for X in data]
if opt.flip_test:
data_flip = [nd.flip(X, axis=3) for X in data]
outputs_flip = [net(X) for X in data_flip]
outputs_flipback = [flip_heatmap(o, val_dataset.joint_pairs, shift=True) for o in outputs_flip]
outputs = [(o + o_flip)/2 for o, o_flip in zip(outputs, outputs_flipback)]
if len(outputs) > 1:
outputs_stack = nd.concat(*[o.as_in_context(mx.cpu()) for o in outputs], dim=0)
else:
outputs_stack = outputs[0].as_in_context(mx.cpu())
# preds, maxvals = get_final_preds(outputs_stack, center.asnumpy(), scale.asnumpy())
preds, maxvals = heatmap_to_coord_alpha_pose(outputs_stack, scale_box)
# print(preds, maxvals, scale_box)
# print(preds, maxvals)
# raise
val_metric.update(preds, maxvals, score, imgid)
res = val_metric.get()
return
示例6: validate
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def validate(val_data, val_dataset, net, ctx, opt):
if isinstance(ctx, mx.Context):
ctx = [ctx]
val_metric = COCOKeyPointsMetric(val_dataset, 'coco_keypoints',
in_vis_thresh=0)
for batch in tqdm(val_data, dynamic_ncols=True):
# data, scale, center, score, imgid = val_batch_fn(batch, ctx)
data, scale_box, score, imgid = val_batch_fn(batch, ctx)
outputs = [net(X) for X in data]
if opt.flip_test:
data_flip = [nd.flip(X, axis=3) for X in data]
outputs_flip = [net(X) for X in data_flip]
outputs_flipback = [flip_heatmap(o, val_dataset.joint_pairs, shift=True) for o in outputs_flip]
outputs = [(o + o_flip) / 2 for o, o_flip in zip(outputs, outputs_flipback)]
if len(outputs) > 1:
outputs_stack = nd.concat(*[o.as_in_context(mx.cpu()) for o in outputs], dim=0)
else:
outputs_stack = outputs[0].as_in_context(mx.cpu())
# preds, maxvals = get_final_preds(outputs_stack, center.asnumpy(), scale.asnumpy())
preds, maxvals = heatmap_to_coord_alpha_pose(outputs_stack, scale_box)
val_metric.update(preds, maxvals, score, imgid)
nullwriter = NullWriter()
oldstdout = sys.stdout
sys.stdout = nullwriter
try:
res = val_metric.get()
finally:
sys.stdout = oldstdout
return res
示例7: random_flip
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def random_flip(src, px=0, py=0, copy=False):
"""Randomly flip image along horizontal and vertical with probabilities.
Parameters
----------
src : mxnet.nd.NDArray
Input image with HWC format.
px : float
Horizontal flip probability [0, 1].
py : float
Vertical flip probability [0, 1].
copy : bool
If `True`, return a copy of input
Returns
-------
mxnet.nd.NDArray
Augmented image.
tuple
Tuple of (flip_x, flip_y), records of whether flips are applied.
"""
flip_y = np.random.choice([False, True], p=[1-py, py])
flip_x = np.random.choice([False, True], p=[1-px, px])
if flip_y:
src = nd.flip(src, axis=0)
if flip_x:
src = nd.flip(src, axis=1)
if copy:
src = src.copy()
return src, (flip_x, flip_y)
示例8: validate
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def validate(val_data, val_dataset, net, ctx):
if isinstance(ctx, mx.Context):
ctx = [ctx]
val_metric.reset()
from tqdm import tqdm
for batch in tqdm(val_data):
data, scale, center, score, imgid = val_batch_fn(batch, ctx)
outputs = [net(X) for X in data]
if opt.flip_test:
data_flip = [nd.flip(X, axis=3) for X in data]
outputs_flip = [net(X) for X in data_flip]
outputs_flipback = [flip_heatmap(o, val_dataset.joint_pairs, shift=True) for o in outputs_flip]
outputs = [(o + o_flip)/2 for o, o_flip in zip(outputs, outputs_flipback)]
if len(outputs) > 1:
outputs_stack = nd.concat(*[o.as_in_context(mx.cpu()) for o in outputs], dim=0)
else:
outputs_stack = outputs[0].as_in_context(mx.cpu())
preds, maxvals = get_final_preds(outputs_stack, center.asnumpy(), scale.asnumpy())
val_metric.update(preds, maxvals, score, imgid)
res = val_metric.get()
return
示例9: transform_test_flip
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def transform_test_flip(data, isf=False):
flip_data = nd.flip(data, axis=1)
if isf:
data = nd.transpose(data, (2, 0, 1)).astype('float32')
flip_data = nd.transpose(flip_data, (2, 0, 1)).astype('float32')
return data, flip_data
return transform_test(data), transform_test(flip_data)
示例10: validate
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def validate(nfolds=10):
metric = FaceVerification(nfolds)
metric_flip = FaceVerification(nfolds)
for loader, name in zip(val_datas, targets.split(",")):
metric.reset()
for i, batch in enumerate(loader):
data0s = gluon.utils.split_and_load(batch[0][0][0], ctx, even_split=False)
data1s = gluon.utils.split_and_load(batch[0][1][0], ctx, even_split=False)
data0s_flip = gluon.utils.split_and_load(batch[0][0][1], ctx, even_split=False)
data1s_flip = gluon.utils.split_and_load(batch[0][1][1], ctx, even_split=False)
issame_list = gluon.utils.split_and_load(batch[1], ctx, even_split=False)
embedding0s = [test_net(X) for X in data0s]
embedding1s = [test_net(X) for X in data1s]
embedding0s_flip = [test_net(X) for X in data0s_flip]
embedding1s_flip = [test_net(X) for X in data1s_flip]
emb0s = [nd.L2Normalization(e, mode='instance') for e in embedding0s]
emb1s = [nd.L2Normalization(e, mode='instance') for e in embedding1s]
for embedding0, embedding1, issame in zip(emb0s, emb1s, issame_list):
metric.update(issame, embedding0, embedding1)
emb0s_flip = [nd.L2Normalization(nd.concatenate([e, ef], 1), mode='instance')
for e, ef in zip(embedding0s, embedding0s_flip)]
emb1s_flip = [nd.L2Normalization(nd.concatenate([e, ef], 1), mode='instance')
for e, ef in zip(embedding1s, embedding1s_flip)]
for embedding0, embedding1, issame in zip(emb0s_flip, emb1s_flip, issame_list):
metric_flip.update(issame, embedding0, embedding1)
tpr, fpr, accuracy, val, val_std, far, accuracy_std = metric.get()
print("{}: \t{:.6f}+-{:.6f}".format(name, accuracy, accuracy_std))
_, _, accuracy, _, _, _, accuracy_std = metric_flip.get()
print("{}-flip: {:.6f}+-{:.6f}".format(name, accuracy, accuracy_std))
示例11: ten_crop
# 需要导入模块: from mxnet import nd [as 别名]
# 或者: from mxnet.nd import flip [as 别名]
def ten_crop(src, size):
"""Crop 10 regions from an array.
This is performed same as:
http://chainercv.readthedocs.io/en/stable/reference/transforms.html#ten-crop
This method crops 10 regions. All regions will be in shape
:obj`size`. These regions consist of 1 center crop and 4 corner
crops and horizontal flips of them.
The crops are ordered in this order.
* center crop
* top-left crop
* bottom-left crop
* top-right crop
* bottom-right crop
* center crop (flipped horizontally)
* top-left crop (flipped horizontally)
* bottom-left crop (flipped horizontally)
* top-right crop (flipped horizontally)
* bottom-right crop (flipped horizontally)
Parameters
----------
src : mxnet.nd.NDArray
Input image.
size : tuple
Tuple of length 2, as (width, height) of the cropped areas.
Returns
-------
mxnet.nd.NDArray
The cropped images with shape (10, size[1], size[0], C)
"""
h, w, _ = src.shape
ow, oh = size
if h < oh or w < ow:
raise ValueError(
"Cannot crop area {} from image with size ({}, {})".format(str(size), h, w))
center = src[(h - oh) // 2:(h + oh) // 2, (w - ow) // 2:(w + ow) // 2, :]
tl = src[0:oh, 0:ow, :]
bl = src[h - oh:h, 0:ow, :]
tr = src[0:oh, w - ow:w, :]
br = src[h - oh:h, w - ow:w, :]
crops = nd.stack(*[center, tl, bl, tr, br], axis=0)
crops = nd.concat(*[crops, nd.flip(crops, axis=2)], dim=0)
return crops