本文整理汇总了Python中numpy.ascontiguousarray方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.ascontiguousarray方法的具体用法?Python numpy.ascontiguousarray怎么用?Python numpy.ascontiguousarray使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.ascontiguousarray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: serialize_ndarray_b64
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def serialize_ndarray_b64(o):
"""
Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are
human-readable, but the array data itself is binary64 encoded.
Args:
o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.
Returns:
A dictionary that can be passed to :obj:`json.dumps`.
"""
if o.flags['C_CONTIGUOUS']:
o_data = o.data
else:
o_data = np.ascontiguousarray(o).data
data_b64 = base64.b64encode(o_data)
return dict(
_type='np.ndarray',
data=data_b64.decode('utf-8'),
dtype=o.dtype,
shape=o.shape)
示例2: tensor2imgs
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True):
"""Convert tensor to images.
Args:
tensor (torch.Tensor): Tensor that contains multiple images
mean (tuple[float], optional): Mean of images. Defaults to (0, 0, 0).
std (tuple[float], optional): Standard deviation of images.
Defaults to (1, 1, 1).
to_rgb (bool, optional): Whether convert the images to RGB format.
Defaults to True.
Returns:
list[np.ndarray]: A list that contains multiple images.
"""
num_imgs = tensor.size(0)
mean = np.array(mean, dtype=np.float32)
std = np.array(std, dtype=np.float32)
imgs = []
for img_id in range(num_imgs):
img = tensor[img_id, ...].cpu().numpy().transpose(1, 2, 0)
img = mmcv.imdenormalize(
img, mean, std, to_bgr=to_rgb).astype(np.uint8)
imgs.append(np.ascontiguousarray(img))
return imgs
示例3: load_default_object
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def load_default_object(self):
v = np.array([[0.0, 0.5, 0.0, 1.0, 1.0, 0.0, 1.0],
[-0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 1.0],
[0.5, -0.5, 0.0, 1.0, 1.0, 1.0, 1.0]], dtype=np.float32)
v = np.concatenate((v,v+0.1), axis=0)
v = np.ascontiguousarray(v, dtype=np.float32)
vbo = glGenBuffers(1)
glBindBuffer (GL_ARRAY_BUFFER, vbo)
glBufferData (GL_ARRAY_BUFFER, v.dtype.itemsize*v.size, v, GL_STATIC_DRAW)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 28, ctypes.c_void_p(0))
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 28, ctypes.c_void_p(12))
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
self.num_to_render = 6;
示例4: _load_mesh_into_gl
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def _load_mesh_into_gl(self, mesh, material):
vvt = np.concatenate((mesh.vertices, mesh.texturecoords[0,:,:2]), axis=1)
vvt = np.ascontiguousarray(vvt[mesh.faces.reshape((-1)),:], dtype=np.float32)
num = vvt.shape[0]
vvt = np.reshape(vvt, (-1))
vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vvt.dtype.itemsize*vvt.size, vvt, GL_STATIC_DRAW)
tbo = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, tbo)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, material.shape[1],
material.shape[0], 0, GL_RGB, GL_UNSIGNED_BYTE,
np.reshape(material, (-1)))
return num, vbo, tbo
示例5: __next__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def __next__(self):
self.count += 1
img0 = self.imgs.copy()
if cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
# Letterbox
img = [letterbox(x, new_shape=self.img_size, interp=cv2.INTER_LINEAR)[0] for x in img0]
# Stack
img = np.stack(img, 0)
# Normalize RGB
img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB
img = np.ascontiguousarray(img, dtype=np.float16 if self.half else np.float32) # uint8 to fp16/fp32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
return self.sources, img, img0, None
示例6: get_screen
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def get_screen(self, env):
screen = env.render(mode='rgb_array').transpose((2, 0, 1)) # transpose into torch order (CHW)
# Strip off the top and bottom of the screen
screen = screen[:, 160:320]
view_width = 320
cart_location = self.get_cart_location(env)
if cart_location < view_width // 2:
slice_range = slice(view_width)
elif cart_location > (self.screen_width - view_width // 2):
slice_range = slice(-view_width, None)
else:
slice_range = slice(cart_location - view_width // 2,
cart_location + view_width // 2)
# Strip off the edges, so that we have a square image centered on a cart
screen = screen[:, :, slice_range]
# Convert to float, rescale, convert to torch tensor
screen = np.ascontiguousarray(screen, dtype=np.float32) / 255
screen = torch.from_numpy(screen)
# Resize, and add a batch dimension (BCHW)
return resize(screen).unsqueeze(0)
示例7: default
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def default(self, obj: Any) -> Any:
try:
return pydantic_encoder(obj)
except TypeError:
pass
if isinstance(obj, np.ndarray):
if obj.shape:
data = {"_nd_": True, "dtype": obj.dtype.str, "data": np.ascontiguousarray(obj).tobytes().hex()}
if len(obj.shape) > 1:
data["shape"] = obj.shape
return data
else:
# Converts np.array(5) -> 5
return obj.tolist()
return json.JSONEncoder.default(self, obj)
示例8: _convert_method_output_to_tensor
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def _convert_method_output_to_tensor(file_or_fd: Any,
fn: Callable,
convert_contiguous: bool = False) -> Iterable[Tuple[str, Tensor]]:
r"""Takes a method invokes it. The output is converted to a tensor.
Args:
file_or_fd (str/FileDescriptor): File name or file descriptor
fn (Callable): Function that has the signature (file name/descriptor) and converts it to
Iterable[Tuple[str, Tensor]].
convert_contiguous (bool, optional): Determines whether the array should be converted into a
contiguous layout. (Default: ``False``)
Returns:
Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is vec/mat
"""
for key, np_arr in fn(file_or_fd):
if convert_contiguous:
np_arr = np.ascontiguousarray(np_arr)
yield key, torch.from_numpy(np_arr)
示例9: load_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def load_image(img_path, net_input_shape):
imgBGR = cv2.imread(img_path)
img = cv2.resize(imgBGR, net_input_shape)
# BGR -> RGB
#img = img[:,:, (2, 1, 0)]
## Method 1
# imgT = np.transpose(img, (2, 0, 1)) # c,w,h
# imgF = np.asarray(imgT, dtype=np.float32)
# mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
# imgS = np.subtract(imgF,mean)
## Method 2
imgF = np.asarray(img, dtype=np.float32)
mean = [128.0, 128.0, 128.0] # Caffe image mean
# mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
imgSS = np.subtract(imgF, mean)/128.0
imgS = np.transpose(imgSS, (2, 0, 1)) # c,w,h
# RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)
return imgBGR, np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous
示例10: load_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def load_image(img_path, net_input_shape):
img = cv2.resize(cv2.imread(img_path), net_input_shape)
# BGR -> RGB
#img = img[:,:, (2, 1, 0)]
## Method 1
# imgT = np.transpose(img, (2, 0, 1)) # c,w,h
# imgF = np.asarray(imgT, dtype=np.float32)
# mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
# imgS = np.subtract(imgF,mean)
## Method 2
imgF = np.asarray(img, dtype=np.float32)
mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
imgSS = np.subtract(imgF, mean)
imgS = np.transpose(imgSS, (2, 0, 1)) # CHW
# RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)
return np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous
示例11: load_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def load_image(img_path, net_input_shape):
img = cv2.resize(cv2.imread(img_path), net_input_shape)
# BGR -> RGB
#img = img[:,:, (2, 1, 0)]
## Method 1
# imgT = np.transpose(img, (2, 0, 1)) # c,w,h
# imgF = np.asarray(imgT, dtype=np.float32)
# mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
# imgS = np.subtract(imgF,mean)
## Method 2
imgF = np.asarray(img, dtype=np.float32)
mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
imgSS = np.subtract(imgF, mean)
imgS = np.transpose(imgSS, (2, 0, 1)) # CHW
# RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)
return np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous
示例12: load_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def load_image(img_path, net_input_shape):
imgBGR = cv2.imread(img_path)
img = cv2.resize(imgBGR, net_input_shape)
# BGR -> RGB
#img = img[:,:, (2, 1, 0)]
## Method 1
# imgT = np.transpose(img, (2, 0, 1)) # c,w,h
# imgF = np.asarray(imgT, dtype=np.float32)
# mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
# imgS = np.subtract(imgF,mean)
## Method 2
imgF = np.asarray(img, dtype=np.float32)
mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
imgSS = np.subtract(imgF, mean)
imgS = np.transpose(imgSS, (2, 0, 1)) # c,w,h
# RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)
return imgBGR, np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous
示例13: _fill_hprobs_block
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def _fill_hprobs_block(self, mxToFill, dest_indices, dest_param_indices1,
dest_param_indices2, evalTree, param_slice1, param_slice2,
comm=None, memLimit=None):
if param_slice1 is None or param_slice1.start is None: param_slice1 = slice(0, self.Np)
if param_slice2 is None or param_slice2.start is None: param_slice2 = slice(0, self.Np)
if dest_param_indices1 is None: dest_param_indices1 = slice(0, _slct.length(param_slice1))
if dest_param_indices2 is None: dest_param_indices2 = slice(0, _slct.length(param_slice2))
if self.mode == "direct":
raise NotImplementedError("hprobs does not support direct path-integral evaluation yet")
# hprobs = self.hprs_directly(evalTree, ...)
else: # "pruned" or "taylor order"
# evaluate derivative of polys
nEls = evalTree.num_final_elements()
polys = evalTree.merged_compact_polys
wrtInds1 = _np.ascontiguousarray(_slct.indices(param_slice1), _np.int64)
wrtInds2 = _np.ascontiguousarray(_slct.indices(param_slice2), _np.int64)
dpolys = _compact_deriv(polys[0], polys[1], wrtInds1)
hpolys = _compact_deriv(dpolys[0], dpolys[1], wrtInds2)
hprobs = _safe_bulk_eval_compact_polys(
hpolys[0], hpolys[1], self.paramvec, (nEls, len(wrtInds1), len(wrtInds2)))
_fas(mxToFill, [dest_indices, dest_param_indices1, dest_param_indices2], hprobs)
示例14: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def __init__(self, outcomes):
"""
Initialize a StabilizerEffectVec object.
Parameters
----------
outcomes : iterable
A list or other iterable of integer 0 or 1 outcomes specifying
which POVM effect vector this object represents within the
full `stabilizerPOVM`
"""
self._outcomes = _np.ascontiguousarray(_np.array(outcomes, int), _np.int64)
#Note: dtype='i' => int in Cython, whereas dtype=int/np.int64 => long in Cython
rep = replib.SBEffectRep(self._outcomes) # dim == 2**nqubits == 2**len(outcomes)
SPAMVec.__init__(self, rep, "stabilizer", "effect")
#def torep(self, typ, outvec=None):
# # changes to_statevec/to_dmvec -> todense, and have
# # torep create an effect rep object...
# return replib.SBEffectRep(_np.ascontiguousarray(self._outcomes, _np.int64))
示例15: soft_nms
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import ascontiguousarray [as 别名]
def soft_nms(
dets, sigma=0.5, overlap_thresh=0.3, score_thresh=0.001, method='linear'
):
"""Apply the soft NMS algorithm from https://arxiv.org/abs/1704.04503."""
if dets.shape[0] == 0:
return dets, []
methods = {'hard': 0, 'linear': 1, 'gaussian': 2}
assert method in methods, 'Unknown soft_nms method: {}'.format(method)
dets, keep = cython_nms.soft_nms(
np.ascontiguousarray(dets, dtype=np.float32),
np.float32(sigma),
np.float32(overlap_thresh),
np.float32(score_thresh),
np.uint8(methods[method])
)
return dets, keep