當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.fromstring方法代碼示例

本文整理匯總了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) 
開發者ID:funcwj,項目名稱:kaldi-python-io,代碼行數:21,代碼來源:_io_kernel.py

示例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) 
開發者ID:funcwj,項目名稱:kaldi-python-io,代碼行數:19,代碼來源:_io_kernel.py

示例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.') 
開發者ID:gregreen,項目名稱:dustmaps,代碼行數:26,代碼來源:json_serializers.py

示例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 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:23,代碼來源:captcha_generator.py

示例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 
開發者ID:protossw512,項目名稱:AdaptiveWingLoss,代碼行數:19,代碼來源:utils.py

示例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) 
開發者ID:ConvLab,項目名稱:ConvLab,代碼行數:18,代碼來源:mdbt_util.py

示例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 
開發者ID:ME-ICA,項目名稱:me-ica,代碼行數:18,代碼來源:netcdf.py

示例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() 
開發者ID:cristianpb,項目名稱:object-detection,代碼行數:18,代碼來源:camera_pi.py

示例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 
開發者ID:CwbhX,項目名稱:Jamais-Vu,代碼行數:23,代碼來源:wavio.py

示例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 
開發者ID:utiasSTARS,項目名稱:pykitti,代碼行數:25,代碼來源:odometry.py

示例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 
開發者ID:swharden,項目名稱:Python-GUI-examples,代碼行數:19,代碼來源:SWHear.py

示例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] 
開發者ID:ildoonet,項目名稱:tf-lcnn,代碼行數:24,代碼來源:data_feeder.py

示例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]) 
開發者ID:atmtools,項目名稱:typhon,代碼行數:20,代碼來源:catalogues.py

示例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 
開發者ID:atmtools,項目名稱:typhon,代碼行數:19,代碼來源:read.py

示例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 
開發者ID:atmtools,項目名稱:typhon,代碼行數:21,代碼來源:read.py


注:本文中的numpy.fromstring方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。