本文整理汇总了Python中numpy.fromstring方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.fromstring方法的具体用法?Python numpy.fromstring怎么用?Python numpy.fromstring使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.fromstring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_common_mat
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [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)
示例2: read_float_vec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def read_float_vec(fd, direct_access=False):
"""
Read float vector(for class Vector in kaldi setup)
see matrix/kaldi-vector.cc
"""
if direct_access:
expect_binary(fd)
vec_type = read_token(fd)
print_info(f'\tType of the common vector: {vec_type}')
if vec_type not in ["FV", "DV"]:
raise RuntimeError(f"Unknown matrix type in kaldi: {vec_type}")
float_size = 4 if vec_type == 'FV' else 8
float_type = np.float32 if vec_type == 'FV' else np.float64
dim = read_int32(fd)
print_info(f'\tDim of the common vector: {dim}')
vec_data = fd.read(float_size * dim)
return np.fromstring(vec_data, dtype=float_type)
示例3: deserialize_ndarray
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def deserialize_ndarray(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray`. Can handle arrays serialized
using any of the methods in this module: :obj:`"npy"`, :obj:`"b64"`,
:obj:`"readable"`.
Args:
d (`dict`): A dictionary representation of an :obj:`ndarray` object.
Returns:
An :obj:`ndarray` object.
"""
if 'data' in d:
x = np.fromstring(
base64.b64decode(d['data']),
dtype=d['dtype'])
x.shape = d['shape']
return x
elif 'value' in d:
return np.array(d['value'], dtype=d['dtype'])
elif 'npy' in d:
return deserialize_ndarray_npy(d)
else:
raise ValueError('Malformed np.ndarray encoding.')
示例4: image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def image(self, captcha_str):
"""
Generate a greyscale captcha image representing number string
Parameters
----------
captcha_str: str
string a characters for captcha image
Returns
-------
numpy.ndarray
Generated greyscale image in np.ndarray float type with values normalized to [0, 1]
"""
img = self.captcha.generate(captcha_str)
img = np.fromstring(img.getvalue(), dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (self.h, self.w))
img = img.transpose(1, 0)
img = np.multiply(img, 1 / 255.0)
return img
示例5: fig2data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def fig2data(fig):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGB buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring (fig.canvas.tostring_rgb(), dtype=np.uint8)
buf.shape = (w, h, 3)
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll (buf, 3, axis=2)
return buf
示例6: load_word_vectors
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def load_word_vectors(url):
'''
Load the word embeddings from the url
:param url: to the word vectors
:return: dict of word and vector values
'''
word_vectors = {}
# print("Loading the word embeddings....................")
# print('abs path: ', os.path.abspath(url))
with open(url, mode='r', encoding='utf8') as f:
for line in f:
line = line.split(" ", 1)
key = line[0]
word_vectors[key] = np.fromstring(line[1], dtype="float32", sep=" ")
# print("\tMDBT: The vocabulary contains about {} word embeddings".format(len(word_vectors)))
return normalise_word_vectors(word_vectors)
示例7: _read_values
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def _read_values(self):
nc_type = self.fp.read(4)
n = self._unpack_int()
typecode, size = TYPEMAP[nc_type]
count = n*size
values = self.fp.read(int(count))
self.fp.read(-count % 4) # read padding
if typecode is not 'c':
values = fromstring(values, dtype='>%s' % typecode)
if values.shape == (1,): values = values[0]
else:
values = values.rstrip(asbytes('\x00'))
return values
示例8: frames
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def frames():
with PiCamera() as camera:
camera.rotation = int(str(os.environ['CAMERA_ROTATION']))
stream = io.BytesIO()
for _ in camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
# return current frame
stream.seek(0)
_stream = stream.getvalue()
data = np.fromstring(_stream, dtype=np.uint8)
img = cv2.imdecode(data, 1)
yield img
# reset stream for next frame
stream.seek(0)
stream.truncate()
示例9: _wav2array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def _wav2array(nchannels, sampwidth, data):
"""data must be the string containing the bytes from the wav file."""
num_samples, remainder = divmod(len(data), sampwidth * nchannels)
if remainder > 0:
raise ValueError('The length of data is not a multiple of '
'sampwidth * num_channels.')
if sampwidth > 4:
raise ValueError("sampwidth must not be greater than 4.")
if sampwidth == 3:
a = _np.empty((num_samples, nchannels, 4), dtype=_np.uint8)
raw_bytes = _np.fromstring(data, dtype=_np.uint8)
a[:, :, :sampwidth] = raw_bytes.reshape(-1, nchannels, sampwidth)
a[:, :, sampwidth:] = (a[:, :, sampwidth - 1:sampwidth] >> 7) * 255
result = a.view('<i4').reshape(a.shape[:-1])
else:
# 8 bit samples are stored as unsigned ints; others as signed ints.
dt_char = 'u' if sampwidth == 1 else 'i'
a = _np.fromstring(data, dtype='<%s%d' % (dt_char, sampwidth))
result = a.reshape(-1, nchannels)
return result
示例10: _load_poses
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def _load_poses(self):
"""Load ground truth poses (T_w_cam0) from file."""
pose_file = os.path.join(self.pose_path, self.sequence + '.txt')
# Read and parse the poses
poses = []
try:
with open(pose_file, 'r') as f:
lines = f.readlines()
if self.frames is not None:
lines = [lines[i] for i in self.frames]
for line in lines:
T_w_cam0 = np.fromstring(line, dtype=float, sep=' ')
T_w_cam0 = T_w_cam0.reshape(3, 4)
T_w_cam0 = np.vstack((T_w_cam0, [0, 0, 0, 1]))
poses.append(T_w_cam0)
except FileNotFoundError:
print('Ground truth poses are not available for sequence ' +
self.sequence + '.')
self.poses = poses
示例11: stream_readchunk
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def stream_readchunk(self):
"""reads some audio and re-launches itself"""
try:
self.data = np.fromstring(self.stream.read(self.chunk),dtype=np.int16)
self.fftx, self.fft = getFFT(self.data,self.rate)
except Exception as E:
print(" -- exception! terminating...")
print(E,"\n"*5)
self.keepRecording=False
if self.keepRecording:
self.stream_thread_new()
else:
self.stream.close()
self.p.terminate()
print(" -- stream STOPPED")
self.chunksRead+=1
示例12: get_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def get_data(self):
idxs = np.arange(len(self.train_list))
if self.shuffle:
self.rng.shuffle(idxs)
caches = {}
for i, k in enumerate(idxs):
path = self.train_list[k]
label = self.lb_list[k]
if i % self.preload == 0:
try:
caches = ILSVRCTenth._read_tenth_batch(self.train_list[idxs[i:i+self.preload]])
except Exception as e:
logging.warning('tenth local cache failed, err=%s' % str(e))
content = caches.get(path, '')
if not content:
content = ILSVRCTenth._read_tenth(path)
img = cv2.imdecode(np.fromstring(content, dtype=np.uint8), cv2.IMREAD_COLOR)
yield [img, label]
示例13: from_xml
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def from_xml(cls, xmlelement):
"""Loads a Sparse object from an existing file."""
binaryfp = xmlelement.binaryfp
nelem = int(xmlelement[0].attrib['nelem'])
nrows = int(xmlelement.attrib['nrows'])
ncols = int(xmlelement.attrib['ncols'])
if binaryfp is None:
rowindex = np.fromstring(xmlelement[0].text, sep=' ').astype(int)
colindex = np.fromstring(xmlelement[1].text, sep=' ').astype(int)
sparsedata = np.fromstring(xmlelement[2].text, sep=' ')
else:
rowindex = np.fromfile(binaryfp, dtype='<i4', count=nelem)
colindex = np.fromfile(binaryfp, dtype='<i4', count=nelem)
sparsedata = np.fromfile(binaryfp, dtype='<d', count=nelem)
return cls((sparsedata, (rowindex, colindex)), [nrows, ncols])
示例14: Vector
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def Vector(elem):
nelem = int(elem.attrib['nelem'])
if nelem == 0:
arr = np.ndarray((0,))
else:
# sep=' ' seems to work even when separated by newlines, see
# http://stackoverflow.com/q/31882167/974555
if elem.binaryfp is not None:
arr = np.fromfile(elem.binaryfp, dtype='<d', count=nelem)
else:
arr = np.fromstring(elem.text, sep=' ')
if arr.size != nelem:
raise RuntimeError(
'Expected {:s} elements in Vector, found {:d}'
' elements!'.format(elem.attrib['nelem'],
arr.size))
return arr
示例15: ComplexVector
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fromstring [as 别名]
def ComplexVector(elem):
nelem = int(elem.attrib['nelem'])
if nelem == 0:
arr = np.ndarray((0,), dtype=np.complex128)
else:
# sep=' ' seems to work even when separated by newlines, see
# http://stackoverflow.com/q/31882167/974555
if elem.binaryfp is not None:
arr = np.fromfile(elem.binaryfp, dtype=np.complex128,
count=nelem)
else:
arr = np.fromstring(elem.text, sep=' ', dtype=np.float64)
arr.dtype = np.complex128
if arr.size != nelem:
raise RuntimeError(
'Expected {:s} elements in Vector, found {:d}'
' elements!'.format(elem.attrib['nelem'],
arr.size))
return arr