Python numpy.right_shift() Examples

The following are 30 code examples of numpy.right_shift(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: test_ufunc.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #2
Source File: modis_l2.py    From satpy with GNU General Public License v3.0 6 votes vote down vote up
def bits_strip(bit_start, bit_count, value):
    """Extract specified bit from bit representation of integer value.

    Parameters
    ----------
    bit_start : int
        Starting index of the bits to extract (first bit has index 0)
    bit_count : int
        Number of bits starting from bit_start to extract
    value : int
        Number from which to extract the bits

    Returns
    -------
        int
        Value of the extracted bits

    """
    bit_mask = pow(2, bit_start + bit_count) - 1
    return np.right_shift(np.bitwise_and(value, bit_mask), bit_start) 
Example #3
Source File: test_ufunc.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #4
Source File: test_Sim.py    From basil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_simple(self):
        input_arr = bitarray('10' * 64)

        self.chip['PIXEL_REG'][:] = input_arr
        self.chip['PIXEL_REG'][0] = 0
        self.chip.program_pixel_reg()

        ret = self.chip['DATA'].get_data()

        data0 = ret.astype(np.uint8)
        data1 = np.right_shift(ret, 8).astype(np.uint8)
        data = np.reshape(np.vstack((data1, data0)), -1, order='F')
        bdata = np.unpackbits(data)

        input_arr[0] = 0

        self.assertEqual(input_arr.tolist(), bdata.tolist()) 
Example #5
Source File: LCD_1in44.py    From Piano-LED-Visualizer with MIT License 6 votes vote down vote up
def LCD_ShowImage(self,Image,Xstart,Ystart):
		if (Image == None):
			return
		imwidth, imheight = Image.size
		if imwidth != self.width or imheight != self.height:
			raise ValueError('Image must be same dimensions as display \
				({0}x{1}).' .format(self.width, self.height))
		img = np.asarray(Image)
		pix = np.zeros((self.width,self.height,2), dtype = np.uint8)
		pix[...,[0]] = np.add(np.bitwise_and(img[...,[0]],0xF8),np.right_shift(img[...,[1]],5))
		pix[...,[1]] = np.add(np.bitwise_and(np.left_shift(img[...,[1]],3),0xE0),np.right_shift(img[...,[2]],3))
		pix = pix.flatten().tolist()
		self.LCD_SetWindows(0, 0, self.width , self.height)
		GPIO.output(LCD_Config.LCD_DC_PIN, GPIO.HIGH)
		for i in range(0,len(pix),4096):
			LCD_Config.SPI_Write_Byte(pix[i:i+4096]) 
Example #6
Source File: test_ufunc.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example #7
Source File: test_ufunc.py    From mxnet-lambda with Apache License 2.0 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #8
Source File: test_ufunc.py    From pySINDy with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #9
Source File: test_ufunc.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example #10
Source File: test_op_level4.py    From incubator-tvm with Apache License 2.0 6 votes vote down vote up
def test_binary_int_broadcast_1():
    for op, ref in [(relay.right_shift, np.right_shift),
                    (relay.left_shift, np.left_shift)]:
        x = relay.var("x", relay.TensorType((10, 4), "int32"))
        y = relay.var("y", relay.TensorType((5, 10, 1), "int32"))
        z = op(x, y)
        zz = run_infer_type(z)
        assert zz.checked_type == relay.TensorType((5, 10, 4), "int32")

        if ref is not None:
            x_shape = (10, 4)
            y_shape = (5, 10, 1)
            t1 = relay.TensorType(x_shape, 'int32')
            t2 = relay.TensorType(y_shape, 'int32')
            x_data = np.random.randint(1, 10000, size=(x_shape)).astype(t1.dtype)
            y_data = np.random.randint(1, 31, size=(y_shape)).astype(t2.dtype)
            func = relay.Function([x, y], z)
            ref_res = ref(x_data, y_data)

            for target, ctx in ctx_list():
                intrp = relay.create_executor("graph", ctx=ctx, target=target)
                op_res = intrp.evaluate(func)(x_data, y_data)
                tvm.testing.assert_allclose(op_res.asnumpy(), ref_res) 
Example #11
Source File: test_ufunc.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example #12
Source File: test_ufunc.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #13
Source File: test_ufunc.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #14
Source File: test_ufunc.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #15
Source File: test_ufunc.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #16
Source File: test_ufunc.py    From keras-lambda with MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example #17
Source File: test_topi_broadcast.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def test_shift():
    # explicit specify the output type
    verify_broadcast_binary_ele(
        (2, 1, 2), None, topi.right_shift, np.right_shift,
        dtype="int32", rhs_min=0, rhs_max=32)

    verify_broadcast_binary_ele(
        (1, 2, 2), (2,), topi.left_shift, np.left_shift,
        dtype="int32", rhs_min=0, rhs_max=32)

    verify_broadcast_binary_ele(
        (1, 2, 2), (2,), topi.left_shift, np.left_shift,
        dtype="int8", rhs_min=0, rhs_max=32) 
Example #18
Source File: load_syn.py    From Gated2Depth with MIT License 5 votes vote down vote up
def load_gated(root_dir, sample, slice):
    path = os.path.join(root_dir, 'gated{}_10bit'.format(slice), sample + '.png')
    img = cv2.imread(path, -1)
    img = np.right_shift(img, 2).astype(np.uint8)  # convert from 10bit to 8bit

    return img 
Example #19
Source File: LMAarrayFile.py    From lmatools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def countBits(values):
    # bit shifting routines are in numpy 1.4
    from numpy import array, left_shift, right_shift

    v = array(values).astype('uint32')


    # Bit counting for a 32 bit unsigned integer.
    # there is a fully generic version of this method at
    # http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
    # Binary magic numbers method, also found in  in pages 187-188 of Software Optimization Guide for AMD Athlon 64 and Opteron Processors.

    # The C version is:
    # v = v - ((v >> 1) & 0x55555555);                    # reuse input as temporary
    # v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     # temp
    # c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; # count

    fives  = int('0x55555555', base=16)
    threes = int('0x33333333', base=16)
    effs   = int('0xF0F0F0F',  base=16)
    ones   = int('0x1010101',  base=16)

    v = v - ( (right_shift(v, 1)) & fives);                        # reuse input as temporary
    v = (v & threes) + ( (right_shift(v,2)) & threes);             # temp
    c = right_shift(((v + (right_shift(v,4)) & effs) * ones), 24); # count

    return c 
Example #20
Source File: test_target_codegen_llvm.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def np_float2np_bf16(arr):
    ''' Convert a numpy array of float to a numpy array
    of bf16 in uint16'''
    orig = arr.view('<u4')
    bias = np.bitwise_and(np.right_shift(orig, 16), 1) + 0x7FFF
    return np.right_shift(orig + bias, 16).astype('uint16') 
Example #21
Source File: display.py    From push2-python with MIT License 5 votes vote down vote up
def rgb565_to_bgr565(rgb565_frame):
    r_filter = int('1111100000000000', 2)
    g_filter = int('0000011111100000', 2)
    b_filter = int('0000000000011111', 2)
    frame_r_filtered = numpy.bitwise_and(rgb565_frame, r_filter)
    frame_r_shifted = numpy.right_shift(frame_r_filtered, 11)  # Shift bits so R compoenent goes to the right
    frame_g_filtered = numpy.bitwise_and(rgb565_frame, g_filter)
    frame_g_shifted = frame_g_filtered  # No need to shift green, it stays in the same position
    frame_b_filtered = numpy.bitwise_and(rgb565_frame, b_filter)
    frame_b_shifted = numpy.left_shift(frame_b_filtered, 11)  # Shift bits so B compoenent goes to the left
    return frame_r_shifted + frame_g_shifted + frame_b_shifted  # Combine all channels


# Non-vectorized function for converting from rgb to bgr565 
Example #22
Source File: LMA_h5_write.py    From lmatools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def countBits(values):
    # bit shifting routines are in numpy 1.4
    from numpy import array, left_shift, right_shift
    
    v = array(values).astype('uint32')
    
    # Bit counting for a 32 bit unsigned integer.
    # there is a fully generic version of this method at
    # http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
    # Binary magic numbers method, also found in pages 187-188 of Software Optimization Guide for AMD Athlon 64 and Opteron Processors.

    # The C version is:
    # v = v - ((v >> 1) & 0x55555555);                    # reuse input as temporary
    # v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     # temp
    # c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; # count

    fives  = int('0x55555555', base=16)
    threes = int('0x33333333', base=16)
    effs   = int('0xF0F0F0F',  base=16)
    ones   = int('0x1010101',  base=16)
    
    v = v - ( (right_shift(v, 1)) & fives);                        # reuse input as temporary
    v = (v & threes) + ( (right_shift(v,2)) & threes);             # temp
    c = right_shift(((v + (right_shift(v,4)) & effs) * ones), 24); # count

    return c 
Example #23
Source File: walsh.py    From geoist with MIT License 5 votes vote down vote up
def walsh_order(n):
    ''' generate 'natural','dyadic','sequence' ordering of walsh matrix.

    Args:
        n (int): degree of walsh matrix.
    '''
    n = 2**np.ceil(np.log2(n))
    n = int(n)
    n_bits = len(np.binary_repr(n))-1
    print(n_bits)
    sequence_order = np.arange(n)
    tmp = np.right_shift(sequence_order,1)
    dyadic_order = np.bitwise_xor(sequence_order,tmp)
    natural_order = [int('{:0{width}b}'.format(i,width=n_bits)[::-1],2) for i in dyadic_order]
    return sequence_order,dyadic_order,natural_order 
Example #24
Source File: readDatFiles.py    From tierpsy-tracker with MIT License 5 votes vote down vote up
def read(self):
        self.curr_frame += 1
        if self.curr_frame < self.num_frames:
            fname = self.files[self.dat_order[self.curr_frame]] # is this indexing correct, or do we need to shift down by one?
            bin_dat = np.fromfile(fname, np.uint8)
            # every 3 bytes will correspond two pixel levels.
            D1 = bin_dat[:-40:3]
            D2 = bin_dat[1:-40:3]
            D3 = bin_dat[2:-40:3]

            # the image format is mono 12 packed (see web)
            # the first and third bytes represent the higher bits of the pixel intensity
            # while the second byte is divided into the lower bits.
            D1s = np.left_shift(D1.astype(np.uint16), 4) + \
                np.bitwise_and(D2, 15)
            D3s = np.left_shift(D3.astype(np.uint16), 4) + \
                np.right_shift(D2, 4)

            # the pixels seemed to be organized in this order
            image_decoded = np.zeros((self.height, self.width), np.uint16)
            image_decoded[::-1, -2::-2] = D3s.reshape((self.height, -1))
            image_decoded[::-1, ::-2] = D1s.reshape((self.height, -1))

            return (1, image_decoded)
        else:
            return (0, [], [], []) 
Example #25
Source File: load_real.py    From Gated2Depth with MIT License 5 votes vote down vote up
def load_gated(root_dir, sample, slice):
    path = os.path.join(root_dir, 'gated{}_10bit'.format(slice), sample + '.png')
    img = cv2.imread(path, -1)
    img = np.right_shift(img, 2).astype(np.uint8) # convert from 10bit to 8bit

    return img 
Example #26
Source File: exprsco.py    From nesmdb with MIT License 5 votes vote down vote up
def exprsco_to_rawsco(exprsco, clock=1789773.):
  rate, nsamps, exprsco = exprsco

  m = exprsco[:, :3, 0]
  m_zero = np.where(m == 0)

  m = m.astype(np.float32)
  f = 440 * np.power(2, ((m - 69) / 12))

  f_p, f_tr = f[:, :2], f[:, 2:]

  t_p = np.round((clock / (16 * f_p)) - 1)
  t_tr = np.round((clock / (32 * f_tr)) - 1)
  t = np.concatenate([t_p, t_tr], axis=1)

  t = t.astype(np.uint16)
  t[m_zero] = 0
  th = np.right_shift(np.bitwise_and(t, 0b11100000000), 8)
  tl = np.bitwise_and(t, 0b00011111111)

  rawsco = np.zeros((exprsco.shape[0], 4, 4), dtype=np.uint8)
  rawsco[:, :, 2:] = exprsco[:, :, 1:]
  rawsco[:, :3, 0] = th
  rawsco[:, :3, 1] = tl
  rawsco[:, 3, 1:] = exprsco[:, 3, :]

  return (clock, rate, nsamps, rawsco) 
Example #27
Source File: grid.py    From gxpy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _transform_color_int_to_rgba(np_values):
    np_values[np_values == gxapi.iDUMMY] = 0
    a = (np.right_shift(np_values, 24) & 0xFF).astype(np.uint8)
    b = (np.right_shift(np_values, 16) & 0xFF).astype(np.uint8)
    g = (np.right_shift(np_values, 8) & 0xFF).astype(np.uint8)
    r = (np_values & 0xFF).astype(np.uint8)
    # the values for color grids actually do not contain alphas but just
    # 0 or 1 to indicate if the color is valid or not
    a[a > 0] = 255
    return np.array([r, g, b, a]).transpose() 
Example #28
Source File: cannonball_wrapper.py    From agent-trainer with MIT License 5 votes vote down vote up
def _rgb_integers_to_components(self, rgb_integers):
        red_mask = 0x00FF0000
        green_mask = 0x0000FF00
        blue_mask =  0x000000FF
        masks = np.asarray([[red_mask, green_mask, blue_mask]])
        masked_rgb_components = np.bitwise_and(rgb_integers, masks)

        red_shifted = np.right_shift(masked_rgb_components[:,0], 16)
        green_shifted = np.right_shift(masked_rgb_components[:,1], 8)
        blue_shifted =  np.right_shift(masked_rgb_components[:,2], 0)
        return np.array([red_shifted, green_shifted, blue_shifted]).transpose() 
Example #29
Source File: packer.py    From blueoil with Apache License 2.0 5 votes vote down vote up
def run(self, tensor: np.ndarray, data_format: str = 'NHWC') -> np.ndarray:
        """Pack a tensor.

        Args:
            tensor (np.ndarray): Input tensor.
            data_format (str): Order of dimension. This defaults to 'NHWC', where 'N' is
                the number of kernels, 'H' and 'W' are the height and
                width, and 'C' is the depth / the number of channels.

        Returns:
            np.ndarray: Quantized tensor.

        """

        wordsize = self.wordsize

        if (tensor >= (2 ** self.bitwidth)).any():
            raise ValueError("all value of input tensor must be less than bit width ({})".format(self.bitwidth))

        output_size = tensor.size // wordsize
        output_size += 1 if tensor.size % wordsize != 0 else 0
        output_size *= self.bitwidth

        tensor_flat = tensor.flatten(order='C').astype(np.uint32)
        output = np.zeros(output_size, dtype=np.uint32)
        oi = 0
        for i in range(0, tensor.size, wordsize):
            if i + wordsize < tensor.size:
                sliced_tensor = tensor_flat[i:i + wordsize]
            else:
                sliced_tensor = tensor_flat[i:]

            for _ in range(0, self.bitwidth):
                output[oi] = self._pack_to_word(np.bitwise_and(sliced_tensor, 1))
                oi += 1
                sliced_tensor = np.right_shift(sliced_tensor, 1)

        return output.reshape([1, output_size]) 
Example #30
Source File: test_topi_broadcast.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def test_shift():
    # explicit specify the output type
    verify_broadcast_binary_ele(
        (2, 1, 2), None, topi.right_shift, np.right_shift,
        dtype="int32", rhs_min=0, rhs_max=32)

    verify_broadcast_binary_ele(
        (1, 2, 2), (2,), topi.left_shift, np.left_shift,
        dtype="int32", rhs_min=0, rhs_max=32)

    verify_broadcast_binary_ele(
        (1, 2, 2), (2,), topi.left_shift, np.left_shift,
        dtype="int8", rhs_min=0, rhs_max=32)