numpy.fromfile

Here are the examples of the python api numpy.fromfile taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

302 Examples 7

5 Source : catalogs.py
with BSD 3-Clause "New" or "Revised" License
from SCECcode

    def load_catalog(cls, filename, loader=None, **kwargs):
        version = numpy.fromfile(filename, dtype=">i2", count=1)[0]
        header = numpy.fromfile(filename, dtype=cls._get_header_dtype(version), count=1)
        catalog_size = header['catalog_size'][0]
        # assign dtype to make sure that its bound to the instance of the class
        dtype = cls._get_catalog_dtype(version)
        event_list = numpy.fromfile(filename, dtype=cls._get_catalog_dtype(version), count=catalog_size)
        new_class = cls(filename=filename, data=event_list, **kwargs)
        new_class.dtype = dtype
        return new_class

    def get_csep_format(self):

3 Source : test_longdouble.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_fromfile_bogus(self):
        with temppath() as path:
            with open(path, 'wt') as f:
                f.write("1. 2. 3. flop 4.\n")
            res = np.fromfile(path, dtype=float, sep=" ")
        assert_equal(res, np.array([1., 2., 3.]))

    @dec.knownfailureif(string_to_longdouble_inaccurate, "Need strtold_l")

3 Source : index_scorer.py
with Apache License 2.0
from AIRC-KETI

def ivecs_read(fname):
    a = np.fromfile(fname, dtype='int32')
    d = a[0]
    return a.reshape(-1, d + 1)[:, 1:].copy()

def fvecs_read(fname):

3 Source : utils.py
with GNU General Public License v3.0
from akpetty

def get_psnlatslons(data_path):
	""" Get NSIDC 25 km lat/lon grids"""

	mask_latf = open(data_path+'/OTHER/psn25lats_v3.dat', 'rb')
	mask_lonf = open(data_path+'/OTHER/psn25lons_v3.dat', 'rb')
	lats_mask = np.reshape(np.fromfile(file=mask_latf, dtype='  <  i4')/100000., [448, 304])
	lons_mask = np.reshape(np.fromfile(file=mask_lonf, dtype=' < i4')/100000., [448, 304])

	return lats_mask, lons_mask

def get_pmask(year, month):

3 Source : cam.py
with MIT License
from AlexShkarin

def _read_cam_frame(f, skip=False):
    size=np.fromfile(f,"  <  u4",count=2)
    if len(size)==0 and file_utils.eof(f):
        raise StopIteration
    if len(size) < 2:
        raise IOError("not enough cam data to read the frame size")
    w,h=size
    if not skip:
        data=np.fromfile(f," < u2",count=w*h)
        if len(data) < w*h:
            raise IOError("not enough cam data to read the frame: {} pixels available instead of {}".format(len(data),w*h))
        return data.reshape((w,h))
    else:
        f.seek(w*h*2,1)
        return None

class CamReader(object):

3 Source : binio.py
with MIT License
from AlexShkarin

def read_num(f, dtype):
    """
    Read a number from file `f`.

    `dtype` is the textual representation of data type (numpy-style).
    """
    if dtype[0] not in "  <  >":
        dtype=default_byteorder+dtype
    if dtype in idtypes_inv:
        return int(np.fromfile(f,dtype=dtype,count=1)[0])
    elif dtype in fdtypes_inv:
        return float(np.fromfile(f,dtype=dtype,count=1)[0])
    else:
        raise ValueError("unrecognized dtype: {}".format(dtype))
def read_str(f, dtype):

3 Source : test_longdouble.py
with MIT License
from alvarobartt

    def test_fromfile_bogus(self):
        with temppath() as path:
            with open(path, 'wt') as f:
                f.write("1. 2. 3. flop 4.\n")
            res = np.fromfile(path, dtype=float, sep=" ")
        assert_equal(res, np.array([1., 2., 3.]))

    @pytest.mark.skipif(string_to_longdouble_inaccurate,

3 Source : utils_classif.py
with MIT License
from andresperezlopez

def load_tensor(in_path, suffix=''):
    """
    Loads a binary .data file
    """
    assert os.path.isdir(os.path.dirname(in_path)), "path to load tensor does not exist"
    f_in = np.fromfile(in_path.replace('.data', suffix + '.data'))
    shape = get_shape(in_path.replace('.data', suffix + '.shape'))
    f_in = f_in.reshape(shape)
    return f_in


def save_shape(shape_file, shape):

3 Source : numpy.py
with MIT License
from andyljones

    def read(self):
        if self._file is None:
            self._init()
        return np.fromfile(self._file, dtype=self._dtype)

class Reader:

3 Source : numpy.py
with MIT License
from andyljones

    def read(self):
        if self._file is None:
            self._init()
        return np.fromfile(self._file, dtype=self._dtype)

    def close(self):

3 Source : db_postprocess.py
with Apache License 2.0
from Ascend

    def get_pred(self, filename):
        path_base = os.path.join(flags.bin_data_path, filename.split(".")[0])
        mask_pred = np.fromfile(path_base + "_" + str(1) + ".bin", dtype="float32")
        mask_pred = np.reshape(mask_pred, [1, 1, 736, 1280])
        mask_pred = torch.from_numpy(mask_pred)
        return mask_pred

    def eval(self):

3 Source : bintofloat.py
with Apache License 2.0
from Ascend

def bin2float(file, dtype):
    if dtype=="fp32":
        data = np.fromfile(file, dtype='float32')
    elif dtype=="fp16":
        data = np.fromfile(file, dtype='float16')
    elif dtype=="int32":
        data = np.fromfile(file, dtype=np.int32)
    elif dtype=="int8":
        data = np.fromfile(file, dtype=np.int8)
    else:
        print("unaccepted type")
    float_file = file + ".txt"
    #print("save to file "+ float_file)
    np.savetxt(float_file, data.reshape(-1, 1), fmt="%.6f")


def bintofloat(filename, dtype):

3 Source : bintofloat.py
with Apache License 2.0
from Ascend

def bin2float(file, dtype):
    if dtype=="fp32":
        data = np.fromfile(file, dtype='float32')
    elif dtype=="fp16":
        data = np.fromfile(file, dtype='float16')
    elif dtype=="int32":
        data = np.fromfile(file, dtype=np.int32)
    elif dtype=="int8":
        data = np.fromfile(file, dtype=np.int8)
    else:
        print("unaccepted type")
    float_file = file + ".txt"
    print("save to file "+ float_file)
    np.savetxt(float_file, data.reshape(-1, 1), fmt="%.6f")


def bintofloat(filename, dtype):

3 Source : computer_map.py
with Apache License 2.0
from Ascend

def readResult(image_list, result_path, labels_list):
    dataOutput = []
    count = 0
    for image_name in image_list:
            file = image_name.split(".")[0]
            classes = np.fromfile(('{}/davinci_{}_output0.bin').format(result_path, file), dtype='float32').reshape(1, 8732, 81)
            boxes = np.fromfile(('{}/davinci_{}_output1.bin').format(result_path, file), dtype='float32').reshape(1, 8732, 4)
            #boxes = np.fromfile(('{}/davinci_{}_output1.bin').format(result_path, file), dtype='float32').reshape(2,8732)
            pred_scores, indices = select_top_k_scores(classes,200)

            dataOutput.append({"pred_box": boxes[0],
                            "source_id": labels_list[count]['source_id'],
                            "indices": indices[0],
                            "pred_scores": pred_scores[0],
                            "raw_shape": labels_list[count]['raw_shape']})
            count = count + 1
    return dataOutput

def _load_images_info(images_info_file):

3 Source : yolov4_postprocess.py
with Apache License 2.0
from Ascend

    def run(self, npu_output):
        pred_box = np.fromfile(os.path.join(npu_PATH, npu_output[:-5]+"1.bin"), dtype="float32").reshape(1, 10647, 4)
        pred_prob = np.fromfile(os.path.join(npu_PATH, npu_output), dtype="float32").reshape(1, 10647, 80)
        boxes, scores, classes, valid_detections = self.sess.run(self.output, feed_dict={self.bbox:pred_box, self.prob:pred_prob})
        writeResult("./detections_npu/", npu_output, boxes, scores, classes)

if __name__ == "__main__":

3 Source : acl_vdec.py
with Apache License 2.0
from Ascend

    def _gen_input_dataset(self, img_path):
        img = np.fromfile(img_path, dtype=self.dtype)
        img_buffer_size = img.size
        img_ptr = acl.util.numpy_to_ptr(img)
        img_device, ret = acl.media.dvpp_malloc(img_buffer_size)
        ret = acl.rt.memcpy(img_device,
                            img_buffer_size,
                            img_ptr,
                            img_buffer_size,
                            ACL_MEMCPY_HOST_TO_DEVICE)
        check_ret("acl.rt.memcpy", ret)
        return img_device, img_buffer_size

    def _set_input(self, input_stream_size):

3 Source : acl_sample.py
with Apache License 2.0
from Ascend

    def _transfer_to_device(self, img_path, dtype=np.uint8):
        img = np.fromfile(img_path, dtype=dtype)
        img_ptr = acl.util.numpy_to_ptr(img)
        img_buffer_size = img.itemsize * img.size
        img_device, ret = acl.media.dvpp_malloc(img_buffer_size)
        check_ret("acl.media.dvpp_malloc", ret)
        ret = acl.rt.memcpy(img_device,
                            img_buffer_size,
                            img_ptr,
                            img_buffer_size,
                            ACL_MEMCPY_HOST_TO_DEVICE)
        check_ret("acl.rt.memcpy", ret)

        return img_device, img_buffer_size

    def forward(self, img_dict):

3 Source : envi_utils.py
with BSD 3-Clause "New" or "Revised" License
from BeamIO-Inc

def read_all_image_data_to_numpy_array(envi_image_path,     # type: str
                                       envi_dtype,          # type: int
                                       ):                   # type: (...) -> np.ndarray
    numpy_dtype = envi_dtype_to_numpy_dtype(envi_dtype)
    numpy_data = np.fromfile(envi_image_path, numpy_dtype)
    return numpy_data


def construct_image_cube_from_raw_data(raw_envi_data,       # type: np.ndarray

3 Source : vectors_utils.py
with Apache License 2.0
from bestfitting

def ivecs_read(fname):
  a = np.fromfile(fname, dtype='int32')
  d = a[0]
  return a.reshape(-1, d + 1)[:, 1:].copy()

def fvecs_read(fname):

3 Source : vaspwfc.py
with GNU General Public License v3.0
from Chengcheng-Xiao

    def readBandCoeff(self, ispin=1, ikpt=1, iband=1, norm=False):
        '''
        Read the planewave coefficients of specified KS states.
        '''

        self.checkIndex(ispin, ikpt, iband)

        rec = self.whereRec(ispin, ikpt, iband)
        self._wfc.seek(rec * self._recl)

        nplw = self._nplws[ikpt - 1]
        dump = np.fromfile(self._wfc, dtype=self._WFPrec, count=nplw)

        cg = np.asarray(dump, dtype=np.complex128)
        if norm:
            cg /= np.linalg.norm(cg)
        return cg

    def whereRec(self, ispin=1, ikpt=1, iband=1):

3 Source : stripe.py
with Apache License 2.0
from Comcast

	def readDir(self):
		"""
		Reads in the entire directory. Not for the faint of heart.

		I *highly* recommend that if this is used, you later do `self.directory.clear()`
		so that memory usage doesn't get out of control.
		Note that you *MUST* have called `self.read()` prior to the calling of this method.
		"""
		utils.log("Stripe.readDir: reading in directory for", self)
		with io.open(self.file, 'rb', self.numDirEntries * 10) as infile:
			infile.seek(self.directoryOffset)

			self.directory = np.fromfile(infile,
			                             dtype=directory.npDirEntry,
			                             count=self.numDirEntries).view(dtype='u2')\
			                                                      .reshape(self.numDirEntries, 5)

	def getSegment(self, index: int) -> directory.Segment:

3 Source : plyfile.py
with MIT License
from corochann

    def _read_bin(self, stream, byte_order):
        '''
        Read data from a binary stream.  Raise StopIteration if the
        property could not be read.

        '''
        try:
            return _np.fromfile(stream, self.dtype(byte_order), 1)[0]
        except IndexError:
            raise StopIteration

    def _write_bin(self, data, stream, byte_order):

3 Source : plyfile.py
with MIT License
from corochann

    def _read_bin(self, stream, byte_order):
        (len_t, val_t) = self.list_dtype(byte_order)

        try:
            n = _np.fromfile(stream, len_t, 1)[0]
        except IndexError:
            raise StopIteration

        data = _np.fromfile(stream, val_t, n)
        if len(data)   <   n:
            raise StopIteration

        return data

    def _write_bin(self, data, stream, byte_order):

3 Source : check_files_similar.py
with MIT License
from creativefloworg

    def _read_file(fname):
        ext = _get_extension(fname)
        if ext == 'flo':
            res = io_util.read_flow(fname)
        elif ext == 'array':
            res = np.fromfile(fname)
        else:
            res = skimage.img_as_float(imread(fname))
            if len(res.shape) == 2:  # Ensure has channels
                res = np.expand_dims(res, axis=2)
        return res

    def _parse_channels(chstr):

3 Source : io_data.py
with Apache License 2.0
from cv-rits

def _read_SemKITTI(path, dtype, do_unpack):
  bin = np.fromfile(path, dtype=dtype)  # Flattened array
  if do_unpack:
    bin = unpack(bin)
  return bin


def _read_label_SemKITTI(path):

3 Source : test_longdouble.py
with Apache License 2.0
from dashanji

    def test_fromfile_bogus(self):
        with temppath() as path:
            with open(path, 'wt') as f:
                f.write("1. 2. 3. flop 4.\n")

            with assert_warns(DeprecationWarning):
                res = np.fromfile(path, dtype=float, sep=" ")
        assert_equal(res, np.array([1., 2., 3.]))

    def test_fromfile_complex(self):

3 Source : btools.py
with GNU General Public License v3.0
from dgbowl

def read_from_file(
    f: BufferedIOBase, offset: int, dtype: str, count: int = 1
) -> Union[str, np.ndarray]:
    f.seek(offset)
    if dtype == "utf-8":
        len = int.from_bytes(f.read(1), byteorder="big")
        chars = f.read(len)
        return chars.decode("utf-8")
    elif dtype == "utf-16":
        len = int.from_bytes(f.read(1), byteorder="big") * 2
        chars = f.read(len)
        return chars.decode("utf-16")
    elif count == 1:
        return np.fromfile(f, offset=0, dtype=dtype, count=1)[0]
    else:
        return np.fromfile(f, offset=0, dtype=dtype, count=count)


def read_from_buffer(

3 Source : image.py
with GNU General Public License v3.0
from dlr-eoc

    def read_body(self, fileobj,bitsPerPixel, im_width,im_height):
        count = im_width * im_height
        self.rawbody = np.fromfile(fileobj, dtype=bitsPerPixel,count=count) 
        self.rawbody = np.reshape(self.rawbody,(im_height,im_width))
        #self.normalize()
        #self.image = self.rawbody
   
    
    def normalize(self):

3 Source : file_io.py
with MIT License
from Dtananaev

def load_lidar(lidar_filename, dtype=np.float32, n_vec=4):
    scan = np.fromfile(lidar_filename, dtype=dtype)
    scan = scan.reshape((-1, n_vec))
    return scan


def save_lidar(lidar_filename, scan):

3 Source : vtk_file.py
with MIT License
from ebranlard

def _read_cells(f, is_ascii, num_items, dtype=numpy.dtype("int32")):
    if is_ascii:
        c = numpy.fromfile(f, count=num_items, sep=" ", dtype=dtype)
    else:
        dtype = dtype.newbyteorder(">")
        c = numpy.fromfile(f, count=num_items, dtype=dtype)
        line = f.readline().decode("utf-8")
        if line != "\n":
            raise ReadError()
    return c


def _read_cell_types(f, is_ascii, num_items):

3 Source : vtk_file.py
with MIT License
from ebranlard

def _read_cell_types(f, is_ascii, num_items):
    if is_ascii:
        ct = numpy.fromfile(f, count=int(num_items), sep=" ", dtype=int)
    else:
        # binary
        ct = numpy.fromfile(f, count=int(num_items), dtype=">i4")
        line = f.readline().decode("utf-8")
        # Sometimes, there's no newline at the end
        if line.strip() != "":
            raise ReadError()
    return ct


def _read_scalar_field(f, num_data, split, is_ascii):

3 Source : Hawc2io.py
with MIT License
from ebranlard

    def ReadFLEX(self, ChVec=[]):
        if not ChVec:
            ChVec = range(1, self.NrCh)
        fid = open(self.FileName, 'rb')
        fid.seek(2 * 4 * self.NrCh + 48 * 2)
        temp = np.fromfile(fid, 'int16')
        if self.Version==3:
            temp = temp.reshape(self.NrCh, self.NrSc).transpose()
        else:
            temp = temp.reshape(self.NrSc, self.NrCh)
        fid.close()
        return np.dot(temp[:, ChVec], np.diag(self.ScaleFactor[ChVec]))
################################################################################
# Read results in GTSD format
    def ReadGtsdf(self):

3 Source : posix_storage.py
with MIT License
from facebookresearch

    def __init__(self, *, idxfile: StoragePath, binfile: StoragePath) -> None:
        self.datafilename = binfile.path

        idx = np.fromfile(str(idxfile.path), dtype="int64")
        self._init_from_index_data(idx)
        self.data = np.memmap(str(self.datafilename), dtype=self.dtype, mode="r")

    def __getitem__(self, index: int):

3 Source : tifffile_old.py
with MIT License
from feldman4

    def read_array(self, dtype, count=-1, sep=""):
        """Return numpy array from file.

        Work around numpy issue #2230, "numpy.fromfile does not accept
        StringIO object" https://github.com/numpy/numpy/issues/2230.

        """
        try:
            return numpy.fromfile(self._fh, dtype, count, sep)
        except IOError:
            if count   <   0:
                size = self._size
            else:
                size = count * numpy.dtype(dtype).itemsize
            data = self._fh.read(size)
            return numpy.fromstring(data, dtype, count, sep)

    def read_record(self, dtype, shape=1, byteorder=None):

3 Source : audioread.py
with MIT License
from fgnt

def read_raw(path, dtype=np.dtype('  <  i2')):
    """
    Reads raw data (tidigits data)

    :param path: file path to audio file
    :param dtype: datatype, default: int16, little-endian
    :return: numpy array with audio samples
    """

    if isinstance(path, Path):
        path = str(path)

    with open(path, 'rb') as f:
        return np.fromfile(f, dtype=dtype)


def getparams(path):

3 Source : htkmfc.py
with GNU General Public License v3.0
from filby89

    def next(self):
        vec = numpy.fromfile(self.fh, self.dtype, self.veclen)
        if len(vec) == 0:
            raise StopIteration
        if self.swap:
            vec = vec.byteswap()
        # Uncompress data to floats if required
        if self.parmKind & _C:
            vec = (vec.astype('f') + self.B) / self.A
        return vec

    def readvec(self):

3 Source : fortran_data.py
with GNU General Public License v3.0
from FireDynamics

def read(infile: BinaryIO, dtype: np.dtype, n: int):
    """Convenience function to read in binary data from a file using a numpy dtype.

    :param infile: Already opened binary IO stream.
    :param dtype: Numpy dtype object.
    :param n: The number of times a dtype object should be read in from the stream.
    :returns: Read in data.
    """
    return np.array(
        [[t[i] for i in range(1, len(t), 3)] for t in np.fromfile(infile, dtype=dtype, count=n)],
        dtype=object)

3 Source : plyfile.py
with MIT License
from FlyingGiraffe

    def _read_bin(self, stream, byte_order):
        '''
        Read data from a binary stream.  Raise StopIteration if the
        property could not be read.
        '''
        try:
            return _np.fromfile(stream, self.dtype(byte_order), 1)[0]
        except IndexError:
            raise StopIteration

    def _write_bin(self, data, stream, byte_order):

3 Source : data_handler.py
with Apache License 2.0
from funcwj

    def _load(self, key):
        obj = np.fromfile(self.index_dict[key], dtype=self.fmt)
        if self.length is not None and obj.size != self.length:
            raise RuntimeError(
                f"Expect length {self.length:d}, but got {obj.size:d}")
        return obj


class ArchiveWriter(Writer):

3 Source : kinne.py
with MIT License
from geohot

  def parameter(self, t: Tensor):
    """
    parameter loads or saves a parameter, given as a tensor.
    """
    path = f"{self.base}{self.next_part_index}.bin"
    if self.save:
      t.data.astype("  <  f4", "C").tofile(path)
      self.metadata.write(f"{self.next_part_index}: {t.shape}\n")
    else:
      t.assign(Tensor(numpy.fromfile(path, " < f4")).reshape(shape=t.shape))
    self.next_part_index += 1

  def parameters(self, params):

3 Source : techelper.py
with MIT License
from GeoStat-Framework

    def get_zone_table_data(self):
        """Read the zone data by hand from the tecplot table file."""
        zone_data = []
        # read all zones to numpy arrays
        with open(self.infile, "r") as f:
            for i in range(self.zone_ct):
                # skip header
                for _ in range(self.skip[i]):
                    f.readline()
                # read matrix with np.fromfile (fastest numpy file reader)
                data = np.fromfile(
                    f, dtype=float, count=self.zone_length[i], sep=" "
                )
                # reshape matrix acording to the number of variables
                zone_data.append(data.reshape((-1, self.var_ct)))

        return zone_data

    def get_zone_block_data(self):

3 Source : data.py
with Apache License 2.0
from GestureGeneration

def read_binary_dataset(dataset_name):
    filename = fl.FLAGS.data_dir + '/' + dataset_name + '.binary'
    dataset = np.fromfile(filename)
    amount_of_frames = int(dataset.shape[0] /(fl.FLAGS.chunk_length * fl.FLAGS.frame_size))
    # Clip array so that it divides exactly into the inputs we want (frame_size *chunk_length)
    dataset = dataset[0:amount_of_frames * fl.FLAGS.chunk_length * fl.FLAGS.frame_size]
    # Reshape
    dataset = dataset.reshape(amount_of_frames, fl.FLAGS.chunk_length, fl.FLAGS.frame_size)
    return dataset


def read_3_datasets_from_binary():

3 Source : importAndProcess.py
with MIT License
from hahnicity

    def __getitem__(self, idx):
        orig_img_path = os.path.join(self.original_imgs_path, self.list[idx])
        arr = np.fromfile(orig_img_path, dtype='>i2').reshape((2048, 2048))
        orig_img = Image.fromarray((arr / arr.max()) * 255).convert(self.convert_to)
        if not self.test:
            bse_img_path = os.path.join(self.bse_imgs_path, self.list[idx].replace('.IMG', '.png'))
            bse = np.array(Image.open(bse_img_path))
            bse_img = Image.fromarray(((bse/bse.max()) * 255).astype('uint8')).convert(self.convert_to)
            return self.imgtransform(orig_img), self.imgtransform(bse_img)
        else:
            return self.imgtransform(orig_img)

3 Source : vasp_io.py
with Apache License 2.0
from hungpham2017

    def get_wfn(self, spin=0, kpt=0):
        '''Extract wfn coefficients''' 

        if kpt >= self.nkpts:
            raise ValueError("kpt must be smaller than the maximum index for kpt", self.nkpts)
            
        #TODO: check spin value

        cg = []
        for band in range(self.nkpts):
            rec = 3 + spin*self.nkpts*(self.nbands + 1) + kpt*(self.nbands + 1) + band 
            self._wavecar.seek(rec * self.recl)
            dump = np.fromfile(self._wavecar, dtype=self.prec, count=self.nplws[kpt])
            cg.append(np.asarray(dump, dtype=np.complex128))
  
        return np.asarray(cg)
        

3 Source : torchfile.py
with MIT License
from imfing

def add_storage_reader(typename, dtype):
    def read_storage(reader, version):
        # https://github.com/torch/torch7/blob/1e86025/generic/Storage.c#L237
        size = reader.read_long()
        return np.fromfile(reader.f, dtype=dtype, count=size)
    type_handlers[typename] = read_storage
add_storage_reader(b'torch.ByteStorage', dtype=np.uint8)

3 Source : picassoio.py
with MIT License
from imodpasteur

    def get_frame(self, index, array=None):
        self.file.seek(self.image_offsets[index])
        frame = _np.reshape(_np.fromfile(self.file, dtype=self._tif_dtype, count=self.frame_size), self.frame_shape)
        # We only want to deal with little endian byte order downstream:
        if self._tif_byte_order == '>':
            frame.byteswap(True)
            frame = frame.newbyteorder('  <  ')
        return frame

    def read(self, type, count=1):

3 Source : tests.py
with BSD 3-Clause "New" or "Revised" License
from int-brain-lab

def test_cli_chop(path, arr):
    _write_arr(path, arr)
    out = path.parent / 'data.cbin'
    out_chopped = path.parent / 'data.chopped.cbin'
    out_chopped_decomp = path.parent / 'data.chopped.bin'

    mtscomp([str(path), '-d', str(arr.dtype), '-s', str(sample_rate), '-n', str(arr.shape[1])])

    # Chop 3 chunks of 1 second each.
    mtschop([str(out), '-n', '3', '-o', str(out_chopped)])

    # Decompress the chopped compressed file.
    mtsdecomp([str(out_chopped), '-o', str(out_chopped_decomp)])

    # Make sure it corresponds to the first 3 seconds of the original array.
    arru = np.fromfile(str(out_chopped_decomp), dtype=arr.dtype)
    arru = arru.reshape((-1, arr.shape[1]))
    assert np.allclose(arr[:int(round(3 * sample_rate))], arru)

3 Source : htk_io.py
with MIT License
from jingyonghou

    def getall(self):
        self.seek(0)
        data = numpy.fromfile(self.fh, self.dtype)
        if self.parmKind & _K: # Remove and ignore checksum
            data = data[:-1]
        data = data.reshape(len(data)/self.veclen, self.veclen)
        if self.swap:
            data = data.byteswap()
        # Uncompress data to floats if required
        if self.parmKind & _C:
            data = (data.astype('f') + self.B) / self.A
        return data

class HTKFeatWriter(object):

3 Source : mama.py
with MIT License
from JonJala

def input_np_matrix(s_input: str) -> np.ndarray:
    """
    Used for parsing some inputs to this program, namely Numpy ndarrays (such as regression
    coefficient matrices).

    :param s_input: String passed in by argparse

    :return: ndarray containing the matrix in the file indicated
    """
    filename = input_file(s_input)
    return np.fromfile(filename, sep='\t')


def glob_path(s_input: str) -> List[str]:

3 Source : utils.py
with Apache License 2.0
from JuanDuGit

def load_descriptor_bin(filename, dim=131, dtype=np.float32):
    desc = np.fromfile(filename, dtype=dtype)
    desc = np.reshape(desc, (-1, dim))
    return desc


def load_single_pcfile(filename, dim=3, dtype=np.float32):

See More Examples