本文整理汇总了Python中numpy.ogrid方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.ogrid方法的具体用法?Python numpy.ogrid怎么用?Python numpy.ogrid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.ogrid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _bilinear_upsampling_weights
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def _bilinear_upsampling_weights(weight_shape):
# weight_shape must be (width, height, n_channels, n_channels)
if weight_shape[-1] != weight_shape[-2]:
raise ValueError("Number of input channels must be the same as the number of input channels.")
weight = np.zeros(weight_shape, dtype=np.float32)
# create single upsampling kernel for one channel
# according to http://warmspringwinds.github.io/tensorflow/tf-slim/2016/11/22/upsampling-and-image-segmentation-with-tensorflow-and-tf-slim/
grid = np.ogrid[:weight_shape[0], :weight_shape[1]]
factors = [(s+1)//2 for s in weight_shape[:2]]
centers = [(s+1)//2 - 0.5*(s%2 + 1) for s in weight_shape[:2]]
upsampling_kernel = (1-abs(grid[0] - centers[0]) / factors[0]) * (1-abs(grid[1] - centers[1]) / factors[1])
for i in range(weight_shape[-1]):
weight[:, :, i, i] = upsampling_kernel
return weight
示例2: execute_agg
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def execute_agg(cls, ctx, op):
axis = cls.get_arg_axis(op.axis, op.inputs[0].ndim)
(vals, arg), device_id, xp = as_same_device(
ctx[op.inputs[0].key], device=op.device, ret_extra=True)
func_name = getattr(cls, '_func_name')
arg_func = getattr(xp, func_name)
with device(device_id):
if xp.any(xp.isnan(vals)) and 'nan' in func_name:
raise ValueError("All NaN slice encountered")
if axis is None:
local_args = arg_func(vals, axis=axis)
arg = arg.ravel()[local_args]
else:
local_args = arg_func(vals, axis=axis)
inds = np.ogrid[tuple(map(slice, local_args.shape))]
if xp != np:
inds = [xp.asarray(it) for it in inds]
inds.insert(axis, local_args)
arg = arg[tuple(inds)]
ctx[op.outputs[0].key] = arg
示例3: execute_combine
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def execute_combine(cls, ctx, op):
axis = cls.get_arg_axis(op.axis, op.inputs[0].ndim)
(vals, arg), device_id, xp = as_same_device(
ctx[op.inputs[0].key], device=op.device, ret_extra=True)
func_name = getattr(cls, '_func_name')
arg_func = getattr(xp, func_name)
with device(device_id):
if axis is None:
local_args = arg_func(vals, axis=axis).reshape(op.outputs[0].shape)
vals = vals.ravel()[local_args]
arg = arg.ravel()[local_args]
else:
local_args = arg_func(vals, axis=axis)
inds = np.ogrid[tuple(map(slice, local_args.shape))]
if xp != np:
inds = [xp.asarray(it) for it in inds]
inds.insert(axis, local_args)
inds_tuple = tuple(inds)
vals = vals[inds_tuple].reshape(op.outputs[0].shape)
arg = arg[inds_tuple].reshape(op.outputs[0].shape)
ctx[op.outputs[0].key] = (vals, arg)
示例4: bilinear_interpolation_kernel
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def bilinear_interpolation_kernel(in_channels, out_channels, ksize):
"""calculate a bilinear interpolation kernel
Args:
in_channels (int): Number of channels of input arrays. If ``None``,
parameter initialization will be deferred until the first forward
data pass at which time the size will be determined.
out_channels (int): Number of channels of output arrays.
ksize (int): Size of filters (a.k.a. kernels).
"""
factor = (ksize + 1) / 2
if ksize % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:ksize, :ksize]
k = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
W = np.zeros((in_channels, out_channels, ksize, ksize)).astype(np.float32)
W[range(in_channels), range(out_channels), :, :] = k
return W
示例5: make_bilinear_weights
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def make_bilinear_weights(size, num_channels):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
filt = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
# print(filt)
filt = torch.from_numpy(filt)
w = torch.zeros(num_channels, num_channels, size, size)
w.requires_grad = False
for i in range(num_channels):
for j in range(num_channels):
if i == j:
w[i, j] = filt
return w
示例6: _gaussian_2d
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def _gaussian_2d(shape, sigma=1):
"""Generate 2d gaussian.
Parameters
----------
shape : tuple of int
The shape of the gaussian.
sigma : float
Sigma for gaussian.
Returns
-------
float
2D gaussian kernel.
"""
m, n = [(ss - 1.) / 2. for ss in shape]
y, x = np.ogrid[-m:m+1, -n:n+1]
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
return h
示例7: main
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def main(imgsize):
y, x = np.ogrid[6: -6: imgsize*2j, -6: 6: imgsize*2j]
z = x + y*1j
z = RiemannSphere(Klein(Mobius(Klein(z))))
# define colors in hsv space
H = np.sin(z[0]*np.pi)**2
S = np.cos(z[1]*np.pi)**2
V = abs(np.sin(z[2]*np.pi) * np.cos(z[2]*np.pi))**0.2
HSV = np.stack((H, S, V), axis=2)
# transform to rgb space
img = hsv_to_rgb(HSV)
fig = plt.figure(figsize=(imgsize/100.0, imgsize/100.0), dpi=100)
ax = fig.add_axes([0, 0, 1, 1], aspect=1)
ax.axis('off')
ax.imshow(img)
fig.savefig('kaleidoscope.png')
示例8: Hankel
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def Hankel(first_col, last_row=None):
"""
Construct a Hankel array, whose skew diagonals are constant.
Args:
``first_col``: 1D array corresponding to first column of Hankel array.
Kwargs:
``last_row``: 1D array corresponding to the last row of Hankel array.
First element will be ignored. Default is an array of zeros of the same
size as ``first_col``.
Returns:
Hankel: 2D array with dimensions ``[len(first_col), len(last_row)]``.
"""
first_col = np.array(first_col).flatten()
if last_row is None:
last_row = np.zeros(first_col.shape)
else:
last_row = last_row.flatten()
unique_vals = np.concatenate((first_col, last_row[1:]))
a, b = np.ogrid[0:len(first_col), 0:len(last_row)]
indices = a + b
return unique_vals[indices]
示例9: apply
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def apply(self):
sc = self.scene
org = self.original
factor = self.factor
sx, sy = sc.displacement.shape
gx, gy = num.ogrid[0:sx, 0:sy]
regions = sy/factor * (gx/factor) + gy/factor
indices = num.arange(regions.max() + 1)
def block_downsample(arr):
res = ndimage.mean(
arr,
labels=regions,
index=indices)
res.shape = (sx/factor, sy/factor)
return res
sc.displacement = block_downsample(sc.displacement)
sc.theta = block_downsample(sc.theta)
sc.phi = block_downsample(sc.phi)
sc.frame.dLat = org['frame.dLat'] * self.factor
sc.frame.dLon = org['frame.dLat'] * self.factor
示例10: test_bbox_inches
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def test_bbox_inches():
if not check_for('xelatex'):
raise SkipTest('xelatex + pgf is required')
rc_xelatex = {'font.family': 'serif',
'pgf.rcfonts': False}
mpl.rcParams.update(rc_xelatex)
Y, X = np.ogrid[-1:1:40j, -1:1:40j]
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.plot(range(5))
ax2 = fig.add_subplot(122)
ax2.plot(range(5))
plt.tight_layout()
bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox})
示例11: createHanningMats
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def createHanningMats(self):
hann2t, hann1t = np.ogrid[0:self.size_patch[0], 0:self.size_patch[1]]
hann1t = 0.5 * (1 - np.cos(2 * np.pi * hann1t / (self.size_patch[1] - 1)))
hann2t = 0.5 * (1 - np.cos(2 * np.pi * hann2t / (self.size_patch[0] - 1)))
hann2d = hann2t * hann1t
if self._hogfeatures:
hann1d = hann2d.reshape(self.size_patch[0] * self.size_patch[1])
self.hann = np.zeros((self.size_patch[2], 1), np.float32) + hann1d
#相当于把1D汉宁窗复制成多个通道
else:
self.hann = hann2d
self.hann = self.hann.astype(np.float32)
# 创建高斯峰函数,函数只在第一帧的时候执行(高斯响应)
示例12: onehottify_2d_array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def onehottify_2d_array(a):
"""
https://stackoverflow.com/questions/36960320/convert-a-2d-matrix-to-a-3d-one-hot-matrix-numpy
:param a: 2-dimensional array.
:return: 3-dim array where last dim corresponds to one-hot encoded vectors.
"""
# https://stackoverflow.com/a/46103129/ @Divakar
def all_idx(idx, axis):
grid = np.ogrid[tuple(map(slice, idx.shape))]
grid.insert(axis, idx)
return tuple(grid)
num_columns = a.max() + 1
out = np.zeros(a.shape + (num_columns,), dtype=int)
out[all_idx(a, axis=2)] = 1
return out
示例13: get
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def get(self, shape=(3, 3), sigma=0.5):
if '%d_%d' % (int(shape[0]), int(sigma * 10)) not in self.kernel_set.keys():
m, n = [(ss - 1.0) / 2.0 for ss in shape]
y, x = np.ogrid[-m:m + 1, -n:n + 1]
h = np.exp(-(x * x + y * y) / (2.0 * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
# import pdb
# pdb.set_trace()
t = h[0][int(m)]
h[h < t] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
self.kernel_set['%d_%d' % (int(shape[0]), int(sigma * 10))] = h
return h
else:
return self.kernel_set['%d_%d' % (int(shape[0]), int(sigma * 10))]
示例14: create_circular_mask
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def create_circular_mask(h, w, center=None, radius=None, angle=None, thick=0):
# img = np.random.randint(0,2,(4,224,224))
# print (img.shape)
# mask = create_circular_mask(224,224, center = (100,100), radius = 20)
# img[3,~mask] = 0
# plt.imshow(img[3,:,:])
# plt.show()
if center is None: # use the middle of the image
center = [int(w/2), int(h/2)]
if radius is None: # use the smallest distance between the center and image walls
radius = min(center[0], center[1], w-center[0], h-center[1])
Y, X = np.ogrid[:h, :w]
dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
if angle is None:
mask = (dist_from_center <= radius)
else:
angle_from_center = np.arctan2(Y-center[1],X-center[0])
mask = (dist_from_center <= radius) & (np.abs(np.unwrap(angle_from_center-angle)) * dist_from_center <= thick)
#(angle_from_center < angle+0.15/(dist_from_center+0.01)) & (angle_from_center > angle-0.15/(dist_from_center+0.01))
return mask
示例15: get_upsampling_weight
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ogrid [as 别名]
def get_upsampling_weight(in_channels, out_channels, kernel_size):
factor = (kernel_size + 1) // 2
if kernel_size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:kernel_size, :kernel_size]
filt = (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
weight = np.zeros(
(in_channels,
out_channels,
kernel_size,
kernel_size),
dtype=np.float64)
weight[list(range(in_channels)), list(range(out_channels)), :, :] = filt
return torch.from_numpy(weight).float()