本文整理汇总了Python中numpy.round方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.round方法的具体用法?Python numpy.round怎么用?Python numpy.round使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.round方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_bounding_boxes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def draw_bounding_boxes(image, gt_boxes, im_info):
num_boxes = gt_boxes.shape[0]
gt_boxes_new = gt_boxes.copy()
gt_boxes_new[:,:4] = np.round(gt_boxes_new[:,:4].copy() / im_info[2])
disp_image = Image.fromarray(np.uint8(image[0]))
for i in range(num_boxes):
this_class = int(gt_boxes_new[i, 4])
disp_image = _draw_single_box(disp_image,
gt_boxes_new[i, 0],
gt_boxes_new[i, 1],
gt_boxes_new[i, 2],
gt_boxes_new[i, 3],
'N%02d-C%02d' % (i, this_class),
FONT,
color=STANDARD_COLORS[this_class % NUM_COLORS])
image[0, :] = np.array(disp_image)
return image
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:21,代码来源:visualization.py
示例2: compute_mode
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def compute_mode(self):
"""
Pre-compute mode vectors from candidate locations (in spherical
coordinates).
"""
if self.num_loc is None:
raise ValueError('Lookup table appears to be empty. \
Run build_lookup().')
self.mode_vec = np.zeros((self.max_bin,self.M,self.num_loc),
dtype='complex64')
if (self.nfft % 2 == 1):
raise ValueError('Signal length must be even.')
f = 1.0 / self.nfft * np.linspace(0, self.nfft / 2, self.max_bin) \
* 1j * 2 * np.pi
for i in range(self.num_loc):
p_s = self.loc[:, i]
for m in range(self.M):
p_m = self.L[:, m]
if (self.mode == 'near'):
dist = np.linalg.norm(p_m - p_s, axis=1)
if (self.mode == 'far'):
dist = np.dot(p_s, p_m)
# tau = np.round(self.fs*dist/self.c) # discrete - jagged
tau = self.fs * dist / self.c # "continuous" - smoother
self.mode_vec[:, m, i] = np.exp(f * tau)
示例3: cantilever_beam_test
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def cantilever_beam_test():
#FEModel Test
model=FEModel()
model.add_node(0,0,0)
model.add_node(2,1,1)
E=1.999e11
mu=0.3
A=4.265e-3
J=9.651e-8
I3=6.572e-5
I2=3.301e-6
rho=7849.0474
model.add_beam(0,1,E,mu,A,I2,I3,J,rho)
model.set_node_force(1,(0,0,-1e6,0,0,0))
model.set_node_restraint(0,[True]*6)
model.assemble_KM()
model.assemble_f()
model.assemble_boundary()
solve_linear(model)
print(np.round(model.d_,6))
print("The result of node 1 should be about [0.12879,0.06440,-0.32485,-0.09320,0.18639,0]")
示例4: predict
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def predict(self):
"""Predict state vector u and variance of uncertainty P (covariance).
where,
u: previous state vector
P: previous covariance matrix
F: state transition matrix
Q: process noise matrix
Equations:
u'_{k|k-1} = Fu'_{k-1|k-1}
P_{k|k-1} = FP_{k-1|k-1} F.T + Q
where,
F.T is F transpose
Args:
None
Return:
vector of predicted state estimate
"""
# Predicted state estimate
self.u = np.round(np.dot(self.F, self.u))
# Predicted estimate covariance
self.P = np.dot(self.F, np.dot(self.P, self.F.T)) + self.Q
self.lastResult = self.u # same last predicted result
return self.u
示例5: _uniform_embed
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def _uniform_embed(self, embed_dict, words_dict):
"""
:param embed_dict:
:param words_dict:
"""
print("loading pre_train embedding by uniform for out of vocabulary.")
embeddings = np.zeros((int(self.words_count), int(self.dim)))
inword_list = {}
for word in words_dict:
if word in embed_dict:
embeddings[words_dict[word]] = np.array([float(i) for i in embed_dict[word]], dtype='float32')
inword_list[words_dict[word]] = 1
self.exact_count += 1
elif word.lower() in embed_dict:
embeddings[words_dict[word]] = np.array([float(i) for i in embed_dict[word.lower()]], dtype='float32')
inword_list[words_dict[word]] = 1
self.fuzzy_count += 1
else:
self.oov_count += 1
uniform_col = np.random.uniform(-0.25, 0.25, int(self.dim)).round(6) # uniform
for i in range(len(words_dict)):
if i not in inword_list and i != self.padID:
embeddings[i] = uniform_col
final_embed = torch.from_numpy(embeddings).float()
return final_embed
示例6: cortex_to_angle
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def cortex_to_angle(self, x, y):
iterX = hasattr(x, '__iter__')
iterY = hasattr(y, '__iter__')
jarr = None
if iterX and iterY:
if len(x) != len(y):
raise RuntimeError('Arguments x and y must be the same length!')
jarr = self._java_object.cortexToAngle(to_java_doubles(x), to_java_doubles(y))
elif iterX:
jarr = self._java_object.cortexToAngle(to_java_doubles(x),
to_java_doubles([y for i in x]))
elif iterY:
jarr = self._java_object.cortexToAngle(to_java_doubles([x for i in y]),
to_java_doubles(y))
else:
return self._java_object.cortexToAngle(x, y)
dat = np.asarray([[c for c in r] for r in jarr])
a = dat[:,2]
a = np.round(np.abs(a))
a[a > 3] = 0
dat[:,2] = a
return dat
示例7: test_lda
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def test_lda(self):
"""
Linear Disciminant Analysis
"""
np.random.seed(100)
N = 150
classes = np.array(["1", "a", 3])
cols = 4
x = np.random.random((N, cols)) # random data
labels = np.random.choice(classes, size=N) # random labels
# LDA components
out = pa.preprocess.LDA_discriminants(x, labels)
self.assertEqual(np.round(np.array(out).mean(), 5), 0.01298)
# LDA analysis
new_x = pa.preprocess.LDA(x, labels, n=2)
self.assertEqual(np.round(np.array(new_x).mean(), 5), -0.50907)
self.assertEqual(new_x.shape, (150, 2))
示例8: resize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def resize(im, short, max_size):
"""
only resize input image to target size and return scale
:param im: BGR image input by opencv
:param short: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
:return: resized image (NDArray) and scale (float)
"""
im_shape = im.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
im_scale = float(short) / float(im_size_min)
# prevent bigger axis from being more than max_size:
if np.round(im_scale * im_size_max) > max_size:
im_scale = float(max_size) / float(im_size_max)
im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
return im, im_scale
示例9: _project_to_map
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def _project_to_map(map, vertex, wt=None, ignore_points_outside_map=False):
"""Projects points to map, returns how many points are present at each
location."""
num_points = np.zeros((map.size[1], map.size[0]))
vertex_ = vertex[:, :2] - map.origin
vertex_ = np.round(vertex_ / map.resolution).astype(np.int)
if ignore_points_outside_map:
good_ind = np.all(np.array([vertex_[:,1] >= 0, vertex_[:,1] < map.size[1],
vertex_[:,0] >= 0, vertex_[:,0] < map.size[0]]),
axis=0)
vertex_ = vertex_[good_ind, :]
if wt is not None:
wt = wt[good_ind, :]
if wt is None:
np.add.at(num_points, (vertex_[:, 1], vertex_[:, 0]), 1)
else:
assert(wt.shape[0] == vertex.shape[0]), \
'number of weights should be same as vertices.'
np.add.at(num_points, (vertex_[:, 1], vertex_[:, 0]), wt)
return num_points
示例10: raw_valid_fn_vec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def raw_valid_fn_vec(self, xyt):
"""Returns if the given set of nodes is valid or not."""
height = self.traversible.shape[0]
width = self.traversible.shape[1]
x = np.round(xyt[:,[0]]).astype(np.int32)
y = np.round(xyt[:,[1]]).astype(np.int32)
is_inside = np.all(np.concatenate((x >= 0, y >= 0,
x < width, y < height), axis=1), axis=1)
x = np.minimum(np.maximum(x, 0), width-1)
y = np.minimum(np.maximum(y, 0), height-1)
ind = np.ravel_multi_index((y,x), self.traversible.shape)
is_traversible = self.traversible.ravel()[ind]
is_valid = np.all(np.concatenate((is_inside[:,np.newaxis], is_traversible),
axis=1), axis=1)
return is_valid
示例11: test_convert_to_normalized_and_back
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def test_convert_to_normalized_and_back(self):
coordinates = np.random.uniform(size=(100, 4))
coordinates = np.round(np.sort(coordinates) * 200)
coordinates[:, 2:4] += 1
coordinates[99, :] = [0, 0, 201, 201]
img = tf.ones((128, 202, 202, 3))
boxlist = box_list.BoxList(tf.constant(coordinates, tf.float32))
boxlist = box_list_ops.to_normalized_coordinates(boxlist,
tf.shape(img)[1],
tf.shape(img)[2])
boxlist = box_list_ops.to_absolute_coordinates(boxlist,
tf.shape(img)[1],
tf.shape(img)[2])
with self.test_session() as sess:
out = sess.run(boxlist.get())
self.assertAllClose(out, coordinates)
示例12: prep_im_for_blob
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def prep_im_for_blob(im, pixel_means, pixel_stds, target_size, max_size):
"""Mean subtract and scale an image for use in a blob."""
im = im.astype(np.float32, copy=False)
im /= 255.0
im -= pixel_means
im /= pixel_stds
# im = im[:, :, ::-1]
im_shape = im.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
im_scale = float(target_size) / float(im_size_min)
# Prevent the biggest axis from being more than MAX_SIZE
# if np.round(im_scale * im_size_max) > max_size:
# im_scale = float(max_size) / float(im_size_max)
# im = imresize(im, im_scale)
im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,
interpolation=cv2.INTER_LINEAR)
return im, im_scale
示例13: vis_det_and_mask
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def vis_det_and_mask(im, class_name, dets, masks, thresh=0.8):
"""Visual debugging of detections."""
num_dets = np.minimum(10, dets.shape[0])
colors_mask = random_colors(num_dets)
colors_bbox = np.round(np.random.rand(num_dets, 3) * 255)
# sort rois according to the coordinates, draw upper bbox first
draw_mask = np.zeros(im.shape[:2], dtype=np.uint8)
for i in range(1):
bbox = tuple(int(np.round(x)) for x in dets[i, :4])
mask = masks[i, :, :]
full_mask = unmold_mask(mask, bbox, im.shape)
score = dets[i, -1]
if score > thresh:
word_width = len(class_name)
cv2.rectangle(im, bbox[0:2], bbox[2:4], colors_bbox[i], 2)
cv2.rectangle(im, bbox[0:2], (bbox[0] + 18 + word_width*8, bbox[1]+15), colors_bbox[i], thickness=cv2.FILLED)
apply_mask(im, full_mask, draw_mask, colors_mask[i], 0.5)
draw_mask += full_mask
cv2.putText(im, '%s' % (class_name), (bbox[0]+5, bbox[1] + 12), cv2.FONT_HERSHEY_PLAIN,
1.0, (255,255,255), thickness=1)
return im
示例14: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def __init__(self, w_in, w_out, stride, bm, gw, se_r):
super(BottleneckTransform, self).__init__()
w_b = int(round(w_out * bm))
g = w_b // gw
self.a = nn.Conv2d(w_in, w_b, 1, stride=1, padding=0, bias=False)
self.a_bn = nn.BatchNorm2d(w_b, eps=1e-5, momentum=0.1)
self.a_relu = nn.ReLU(inplace=True)
self.b = nn.Conv2d(w_b, w_b, 3, stride=stride, padding=1, groups=g, bias=False)
self.b_bn = nn.BatchNorm2d(w_b, eps=1e-5, momentum=0.1)
self.b_relu = nn.ReLU(inplace=True)
if se_r:
w_se = int(round(w_in * se_r))
self.se = SE(w_b, w_se)
self.c = nn.Conv2d(w_b, w_out, 1, stride=1, padding=0, bias=False)
self.c_bn = nn.BatchNorm2d(w_out, eps=1e-5, momentum=0.1)
self.c_bn.final_bn = True
示例15: forward
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import round [as 别名]
def forward(self, x):
for layer in self.children():
x = layer(x)
return x
# @staticmethod
# def complexity(cx, w_in, w_out, stride, bm, gw, se_r):
# w_b = int(round(w_out * bm))
# g = w_b // gw
# cx = net.complexity_conv2d(cx, w_in, w_b, 1, 1, 0)
# cx = net.complexity_batchnorm2d(cx, w_b)
# cx = net.complexity_conv2d(cx, w_b, w_b, 3, stride, 1, g)
# cx = net.complexity_batchnorm2d(cx, w_b)
# if se_r:
# w_se = int(round(w_in * se_r))
# cx = SE.complexity(cx, w_b, w_se)
# cx = net.complexity_conv2d(cx, w_b, w_out, 1, 1, 0)
# cx = net.complexity_batchnorm2d(cx, w_out)
# return cx