本文整理匯總了Python中numpy.resize方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.resize方法的具體用法?Python numpy.resize怎麽用?Python numpy.resize使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.resize方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: PreprocessContentImage
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def PreprocessContentImage(path, long_edge):
img = io.imread(path)
logging.info("load the content image, size = %s", img.shape[:2])
factor = float(long_edge) / max(img.shape[:2])
new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
resized_img = transform.resize(img, new_size)
sample = np.asarray(resized_img) * 256
# swap axes to make image from (224, 224, 3) to (3, 224, 224)
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
# sub mean
sample[0, :] -= 123.68
sample[1, :] -= 116.779
sample[2, :] -= 103.939
logging.info("resize the content image to %s", new_size)
return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
示例2: test_PLinearDropInputs_ShouldDropRightParams
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def test_PLinearDropInputs_ShouldDropRightParams(self):
dropped_index = 0
# assume input is 2x2x2, 2 layers of 2x2
input_shape = (2, 2, 2)
module = pnn.PLinear(8, 10)
old_num_features = module.in_features
old_weight = module.weight.data.cpu().numpy()
resized_old_weight = np.resize(old_weight, (module.out_features, *input_shape))
module.drop_inputs(input_shape, dropped_index)
new_shape = module.weight.size()
# ensure that the chosen index is dropped
expected_weight = np.resize(np.delete(resized_old_weight, dropped_index, 1), new_shape)
output = module.weight.data.cpu().numpy()
self.assertTrue(np.array_equal(output, expected_weight))
# ensure num features is reduced
self.assertTrue(module.in_features, old_num_features-1)
示例3: load_flo
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def load_flo(file_path):
"""
Read .flo file in MiddleBury format
Code adapted from:
http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
WARNING: this will work on little-endian architectures (eg Intel x86) only!
Args:
file_path string: file path(absolute)
Returns:
flow (numpy.array): data of image in (Height, Width, 2) layout
"""
with open(file_path, 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
assert(magic == 202021.25)
w = int(np.fromfile(f, np.int32, count=1))
h = int(np.fromfile(f, np.int32, count=1))
# print('Reading %d x %d flo file\n' % (w, h))
flow = np.fromfile(f, np.float32, count=2 * w * h)
# Reshape data into 3D array (columns, rows, bands)
# The reshape here is for visualization, the original code is (w,h,2)
flow = np.resize(flow, (h, w, 2))
return flow
示例4: read_flo_file
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def read_flo_file(filename,verbose=False):
"""
Read from .flo optical flow file (Middlebury format)
:param flow_file: name of the flow file
:return: optical flow data in matrix
adapted from https://github.com/liruoteng/OpticalFlowToolkit/
"""
f = open(filename, 'rb')
magic = np.fromfile(f, np.float32, count=1)
data2d = None
if 202021.25 != magic:
raise TypeError('Magic number incorrect. Invalid .flo file')
else:
w = np.fromfile(f, np.int32, count=1)
h = np.fromfile(f, np.int32, count=1)
if verbose:
print("Reading %d x %d flow file in .flo format" % (h, w))
data2d = np.fromfile(f, np.float32, count=int(2 * w * h))
# reshape data into 3D array (columns, rows, channels)
data2d = np.resize(data2d, (h[0], w[0], 2))
f.close()
return data2d
示例5: test_broadcast
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def test_broadcast(size, mask, item, box):
selection = np.resize(mask, size)
data = np.arange(size, dtype=float)
# Construct the expected series by taking the source
# data or item based on the selection
expected = Series([item if use_item else data[
i] for i, use_item in enumerate(selection)])
s = Series(data)
s[selection] = box(item)
assert_series_equal(s, expected)
s = Series(data)
result = s.where(~selection, box(item))
assert_series_equal(result, expected)
s = Series(data)
result = s.mask(selection, box(item))
assert_series_equal(result, expected)
示例6: read_flo_file
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def read_flo_file(filename, memcached=False):
"""
Read from Middlebury .flo file
:param flow_file: name of the flow file
:return: optical flow data in matrix
"""
if memcached:
filename = io.BytesIO(filename)
f = open(filename, 'rb')
magic = np.fromfile(f, np.float32, count=1)[0]
data2d = None
if 202021.25 != magic:
print('Magic number incorrect. Invalid .flo file')
else:
w = np.fromfile(f, np.int32, count=1)[0]
h = np.fromfile(f, np.int32, count=1)[0]
data2d = np.fromfile(f, np.float32, count=2 * w * h)
# reshape data into 3D array (columns, rows, channels)
data2d = np.resize(data2d, (h, w, 2))
f.close()
return data2d
# fast resample layer
示例7: test_check_preserve_type
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def test_check_preserve_type():
# Ensures that type float32 is preserved.
XA = np.resize(np.arange(40), (5, 8)).astype(np.float32)
XB = np.resize(np.arange(40), (5, 8)).astype(np.float32)
XA_checked, XB_checked = check_pairwise_arrays(XA, None)
assert_equal(XA_checked.dtype, np.float32)
# both float32
XA_checked, XB_checked = check_pairwise_arrays(XA, XB)
assert_equal(XA_checked.dtype, np.float32)
assert_equal(XB_checked.dtype, np.float32)
# mismatched A
XA_checked, XB_checked = check_pairwise_arrays(XA.astype(np.float),
XB)
assert_equal(XA_checked.dtype, np.float)
assert_equal(XB_checked.dtype, np.float)
# mismatched B
XA_checked, XB_checked = check_pairwise_arrays(XA,
XB.astype(np.float))
assert_equal(XA_checked.dtype, np.float)
assert_equal(XB_checked.dtype, np.float)
示例8: readFlow
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def readFlow(fn):
""" Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
# print 'fn = %s'%(fn)
with open(fn, 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
if 202021.25 != magic:
print('Magic number incorrect. Invalid .flo file')
return None
else:
w = np.fromfile(f, np.int32, count=1)
h = np.fromfile(f, np.int32, count=1)
# print 'Reading %d x %d flo file\n' % (w, h)
data = np.fromfile(f, np.float32, count=2 * int(w) * int(h))
# Reshape data into 3D array (columns, rows, bands)
# The reshape here is for visualization, the original code is (w,h,2)
return np.resize(data, (int(h), int(w), 2))
示例9: img_pre_process
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def img_pre_process(img):
"""
Processes the image and returns it
:param img: The image to be processed
:return: Returns the processed image
"""
## Chop off 1/3 from the top and cut bottom 150px(which contains the head of car)
shape = img.shape
img = img[int(shape[0]/3):shape[0]-150, 0:shape[1]]
## Resize the image
img = cv2.resize(img, (params.FLAGS.img_w, params.FLAGS.img_h), interpolation=cv2.INTER_AREA)
## Return the image sized as a 4D array
return np.resize(img, (params.FLAGS.img_w, params.FLAGS.img_h, params.FLAGS.img_c))
## Process video
示例10: mesh_from_img
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def mesh_from_img(img):
nv = (img.shape[0] + 1) * (img.shape[1] + 1)
nf = img.size * 2
v_count = 0
f_count = 0
V_dict = {}
V = np.zeros([nv, 2])
F = np.zeros([nf, 3], dtype=np.int)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
val = img[i, j]
if val == 255.0:
continue
v_idx = []
for v_i in [(i, j), (i + 1, j), (i, j + 1), (i + 1, j + 1)]:
if v_i in V_dict:
v_idx.append(V_dict[v_i])
else:
V_dict[v_i] = v_count
V[v_count, :] = np.array((v_i[1], -v_i[0]))
v_count += 1
v_idx.append(v_count - 1)
v1, v2, v3, v4 = v_idx
F[f_count, :] = np.array([v1, v2, v4])
F[f_count + 1, :] = np.array([v1, v4, v3])
f_count += 2
V = np.resize(V, [v_count, 2])
F = np.resize(F, [f_count, 3])
return V, F
示例11: get_args
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def get_args(arglist=None):
parser = argparse.ArgumentParser(description='neural style')
parser.add_argument('--model', type=str, default='vgg19',
choices = ['vgg'],
help = 'the pretrained model to use')
parser.add_argument('--content-image', type=str, default='input/IMG_4343.jpg',
help='the content image')
parser.add_argument('--style-image', type=str, default='input/starry_night.jpg',
help='the style image')
parser.add_argument('--stop-eps', type=float, default=.005,
help='stop if the relative chanage is less than eps')
parser.add_argument('--content-weight', type=float, default=10,
help='the weight for the content image')
parser.add_argument('--style-weight', type=float, default=1,
help='the weight for the style image')
parser.add_argument('--tv-weight', type=float, default=1e-2,
help='the magtitute on TV loss')
parser.add_argument('--max-num-epochs', type=int, default=1000,
help='the maximal number of training epochs')
parser.add_argument('--max-long-edge', type=int, default=600,
help='resize the content image')
parser.add_argument('--lr', type=float, default=.001,
help='the initial learning rate')
parser.add_argument('--gpu', type=int, default=0,
help='which gpu card to use, -1 means using cpu')
parser.add_argument('--output_dir', type=str, default='output/',
help='the output image')
parser.add_argument('--save-epochs', type=int, default=50,
help='save the output every n epochs')
parser.add_argument('--remove-noise', type=float, default=.02,
help='the magtitute to remove noise')
parser.add_argument('--lr-sched-delay', type=int, default=75,
help='how many epochs between decreasing learning rate')
parser.add_argument('--lr-sched-factor', type=int, default=0.9,
help='factor to decrease learning rate on schedule')
if arglist is None:
return parser.parse_args()
else:
return parser.parse_args(arglist)
示例12: PreprocessStyleImage
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def PreprocessStyleImage(path, shape):
img = io.imread(path)
resized_img = transform.resize(img, (shape[2], shape[3]))
sample = np.asarray(resized_img) * 256
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
sample[0, :] -= 123.68
sample[1, :] -= 116.779
sample[2, :] -= 103.939
return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
示例13: PostprocessImage
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def PostprocessImage(img):
img = np.resize(img, (3, img.shape[2], img.shape[3]))
img[0, :] += 123.68
img[1, :] += 116.779
img[2, :] += 103.939
img = np.swapaxes(img, 1, 2)
img = np.swapaxes(img, 0, 2)
img = np.clip(img, 0, 255)
return img.astype('uint8')
示例14: PreprocessContentImage
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def PreprocessContentImage(path, short_edge, dshape=None):
img = io.imread(path)
#logging.info("load the content image, size = %s", img.shape[:2])
factor = float(short_edge) / min(img.shape[:2])
new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
resized_img = transform.resize(img, new_size)
sample = np.asarray(resized_img) * 256
if dshape is not None:
# random crop
xx = int((sample.shape[0] - dshape[2]))
yy = int((sample.shape[1] - dshape[3]))
xstart = random.randint(0, xx)
ystart = random.randint(0, yy)
xend = xstart + dshape[2]
yend = ystart + dshape[3]
sample = sample[xstart:xend, ystart:yend, :]
# swap axes to make image from (224, 224, 3) to (3, 224, 224)
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
# sub mean
sample[0, :] -= 123.68
sample[1, :] -= 116.779
sample[2, :] -= 103.939
#logging.info("resize the content image to %s", sample.shape)
return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
示例15: convert_to_batched_episodes
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import resize [as 別名]
def convert_to_batched_episodes(self, episodes, max_length=None):
"""Convert batch-major list of episodes to time-major batch of episodes."""
lengths = [len(ep[-2]) for ep in episodes]
max_length = max_length or max(lengths)
new_episodes = []
for ep, length in zip(episodes, lengths):
initial, observations, actions, rewards, terminated = ep
observations = [np.resize(obs, [max_length + 1] + list(obs.shape)[1:])
for obs in observations]
actions = [np.resize(act, [max_length + 1] + list(act.shape)[1:])
for act in actions]
pads = np.array([0] * length + [1] * (max_length - length))
rewards = np.resize(rewards, [max_length]) * (1 - pads)
new_episodes.append([initial, observations, actions, rewards,
terminated, pads])
(initial, observations, actions, rewards,
terminated, pads) = zip(*new_episodes)
observations = [np.swapaxes(obs, 0, 1)
for obs in zip(*observations)]
actions = [np.swapaxes(act, 0, 1)
for act in zip(*actions)]
rewards = np.transpose(rewards)
pads = np.transpose(pads)
return (initial, observations, actions, rewards, terminated, pads)