本文整理汇总了Python中numpy.ceil方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.ceil方法的具体用法?Python numpy.ceil怎么用?Python numpy.ceil使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.ceil方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _draw_single_box
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def _draw_single_box(image, xmin, ymin, xmax, ymax, display_str, font, color='black', thickness=4):
draw = ImageDraw.Draw(image)
(left, right, top, bottom) = (xmin, xmax, ymin, ymax)
draw.line([(left, top), (left, bottom), (right, bottom),
(right, top), (left, top)], width=thickness, fill=color)
text_bottom = bottom
# Reverse list and print from bottom to top.
text_width, text_height = font.getsize(display_str)
margin = np.ceil(0.05 * text_height)
draw.rectangle(
[(left, text_bottom - text_height - 2 * margin), (left + text_width,
text_bottom)],
fill=color)
draw.text(
(left + margin, text_bottom - text_height - margin),
display_str,
fill='black',
font=font)
return image
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:22,代码来源:visualization.py
示例2: create_image_grid
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def create_image_grid(images, grid_size=None):
assert images.ndim == 3 or images.ndim == 4
num, img_w, img_h = images.shape[0], images.shape[-1], images.shape[-2]
if grid_size is not None:
grid_w, grid_h = tuple(grid_size)
else:
grid_w = max(int(np.ceil(np.sqrt(num))), 1)
grid_h = max((num - 1) // grid_w + 1, 1)
grid = np.zeros(list(images.shape[1:-2]) + [grid_h * img_h, grid_w * img_w], dtype=images.dtype)
for idx in range(num):
x = (idx % grid_w) * img_w
y = (idx // grid_w) * img_h
grid[..., y : y + img_h, x : x + img_w] = images[idx]
return grid
示例3: __iter__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def __iter__(self):
indices = []
for i, size in enumerate(self.group_sizes):
if size == 0:
continue
indice = np.where(self.flag == i)[0]
assert len(indice) == size
np.random.shuffle(indice)
num_extra = int(np.ceil(size / self.samples_per_gpu)
) * self.samples_per_gpu - len(indice)
indice = np.concatenate(
[indice, np.random.choice(indice, num_extra)])
indices.append(indice)
indices = np.concatenate(indices)
indices = [
indices[i * self.samples_per_gpu:(i + 1) * self.samples_per_gpu]
for i in np.random.permutation(
range(len(indices) // self.samples_per_gpu))
]
indices = np.concatenate(indices)
indices = indices.astype(np.int64).tolist()
assert len(indices) == self.num_samples
return iter(indices)
示例4: get_deep_representations
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def get_deep_representations(model, X, batch_size=256):
"""
TODO
:param model:
:param X:
:param batch_size:
:return:
"""
# last hidden layer is always at index -4
output_dim = model.layers[-4].output.shape[-1].value
get_encoding = K.function(
[model.layers[0].input, K.learning_phase()],
[model.layers[-4].output]
)
n_batches = int(np.ceil(X.shape[0] / float(batch_size)))
output = np.zeros(shape=(len(X), output_dim))
for i in range(n_batches):
output[i * batch_size:(i + 1) * batch_size] = \
get_encoding([X[i * batch_size:(i + 1) * batch_size], 0])[0]
return output
示例5: create_sprite_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def create_sprite_image(images):
if isinstance(images, list):
images = np.array(images)
img_h = images.shape[1]
img_w = images.shape[2]
# sprite 可以理解为所有小图片拼成的大正方形矩阵
m = int(np.ceil(np.sqrt(images.shape[0])))
# 使用全 1 来初始化最终的大图片
sprite_image = np.ones((img_h*m, img_w*m))
for i in range(m):
for j in range(m):
# 计算当前图片编号
cur = i * m + j
if cur < images.shape[0]:
# 将小图片的内容复制到最终的 sprite 图像
sprite_image[i*img_h:(i+1)*img_h,
j*img_w:(j+1)*img_w] = images[cur]
return sprite_image
# 加载 mnist 数据,制定 one_hot=False,得到的 labels 就是一个数字,而不是一个向量
示例6: curve_length
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def curve_length(self, start=None, end=None, precision=0.01):
'''
Calculates the length of the curve by dividing the curve up
into pieces of parameterized-length <precision>.
'''
if start is None: start = self.t[0]
if end is None: end = self.t[-1]
from scipy import interpolate
if self.order == 1:
# we just want to add up along the steps...
ii = [ii for (ii,t) in enumerate(self.t) if start < t and t < end]
ts = np.concatenate([[start], self.t[ii], [end]])
xy = np.vstack([[self(start)], self.coordinates[:,ii].T, [self(end)]])
return np.sum(np.sqrt(np.sum((xy[1:] - xy[:-1])**2, axis=1)))
else:
t = np.linspace(start, end, int(np.ceil((end-start)/precision)))
dt = t[1] - t[0]
dx = interpolate.splev(t, self.splrep[0], der=1)
dy = interpolate.splev(t, self.splrep[1], der=1)
return np.sum(np.sqrt(dx**2 + dy**2)) * dt
示例7: visual
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def visual(title, X, activation):
'''create a grid of images and save it as a final image
title : grid image name
X : array of images
'''
assert len(X.shape) == 4
X = X.transpose((0, 2, 3, 1))
if activation == 'sigmoid':
X = np.clip((X)*(255.0), 0, 255).astype(np.uint8)
elif activation == 'tanh':
X = np.clip((X+1.0)*(255.0/2.0), 0, 255).astype(np.uint8)
n = np.ceil(np.sqrt(X.shape[0]))
buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
for i, img in enumerate(X):
fill_buf(buff, i, img, X.shape[1:3])
cv2.imwrite('%s.jpg' % (title), buff)
示例8: plot_images
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def plot_images(imgs, targets, paths=None, fname='images.jpg'):
# Plots training images overlaid with targets
imgs = imgs.cpu().numpy()
targets = targets.cpu().numpy()
# targets = targets[targets[:, 1] == 21] # plot only one class
fig = plt.figure(figsize=(10, 10))
bs, _, h, w = imgs.shape # batch size, _, height, width
bs = min(bs, 16) # limit plot to 16 images
ns = np.ceil(bs ** 0.5) # number of subplots
for i in range(bs):
boxes = xywh2xyxy(targets[targets[:, 0] == i, 2:6]).T
boxes[[0, 2]] *= w
boxes[[1, 3]] *= h
plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0))
plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-')
plt.axis('off')
if paths is not None:
s = Path(paths[i]).name
plt.title(s[:min(len(s), 40)], fontdict={'size': 8}) # limit to 40 characters
fig.tight_layout()
fig.savefig(fname, dpi=200)
plt.close()
示例9: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def __call__(self, input):
with tf.variable_scope(self.name, reuse=self._reuse):
if not self._reuse:
print('\033[93m'+self.name+'\033[0m')
_ = input
num_channel = [32, 64, 128, 256, 256, 512]
num_layer = np.ceil(np.log2(min(_.shape.as_list()[1:3]))).astype(np.int)
for i in range(num_layer):
ch = num_channel[i] if i < len(num_channel) else 512
_ = conv2d(_, ch, self._is_train, info=not self._reuse,
norm=self._norm_type, name='conv{}'.format(i+1))
_ = conv2d(_, int(num_channel[i]/4), self._is_train, k=1, s=1,
info=not self._reuse, norm='None', name='conv{}'.format(i+2))
_ = conv2d(_, self._num_class+1, self._is_train, k=1, s=1, info=not self._reuse,
activation_fn=None, norm='None',
name='conv{}'.format(i+3))
_ = tf.squeeze(_)
if not self._reuse:
log.info('discriminator output {}'.format(_.shape.as_list()))
self._reuse = True
self.var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.name)
return tf.nn.sigmoid(_), _
示例10: move
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def move(self, P0, P1):
"""
Move a point P0 to a new legal location
:param P0: ndarray[2]
:param P1: ndarray[2]
:return: ndarray[2]
"""
x_dist, y_dist = P1 - P0
tdist = np.sqrt(y_dist**2+x_dist**2)
if self.is_in(P1):
return P1
else:
x_steps = int(np.sign(x_dist) * np.ceil(abs(x_dist / self.dx)))#, self.max_step
y_steps = int(np.sign(y_dist) * np.ceil(abs(y_dist / self.dy)))#, self.max_step
i0, j0 = self.locate_ij(P0)
P2 = self.locate_xy(i0, j0)
P_off = P2 - P0
self.loop_i = 0
i1, j1 = self.valid_move(i0, j0, x_steps, y_steps, P_off)
P2 = self.locate_xy(i1, j1) + P_off
return P2
示例11: tile_images
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def tile_images(img_nhwc):
"""
Tile N images into one big PxQ image
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
input: img_nhwc, list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = channel
returns:
bigim_HWc, ndarray with ndim=3
"""
img_nhwc = np.asarray(img_nhwc)
N, h, w, c = img_nhwc.shape
H = int(np.ceil(np.sqrt(N)))
W = int(np.ceil(float(N)/H))
img_nhwc = np.array(list(img_nhwc) + [img_nhwc[0]*0 for _ in range(N, H*W)])
img_HWhwc = img_nhwc.reshape(H, W, h, w, c)
img_HhWwc = img_HWhwc.transpose(0, 2, 1, 3, 4)
img_Hh_Ww_c = img_HhWwc.reshape(H*h, W*w, c)
return img_Hh_Ww_c
示例12: split4
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [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)
示例13: split8
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def split8(data, max_stride, margin):
splits = []
if isinstance(data, np.ndarray):
c, z, h, w = data.shape
else:
_,c, z, h, w = data.size()
z_width = np.ceil(float(z / 2 + margin)/max_stride).astype('int')*max_stride
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
for zz in [[0,z_width],[-z_width,None]]:
for hh in [[0,h_width],[-h_width,None]]:
for ww in [[0,w_width],[-w_width,None]]:
if isinstance(data, np.ndarray):
splits.append(data[np.newaxis, :, zz[0]:zz[1], hh[0]:hh[1], ww[0]:ww[1]])
else:
splits.append(data[:, :, zz[0]:zz[1], hh[0]:hh[1], ww[0]:ww[1]])
if isinstance(data, np.ndarray):
return np.concatenate(splits, 0)
else:
return torch.cat(splits, 0)
示例14: split32
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def split32(data, max_stride, margin):
splits = []
_,c, z, h, w = data.size()
z_width = np.ceil(float(z / 2 + margin)/max_stride).astype('int')*max_stride
w_width = np.ceil(float(w / 4 + margin)/max_stride).astype('int')*max_stride
h_width = np.ceil(float(h / 4 + margin)/max_stride).astype('int')*max_stride
w_pos = [w*3/8-w_width/2,
w*5/8-w_width/2]
h_pos = [h*3/8-h_width/2,
h*5/8-h_width/2]
for zz in [[0,z_width],[-z_width,None]]:
for hh in [[0,h_width],[h_pos[0],h_pos[0]+h_width],[h_pos[1],h_pos[1]+h_width],[-h_width,None]]:
for ww in [[0,w_width],[w_pos[0],w_pos[0]+w_width],[w_pos[1],w_pos[1]+w_width],[-w_width,None]]:
splits.append(data[:, :, zz[0]:zz[1], hh[0]:hh[1], ww[0]:ww[1]])
return torch.cat(splits, 0)
示例15: split64
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ceil [as 别名]
def split64(data, max_stride, margin):
splits = []
_,c, z, h, w = data.size()
z_width = np.ceil(float(z / 4 + margin)/max_stride).astype('int')*max_stride
w_width = np.ceil(float(w / 4 + margin)/max_stride).astype('int')*max_stride
h_width = np.ceil(float(h / 4 + margin)/max_stride).astype('int')*max_stride
z_pos = [z*3/8-z_width/2,
z*5/8-z_width/2]
w_pos = [w*3/8-w_width/2,
w*5/8-w_width/2]
h_pos = [h*3/8-h_width/2,
h*5/8-h_width/2]
for zz in [[0,z_width],[z_pos[0],z_pos[0]+z_width],[z_pos[1],z_pos[1]+z_width],[-z_width,None]]:
for hh in [[0,h_width],[h_pos[0],h_pos[0]+h_width],[h_pos[1],h_pos[1]+h_width],[-h_width,None]]:
for ww in [[0,w_width],[w_pos[0],w_pos[0]+w_width],[w_pos[1],w_pos[1]+w_width],[-w_width,None]]:
splits.append(data[:, :, zz[0]:zz[1], hh[0]:hh[1], ww[0]:ww[1]])
return torch.cat(splits, 0)