本文整理匯總了Python中numpy.ndarray方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.ndarray方法的具體用法?Python numpy.ndarray怎麽用?Python numpy.ndarray使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.ndarray方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_cls_results
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def get_cls_results(det_results, annotations, class_id):
"""Get det results and gt information of a certain class.
Args:
det_results (list[list]): Same as `eval_map()`.
annotations (list[dict]): Same as `eval_map()`.
class_id (int): ID of a specific class.
Returns:
tuple[list[np.ndarray]]: detected bboxes, gt bboxes, ignored gt bboxes
"""
cls_dets = [img_res[class_id] for img_res in det_results]
cls_gts = []
cls_gts_ignore = []
for ann in annotations:
gt_inds = ann['labels'] == class_id
cls_gts.append(ann['bboxes'][gt_inds, :])
if ann.get('labels_ignore', None) is not None:
ignore_inds = ann['labels_ignore'] == class_id
cls_gts_ignore.append(ann['bboxes_ignore'][ignore_inds, :])
else:
cls_gts_ignore.append(np.empty((0, 4), dtype=np.float32))
return cls_dets, cls_gts, cls_gts_ignore
示例2: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def __init__(self, masks, height, width):
self.height = height
self.width = width
if len(masks) == 0:
self.masks = np.empty((0, self.height, self.width), dtype=np.uint8)
else:
assert isinstance(masks, (list, np.ndarray))
if isinstance(masks, list):
assert isinstance(masks[0], np.ndarray)
assert masks[0].ndim == 2 # (H, W)
else:
assert masks.ndim == 3 # (N, H, W)
self.masks = np.stack(masks).reshape(-1, height, width)
assert self.masks.shape[1] == self.height
assert self.masks.shape[2] == self.width
示例3: __call__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def __call__(self, video):
"""
Args:
video (numpy.ndarray): Video to be scaled.
Returns:
numpy.ndarray: Rescaled video.
"""
if isinstance(self.size, int):
w, h = video.shape[-2], video.shape[-3]
if (w <= h and w == self.size) or (h <= w and h == self.size):
return video
if w < h:
ow = self.size
oh = int(self.size*h/w)
return resize(video, (ow, oh), self.interpolation)
else:
oh = self.size
ow = int(self.size*w/h)
return resize(video, (ow, oh), self.interpolation)
else:
return resize(video, self.size, self.interpolation)
示例4: _serialize_data
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def _serialize_data(self, data):
# Default to raw bytes
type_ = _BYTES
if isinstance(data, np.ndarray):
# When the data is a numpy array, use the more compact native
# numpy format.
buf = io.BytesIO()
np.save(buf, data)
data = buf.getvalue()
type_ = _NUMPY
elif not isinstance(data, (bytearray, bytes)):
# Everything else except byte data is serialized in pickle format.
data = pickle.dumps(data)
type_ = _PICKLE
if self.compress:
# Optional compression
data = lz4.frame.compress(data)
return type_, data
示例5: read_common_mat
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def read_common_mat(fd):
"""
Read common matrix(for class Matrix in kaldi setup)
see matrix/kaldi-matrix.cc::
void Matrix<Real>::Read(std::istream & is, bool binary, bool add)
Return a numpy ndarray object
"""
mat_type = read_token(fd)
print_info(f'\tType of the common matrix: {mat_type}')
if mat_type not in ["FM", "DM"]:
raise RuntimeError(f"Unknown matrix type in kaldi: {mat_type}")
float_size = 4 if mat_type == 'FM' else 8
float_type = np.float32 if mat_type == 'FM' else np.float64
num_rows = read_int32(fd)
num_cols = read_int32(fd)
print_info(f'\tSize of the common matrix: {num_rows} x {num_cols}')
mat_data = fd.read(float_size * num_cols * num_rows)
mat = np.fromstring(mat_data, dtype=float_type)
return mat.reshape(num_rows, num_cols)
示例6: read_compress_mat
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def read_compress_mat(fd):
"""
Reference to function Read in CompressMatrix
Return a numpy ndarray object
"""
cps_type = read_token(fd)
print_info(f'\tFollowing matrix type: {cps_type}')
head = struct.unpack('ffii', fd.read(16))
print_info(f'\tCompress matrix header: {head}')
# 8: sizeof PerColHeader
# head: {min_value, range, num_rows, num_cols}
num_rows, num_cols = head[2], head[3]
if cps_type == 'CM':
remain_size = num_cols * (8 + num_rows)
elif cps_type == 'CM2':
remain_size = 2 * num_rows * num_cols
elif cps_type == 'CM3':
remain_size = num_rows * num_cols
else:
throw_on_error(False, f'Unknown matrix compressing type: {cps_type}')
# now uncompress it
compress_data = fd.read(remain_size)
mat = uncompress(compress_data, cps_type, head)
return mat
示例7: serialize_ndarray_b64
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [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)
示例8: serialize_ndarray_npy
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def serialize_ndarray_npy(o):
"""
Serializes a :obj:`numpy.ndarray` using numpy's built-in :obj:`save` function.
This produces totally unreadable (and very un-JSON-like) results (in "npy"
format), but it's basically guaranteed to work in 100% of cases.
Args:
o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.
Returns:
A dictionary that can be passed to :obj:`json.dumps`.
"""
with io.BytesIO() as f:
np.save(f, o)
f.seek(0)
serialized = json.dumps(f.read().decode('latin-1'))
return dict(
_type='np.ndarray',
npy=serialized)
示例9: deserialize_ndarray_npy
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def deserialize_ndarray_npy(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's
:obj:`save` function.
Args:
d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created
using :obj:`numpy.save`.
Returns:
An :obj:`ndarray` object.
"""
with io.BytesIO() as f:
f.write(json.loads(d['npy']).encode('latin-1'))
f.seek(0)
return np.load(f)
示例10: xyxy2xywh
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def xyxy2xywh(self, bbox):
"""Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO
evaluation.
Args:
bbox (numpy.ndarray): The bounding boxes, shape (4, ), in
``xyxy`` order.
Returns:
list[float]: The converted bounding boxes, in ``xywh`` order.
"""
_bbox = bbox.tolist()
return [
_bbox[0],
_bbox[1],
_bbox[2] - _bbox[0],
_bbox[3] - _bbox[1],
]
示例11: to_tensor
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
:class:`Sequence`, :class:`int` and :class:`float`.
Args:
data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to
be converted.
"""
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)
elif isinstance(data, Sequence) and not mmcv.is_str(data):
return torch.tensor(data)
elif isinstance(data, int):
return torch.LongTensor([data])
elif isinstance(data, float):
return torch.FloatTensor([data])
else:
raise TypeError(f'type {type(data)} cannot be converted to tensor.')
示例12: plot_iou_recall
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def plot_iou_recall(recalls, iou_thrs):
"""Plot IoU-Recalls curve.
Args:
recalls(ndarray or list): shape (k,)
iou_thrs(ndarray or list): same shape as `recalls`
"""
if isinstance(iou_thrs, np.ndarray):
_iou_thrs = iou_thrs.tolist()
else:
_iou_thrs = iou_thrs
if isinstance(recalls, np.ndarray):
_recalls = recalls.tolist()
else:
_recalls = recalls
import matplotlib.pyplot as plt
f = plt.figure()
plt.plot(_iou_thrs + [1.0], _recalls + [0.])
plt.xlabel('IoU')
plt.ylabel('Recall')
plt.axis([iou_thrs.min(), 1, 0, 1])
f.show()
示例13: tensor2imgs
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [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
示例14: crop_and_resize
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def crop_and_resize(self,
bboxes,
out_shape,
inds,
device,
interpolation='bilinear'):
"""Crop and resize masks by the given bboxes.
This function is mainly used in mask targets computation.
It firstly align mask to bboxes by assigned_inds, then crop mask by the
assigned bbox and resize to the size of (mask_h, mask_w)
Args:
bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4)
out_shape (tuple[int]): Target (h, w) of resized mask
inds (ndarray): Indexes to assign masks to each bbox
device (str): Device of bboxes
interpolation (str): See `mmcv.imresize`
Return:
BaseInstanceMasks: the cropped and resized masks.
"""
pass
示例15: crop
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarray [as 別名]
def crop(self, bbox):
"""See :func:`BaseInstanceMasks.crop`."""
assert isinstance(bbox, np.ndarray)
assert bbox.ndim == 1
# clip the boundary
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
x1, y1, x2, y2 = bbox
w = np.maximum(x2 - x1, 1)
h = np.maximum(y2 - y1, 1)
if len(self.masks) == 0:
cropped_masks = np.empty((0, h, w), dtype=np.uint8)
else:
cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w]
return BitmapMasks(cropped_masks, h, w)