Python numpy.uint32() Examples

The following are 30 code examples for showing how to use numpy.uint32(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: recruit   Author: Frank-qlu   File: test_dtype.py    License: Apache License 2.0 8 votes vote down vote up
def test_union_with_struct_packed(self):
        class Struct(ctypes.Structure):
            _pack_ = 1
            _fields_ = [
                ('one', ctypes.c_uint8),
                ('two', ctypes.c_uint32)
            ]

        class Union(ctypes.Union):
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint32),
                ('d', Struct),
            ]
        expected = np.dtype(dict(
            names=['a', 'b', 'c', 'd'],
            formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
            offsets=[0, 0, 0, 0],
            itemsize=ctypes.sizeof(Union)
        ))
        self.check(Union, expected) 
Example 2
Project: pfilter   Author: johnhw   File: pfilter.py    License: MIT License 6 votes vote down vote up
def residual_resample(weights):
    n = len(weights)
    indices = np.zeros(n, np.uint32)
    # take int(N*w) copies of each weight
    num_copies = (n * weights).astype(np.uint32)
    k = 0
    for i in range(n):
        for _ in range(num_copies[i]):  # make n copies
            indices[k] = i
            k += 1
    # use multinormial resample on the residual to fill up the rest.
    residual = weights - num_copies  # get fractional part
    residual /= np.sum(residual)
    cumsum = np.cumsum(residual)
    cumsum[-1] = 1
    indices[k:n] = np.searchsorted(cumsum, np.random.uniform(0, 1, n - k))
    return indices 
Example 3
Project: pfilter   Author: johnhw   File: pfilter.py    License: MIT License 6 votes vote down vote up
def create_indices(positions, weights):
    n = len(weights)
    indices = np.zeros(n, np.uint32)
    cumsum = np.cumsum(weights)
    i, j = 0, 0
    while i < n:
        if positions[i] < cumsum[j]:
            indices[i] = j
            i += 1
        else:
            j += 1

    return indices


### end rlabbe's resampling functions 
Example 4
Project: me-ica   Author: ME-ICA   File: test_utils.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_can_cast():
    tests = ((np.float32, np.float32, True, True, True),
             (np.float64, np.float32, True, True, True),
             (np.complex128, np.float32, False, False, False),
             (np.float32, np.complex128, True, True, True),
             (np.float32, np.uint8, False, True, True),
             (np.uint32, np.complex128, True, True, True),
             (np.int64, np.float32, True, True, True),
             (np.complex128, np.int16, False, False, False),
             (np.float32, np.int16, False, True, True),
             (np.uint8, np.int16, True, True, True),
             (np.uint16, np.int16, False, True, True),
             (np.int16, np.uint16, False, False, True),
             (np.int8, np.uint16, False, False, True),
             (np.uint16, np.uint8, False, True, True),
             )
    for intype, outtype, def_res, scale_res, all_res in tests:
        assert_equal(def_res, can_cast(intype, outtype))
        assert_equal(scale_res, can_cast(intype, outtype, False, True))
        assert_equal(all_res, can_cast(intype, outtype, True, True)) 
Example 5
Project: baseband   Author: mhvk   File: header.py    License: GNU General Public License v3.0 6 votes vote down vote up
def stream2words(stream, track=None):
    """Convert a stream of integers to uint32 header words.

    Parameters
    ----------
    stream : `~numpy.array` of int
        For each int, every bit corresponds to a particular track.
    track : int, array, or None, optional
        The track to extract.  If `None` (default), extract all tracks that
        the type of int in the stream can hold.
    """
    if track is None:
        track = np.arange(stream.dtype.itemsize * 8, dtype=stream.dtype)

    track_sel = ((stream.reshape(-1, 32, 1) >> track) & 1).astype(np.uint32)
    track_sel <<= np.arange(31, -1, -1, dtype=np.uint32).reshape(-1, 1)
    words = np.bitwise_or.reduce(track_sel, axis=1)
    return words.squeeze() 
Example 6
Project: baseband   Author: mhvk   File: header.py    License: GNU General Public License v3.0 6 votes vote down vote up
def words2stream(words):
    """Convert a set of uint32 header words to a stream of integers.

    Parameters
    ----------
    words : `~numpy.array` of uint32

    Returns
    -------
    stream : `~numpy.array` of int
        For each int, every bit corresponds to a particular track.
    """
    ntrack = words.shape[1]
    dtype = MARK4_DTYPES[ntrack]
    nbits = words.dtype.itemsize * 8
    bit = np.arange(nbits - 1, -1, -1, dtype=words.dtype).reshape(-1, 1)

    bit_sel = ((words[:, np.newaxis, :] >> bit) & 1).astype(dtype[1:])
    bit_sel <<= np.arange(ntrack, dtype=dtype[1:])
    words = np.empty(bit_sel.shape[:2], dtype)
    words = np.bitwise_or.reduce(bit_sel, axis=2, out=words)
    return words.ravel() 
Example 7
Project: pytorch-fm   Author: rixwew   File: avazu.py    License: MIT License 6 votes vote down vote up
def __yield_buffer(self, path, feat_mapper, defaults, buffer_size=int(1e5)):
        item_idx = 0
        buffer = list()
        with open(path) as f:
            f.readline()
            pbar = tqdm(f, mininterval=1, smoothing=0.1)
            pbar.set_description('Create avazu dataset cache: setup lmdb')
            for line in pbar:
                values = line.rstrip('\n').split(',')
                if len(values) != self.NUM_FEATS + 2:
                    continue
                np_array = np.zeros(self.NUM_FEATS + 1, dtype=np.uint32)
                np_array[0] = int(values[1])
                for i in range(1, self.NUM_FEATS + 1):
                    np_array[i] = feat_mapper[i].get(values[i+1], defaults[i])
                buffer.append((struct.pack('>I', item_idx), np_array.tobytes()))
                item_idx += 1
                if item_idx % buffer_size == 0:
                    yield buffer
                    buffer.clear()
            yield buffer 
Example 8
Project: pytorch-fm   Author: rixwew   File: criteo.py    License: MIT License 6 votes vote down vote up
def __yield_buffer(self, path, feat_mapper, defaults, buffer_size=int(1e5)):
        item_idx = 0
        buffer = list()
        with open(path) as f:
            pbar = tqdm(f, mininterval=1, smoothing=0.1)
            pbar.set_description('Create criteo dataset cache: setup lmdb')
            for line in pbar:
                values = line.rstrip('\n').split('\t')
                if len(values) != self.NUM_FEATS + 1:
                    continue
                np_array = np.zeros(self.NUM_FEATS + 1, dtype=np.uint32)
                np_array[0] = int(values[0])
                for i in range(1, self.NUM_INT_FEATS + 1):
                    np_array[i] = feat_mapper[i].get(convert_numeric_feature(values[i]), defaults[i])
                for i in range(self.NUM_INT_FEATS + 1, self.NUM_FEATS + 1):
                    np_array[i] = feat_mapper[i].get(values[i], defaults[i])
                buffer.append((struct.pack('>I', item_idx), np_array.tobytes()))
                item_idx += 1
                if item_idx % buffer_size == 0:
                    yield buffer
                    buffer.clear()
            yield buffer 
Example 9
Project: pulse2percept   Author: pulse2percept   File: beyeler2019.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _predict_spatial(self, earray, stim):
        """Predicts the brightness at specific times ``t``"""
        # This does the expansion of a compact stimulus and a list of
        # electrodes to activation values at X,Y grid locations:
        assert isinstance(earray, ElectrodeArray)
        assert isinstance(stim, Stimulus)
        return fast_axon_map(stim.data,
                             np.array([earray[e].x for e in stim.electrodes],
                                      dtype=np.float32),
                             np.array([earray[e].y for e in stim.electrodes],
                                      dtype=np.float32),
                             self.axon_contrib,
                             self.axon_idx_start.astype(np.uint32),
                             self.axon_idx_end.astype(np.uint32),
                             self.rho,
                             self.thresh_percept) 
Example 10
Project: pulse2percept   Author: pulse2percept   File: horsager2009.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _predict_temporal(self, stim, t_percept):
        """Predict the temporal response"""
        # Pass the stimulus as a 2D NumPy array to the fast Cython function:
        stim_data = stim.data.reshape((-1, len(stim.time)))
        # Calculate at which simulation time steps we need to output a percept.
        # This is basically t_percept/self.dt, but we need to beware of
        # floating point rounding errors! 29.999 will be rounded down to 29 by
        # np.uint32, so we need to np.round it first:
        idx_percept = np.uint32(np.round(t_percept / self.dt))
        if np.unique(idx_percept).size < t_percept.size:
            raise ValueError("All times 't_percept' must be distinct multiples "
                             "of `dt`=%.2e" % self.dt)
        # Cython returns a 2D (space x time) NumPy array:
        return temporal_fast(stim_data.astype(np.float32),
                             stim.time.astype(np.float32),
                             idx_percept,
                             self.dt, self.tau1, self.tau2, self.tau3,
                             self.eps, self.beta, self.thresh_percept) 
Example 11
Project: pulse2percept   Author: pulse2percept   File: nanduri2012.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _predict_temporal(self, stim, t_percept):
        """Predict the temporal response"""
        # Pass the stimulus as a 2D NumPy array to the fast Cython function:
        stim_data = stim.data.reshape((-1, len(stim.time)))
        # Calculate at which simulation time steps we need to output a percept.
        # This is basically t_percept/self.dt, but we need to beware of
        # floating point rounding errors! 29.999 will be rounded down to 29 by
        # np.uint32, so we need to np.round it first:
        idx_percept = np.uint32(np.round(t_percept / self.dt))
        if np.unique(idx_percept).size < t_percept.size:
            raise ValueError("All times 't_percept' must be distinct multiples "
                             "of `dt`=%.2e" % self.dt)
        # Cython returns a 2D (space x time) NumPy array:
        return temporal_fast(stim_data.astype(np.float32),
                             stim.time.astype(np.float32),
                             idx_percept,
                             self.dt, self.tau1, self.tau2, self.tau3,
                             self.asymptote, self.shift, self.slope, self.eps,
                             self.thresh_percept) 
Example 12
Project: modelforge   Author: src-d   File: model.py    License: Apache License 2.0 6 votes vote down vote up
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray:
    """Return a copy of an integer numpy array with the minimum bitness."""
    assert arr.dtype.kind in ("i", "u")
    if arr.size == 0:
        return arr
    if arr.dtype.kind == "i":
        assert arr.min() >= 0
    mlbl = int(arr.max()).bit_length()
    if mlbl <= 8:
        dtype = numpy.uint8
    elif mlbl <= 16:
        dtype = numpy.uint16
    elif mlbl <= 32:
        dtype = numpy.uint32
    else:
        dtype = numpy.uint64
    return arr.astype(dtype) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_ctypeslib.py    License: Apache License 2.0 6 votes vote down vote up
def test_padded_union(self):
        dt = np.dtype(dict(
            names=['a', 'b'],
            offsets=[0, 0],
            formats=[np.uint16, np.uint32],
            itemsize=5,
        ))

        ct = np.ctypeslib.as_ctypes_type(dt)
        assert_(issubclass(ct, ctypes.Union))
        assert_equal(ctypes.sizeof(ct), dt.itemsize)
        assert_equal(ct._fields_, [
            ('a', ctypes.c_uint16),
            ('b', ctypes.c_uint32),
            ('', ctypes.c_char * 5),  # padding
        ]) 
Example 14
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                assert_raises(ArithmeticError, np.prod, a)
                assert_raises(ArithmeticError, np.prod, a2, 1)
            else:
                assert_equal(a.prod(axis=0), 26400)
                assert_array_equal(a2.prod(axis=0),
                                   np.array([50, 36, 84, 180], ctype))
                assert_array_equal(a2.prod(axis=-1),
                                   np.array([24, 1890, 600], ctype)) 
Example 15
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                assert_raises(ArithmeticError, np.cumprod, a)
                assert_raises(ArithmeticError, np.cumprod, a2, 1)
                assert_raises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example 16
Project: recruit   Author: Frank-qlu   File: test_arraysetops.py    License: Apache License 2.0 6 votes vote down vote up
def test_setdiff1d(self):
        a = np.array([6, 5, 4, 7, 1, 2, 7, 4])
        b = np.array([2, 4, 3, 3, 2, 1, 5])

        ec = np.array([6, 7])
        c = setdiff1d(a, b)
        assert_array_equal(c, ec)

        a = np.arange(21)
        b = np.arange(19)
        ec = np.array([19, 20])
        c = setdiff1d(a, b)
        assert_array_equal(c, ec)

        assert_array_equal([], setdiff1d([], []))
        a = np.array((), np.uint32)
        assert_equal(setdiff1d(a, []).dtype, np.uint32) 
Example 17
Project: recruit   Author: Frank-qlu   File: test_dtype.py    License: Apache License 2.0 6 votes vote down vote up
def test_union_packed(self):
        class Struct(ctypes.Structure):
            _fields_ = [
                ('one', ctypes.c_uint8),
                ('two', ctypes.c_uint32)
            ]
            _pack_ = 1
        class Union(ctypes.Union):
            _pack_ = 1
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint32),
                ('d', Struct),
            ]
        expected = np.dtype(dict(
            names=['a', 'b', 'c', 'd'],
            formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
            offsets=[0, 0, 0, 0],
            itemsize=ctypes.sizeof(Union)
        ))
        self.check(Union, expected) 
Example 18
Project: recruit   Author: Frank-qlu   File: test_dtype.py    License: Apache License 2.0 6 votes vote down vote up
def test_large_packed_structure(self):
        class PackedStructure(ctypes.Structure):
            _pack_ = 2
            _fields_ = [
                ('a', ctypes.c_uint8),
                ('b', ctypes.c_uint16),
                ('c', ctypes.c_uint8),
                ('d', ctypes.c_uint16),
                ('e', ctypes.c_uint32),
                ('f', ctypes.c_uint32),
                ('g', ctypes.c_uint8)
                ]
        expected = np.dtype(dict(
            formats=[np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8 ],
            offsets=[0, 2, 4, 6, 8, 12, 16],
            names=['a', 'b', 'c', 'd', 'e', 'f', 'g'],
            itemsize=18))
        self.check(PackedStructure, expected) 
Example 19
Project: recruit   Author: Frank-qlu   File: test_stata.py    License: Apache License 2.0 6 votes vote down vote up
def test_bool_uint(self, byteorder, version):
        s0 = Series([0, 1, True], dtype=np.bool)
        s1 = Series([0, 1, 100], dtype=np.uint8)
        s2 = Series([0, 1, 255], dtype=np.uint8)
        s3 = Series([0, 1, 2 ** 15 - 100], dtype=np.uint16)
        s4 = Series([0, 1, 2 ** 16 - 1], dtype=np.uint16)
        s5 = Series([0, 1, 2 ** 31 - 100], dtype=np.uint32)
        s6 = Series([0, 1, 2 ** 32 - 1], dtype=np.uint32)

        original = DataFrame({'s0': s0, 's1': s1, 's2': s2, 's3': s3,
                              's4': s4, 's5': s5, 's6': s6})
        original.index.name = 'index'
        expected = original.copy()
        expected_types = (np.int8, np.int8, np.int16, np.int16, np.int32,
                          np.int32, np.float64)
        for c, t in zip(expected.columns, expected_types):
            expected[c] = expected[c].astype(t)

        with tm.ensure_clean() as path:
            original.to_stata(path, byteorder=byteorder, version=version)
            written_and_read_again = self.read_dta(path)
            written_and_read_again = written_and_read_again.set_index('index')
            tm.assert_frame_equal(written_and_read_again, expected) 
Example 20
Project: incubator-spot   Author: apache   File: flow.py    License: Apache License 2.0 5 votes vote down vote up
def add_geospatial_info(iploc,inbound,outbound,twoway):
    iplist = ''
    if os.path.isfile(iploc):
        iplist = np.loadtxt(iploc,dtype=np.uint32,delimiter=',',usecols={0},\
        converters={0: lambda s: np.uint32(s.replace('"',''))})
    else:
        print "No iploc.csv file was found, Map View map won't be created"


    # get geospatial info, only when iplocation file is available
    if iplist != '':
        for srcip in outbound:
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,outbound[srcip]['ip_int'])).replace('\n','')])

            outbound[srcip]['geo'] = reader.next()
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,outbound[srcip]['dst_ip_int'])).replace('\n','')])
            outbound[srcip]['geo_dst'] = reader.next()

        for dstip in twoway:
            reader = csv.reader([linecache.getline(\
            iploc,bisect.bisect(iplist,twoway[dstip]['ip_int'])).replace('\n','')])
            twoway[dstip]['geo'] = reader.next()

        for srcip in inbound:
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,inbound[srcip]['ip_int'])).replace('\n','')])

            inbound[srcip]['geo'] = reader.next()
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,inbound[srcip]['src_ip_int'])).replace('\n','')])
            inbound[srcip]['geo_src'] = reader.next()

    return inbound,outbound,twoway 
Example 21
Project: incubator-spot   Author: apache   File: geoloc.py    License: Apache License 2.0 5 votes vote down vote up
def _get_low_ips_in_ranges(self):

        self._logger.info("Reading GEO localization file: {0}".format(self._ip_localization_file))
        if os.path.isfile(self._ip_localization_file):
            return numpy.loadtxt(self._ip_localization_file, dtype=numpy.uint32, delimiter=',', usecols=[0], converters={0: lambda s: numpy.uint32(s.replace('"', ''))})
        else:
            self._logger.error("file: {0} does not exist".format(self._ip_localization_file)) 
Example 22
Project: vergeml   Author: mme   File: env.py    License: MIT License 5 votes vote down vote up
def _toscalar(v):
    if isinstance(v, (np.float16, np.float32, np.float64,
                      np.uint8, np.uint16, np.uint32, np.uint64,
                      np.int8, np.int16, np.int32, np.int64)):
        return np.asscalar(v)
    else:
        return v 
Example 23
Project: PyOptiX   Author: ozen   File: sphere.py    License: MIT License 5 votes vote down vote up
def create_context():
    context = Context()

    context.set_ray_type_count(1)
    context['radiance_ray_type'] = np.array(0, dtype=np.uint32)
    context['scene_epsilon'] = np.array(1e-4, dtype=np.float32)
    context['output_buffer'] = Buffer.empty((height, width, 4), dtype=np.uint8, buffer_type='o', drop_last_dim=True)
    entry_point = EntryPoint(Program('pinhole_camera.cu', 'pinhole_camera'),
                             Program('pinhole_camera.cu', 'exception'))

    cam_eye = [0.0, 0.0, 5.0]
    lookat = [0.0, 0.0, 0.0]
    up = [0.0, 1.0, 0.0]
    hfov = 60.0
    aspect_ratio = width / height
    camera_u, camera_v, camera_w = calculate_camera_variables(cam_eye, lookat, up, hfov, aspect_ratio, True)

    context['eye'] = np.array(cam_eye, dtype=np.float32)
    context['U'] = np.array(camera_u, dtype=np.float32)
    context['V'] = np.array(camera_v, dtype=np.float32)
    context['W'] = np.array(camera_w, dtype=np.float32)

    context['bad_color'] = np.array([1.0, 0.0, 1.0], dtype=np.float32)
    context.set_miss_program(0, Program('constantbg.cu', 'miss'))
    context['bg_color'] = np.array([0.2, 0.1, 0.3], dtype=np.float32)

    return context, entry_point 
Example 24
Project: PyOptiX   Author: ozen   File: buffers_of_buffers.py    License: MIT License 5 votes vote down vote up
def create_context():
    context = Context()

    context.set_ray_type_count(2)
    context.set_stack_size(1200)
    context.set_print_enabled(True)
    context.set_all_exceptions_enabled(True)

    # here pyoptix won't be able to deduce types of these variables,
    # so we must put them inside numpy arrays with proper dtypes
    context['max_depth'] = np.array(5, dtype=np.int32)
    context['radiance_ray_type'] = np.array(0, dtype=np.uint32)
    context['shadow_ray_type'] = np.array(1, dtype=np.uint32)
    context['scene_epsilon'] = np.array(1e-4, dtype=np.float32)

    context['output_buffer'] = Buffer.empty((height, width, 4), dtype=np.uint8, buffer_type='o', drop_last_dim=True)

    cam_eye = [2.0, 1.5, -2.0]
    lookat = [0.0, 1.2, 0.0]
    up = [0.0, 1.0, 0.0]
    hfov = 60.0
    aspect_ratio = width / height
    camera_u, camera_v, camera_w = calculate_camera_variables(cam_eye, lookat, up, hfov, aspect_ratio)

    context['eye'] = np.array(cam_eye, dtype=np.float32)
    context['U'] = np.array(camera_u, dtype=np.float32)
    context['V'] = np.array(camera_v, dtype=np.float32)
    context['W'] = np.array(camera_w, dtype=np.float32)

    ray_gen_program = Program('pinhole_camera.cu', 'pinhole_camera')
    exception_program = Program('pinhole_camera.cu', 'exception')
    entry_point = EntryPoint(ray_gen_program, exception_program)

    context['bad_color'] = np.array([0, 1, 1], dtype=np.float32)

    context.set_miss_program(0, Program('constantbg.cu', 'miss'))
    context['bg_color'] = np.array([0.4, 0.33, 0.21], dtype=np.float32)

    return context, entry_point 
Example 25
Project: openISP   Author: cruxopen   File: ccm.py    License: MIT License 5 votes vote down vote up
def execute(self):
        img_h = self.img.shape[0]
        img_w = self.img.shape[1]
        img_c = self.img.shape[2]
        ccm_img = np.empty((img_h, img_w, img_c), np.uint32)
        for y in range(img_h):
            for x in range(img_w):
                mulval = self.ccm[:,0:3] * self.img[y,x,:]
                ccm_img[y,x,0] = np.sum(mulval[0]) + self.ccm[0,3]
                ccm_img[y,x,1] = np.sum(mulval[1]) + self.ccm[1,3]
                ccm_img[y,x,2] = np.sum(mulval[2]) + self.ccm[2,3]
                ccm_img[y,x,:] = ccm_img[y,x,:] / 1024
        self.img = ccm_img.astype(np.uint8)
        return self.img 
Example 26
Project: openISP   Author: cruxopen   File: csc.py    License: MIT License 5 votes vote down vote up
def execute(self):
        img_h = self.img.shape[0]
        img_w = self.img.shape[1]
        img_c = self.img.shape[2]
        csc_img = np.empty((img_h, img_w, img_c), np.uint32)
        for y in range(img_h):
            for x in range(img_w):
                mulval = self.csc[:,0:3] * self.img[y,x,:]
                csc_img[y,x,0] = np.sum(mulval[0]) + self.csc[0,3]
                csc_img[y,x,1] = np.sum(mulval[1]) + self.csc[1,3]
                csc_img[y,x,2] = np.sum(mulval[2]) + self.csc[2,3]
                csc_img[y,x,:] = csc_img[y,x,:] / 1024
        self.img = csc_img.astype(np.uint8)
        return self.img 
Example 27
Project: RingNet   Author: soubhiksanyal   File: dynamic_contour_embedding.py    License: MIT License 5 votes vote down vote up
def load_static_embedding(static_embedding_path):
    with open(static_embedding_path, 'rb') as f:
        lmk_indexes_dict = pickle.load(f)
    lmk_face_idx = lmk_indexes_dict[ 'lmk_face_idx' ].astype( np.uint32 )
    lmk_b_coords = lmk_indexes_dict[ 'lmk_b_coords' ]
    return lmk_face_idx, lmk_b_coords 
Example 28
Project: L3C-PyTorch   Author: fab-jul   File: bitcoding.py    License: GNU General Public License v3.0 5 votes vote down vote up
def write_num_bytes_encoded(num_bytes, fout):
    assert num_bytes < 2**32
    write_bytes(fout, [np.uint32], [num_bytes])
    return 2  # number of bytes written 
Example 29
Project: L3C-PyTorch   Author: fab-jul   File: bitcoding.py    License: GNU General Public License v3.0 5 votes vote down vote up
def read_num_bytes_encoded(fin):
    return int(read_bytes(fin, [np.uint32])[0]) 
Example 30
Project: me-ica   Author: ME-ICA   File: ecat.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_mlist(self, fileobj):
        fileobj.seek(512)
        dat=fileobj.read(128*32)

        dt = np.dtype([('matlist',np.int32)])
        if not self.hdr.endianness is native_code:
            dt = dt.newbyteorder(self.hdr.endianness)
        nframes = self.hdr['num_frames']
        mlist = np.zeros((nframes,4), dtype='uint32')
        record_count = 0
        done = False

        while not done: #mats['matlist'][0,1] == 2:

            mats = np.recarray(shape=(32,4), dtype=dt,  buf=dat)
            if not (mats['matlist'][0,0] +  mats['matlist'][0,3]) == 31:
                mlist = []
                return mlist

            nrecords = mats['matlist'][0,3]
            mlist[record_count:nrecords+record_count,:] = mats['matlist'][1:nrecords+1,:]
            record_count+= nrecords
            if mats['matlist'][0,1] == 2 or mats['matlist'][0,1] == 0:
                done = True
            else:
                # Find next subheader
                tmp = int(mats['matlist'][0,1]-1)#cast to int
                fileobj.seek(0)
                fileobj.seek(tmp*512)
                dat = fileobj.read(128*32)

        return mlist