Python numpy.left_shift() Examples

The following are 30 code examples of numpy.left_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: led.py    From audio-reactive-led-strip with MIT License 6 votes vote down vote up
def _update_pi():
    """Writes new LED values to the Raspberry Pi's LED strip

    Raspberry Pi uses the rpi_ws281x to control the LED strip directly.
    This function updates the LED strip with new values.
    """
    global pixels, _prev_pixels
    # Truncate values and cast to integer
    pixels = np.clip(pixels, 0, 255).astype(int)
    # Optional gamma correction
    p = _gamma[pixels] if config.SOFTWARE_GAMMA_CORRECTION else np.copy(pixels)
    # Encode 24-bit LED values in 32 bit integers
    r = np.left_shift(p[0][:].astype(int), 8)
    g = np.left_shift(p[1][:].astype(int), 16)
    b = p[2][:].astype(int)
    rgb = np.bitwise_or(np.bitwise_or(r, g), b)
    # Update the pixels
    for i in range(config.N_PIXELS):
        # Ignore pixels if they haven't changed (saves bandwidth)
        if np.array_equal(p[:, i], _prev_pixels[:, i]):
            continue
        #strip._led_data[i] = rgb[i]
        strip._led_data[i] = int(rgb[i])
    _prev_pixels = np.copy(p)
    strip.show() 
Example #2
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 #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: led.py    From Systematic-LEDs with MIT License 6 votes vote down vote up
def _update_pi():
    """Writes new LED values to the Raspberry Pi's LED strip

    Raspberry Pi uses the rpi_ws281x to control the LED strip directly.
    This function updates the LED strip with new values.
    """
    global pixels, _prev_pixels
    # Truncate values and cast to integer
    pixels = np.clip(pixels, 0, 255).astype(int)
    # Optional gamma correction
    p = _gamma[pixels] if config.settings["configuration"]["SOFTWARE_GAMMA_CORRECTION"] else np.copy(pixels)
    # Encode 24-bit LED values in 32 bit integers
    r = np.left_shift(p[0][:].astype(int), 8)
    g = np.left_shift(p[1][:].astype(int), 16)
    b = p[2][:].astype(int)
    rgb = np.bitwise_or(np.bitwise_or(r, g), b)
    # Update the pixels
    for i in range(config.settings["configuration"]["N_PIXELS"]):
        # Ignore pixels if they haven't changed (saves bandwidth)
        if np.array_equal(p[:, i], _prev_pixels[:, i]):
            continue
        strip._led_data[i] = rgb[i]
    _prev_pixels = np.copy(p)
    strip.show() 
Example #5
Source File: devices.py    From Systematic-LEDs with MIT License 6 votes vote down vote up
def show(self, pixels):
        """Writes new LED values to the Raspberry Pi's LED strip
        Raspberry Pi uses the rpi_ws281x to control the LED strip directly.
        This function updates the LED strip with new values.
        """
        # Truncate values and cast to integer
        n_pixels = pixels.shape[1]
        pixels = pixels.clip(0, 255).astype(int)
        # Optional gamma correction
        pixels = _GAMMA_TABLE[pixels]
        # Encode 24-bit LED values in 32 bit integers
        r = np.left_shift(pixels[0][:].astype(int), 8)
        g = np.left_shift(pixels[1][:].astype(int), 16)
        b = pixels[2][:].astype(int)
        rgb = np.bitwise_or(np.bitwise_or(r, g), b)
        # Update the pixels
        for i in range(n_pixels):
            self.strip.setPixelColor(i, neopixel.Color(rgb[i]))
        self.strip.show() 
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: output.py    From music_led_strip_control with MIT License 6 votes vote down vote up
def show(self, output_array):
        

        import _rpi_ws281x as ws # pylint: disable=import-error

        # Typecast the array to int
        output_array = output_array.clip(0, 255).astype(int)

        # sort the colors. grb
        g = np.left_shift(output_array[1][:].astype(int), 16) # pylint: disable=assignment-from-no-return
        r = np.left_shift(output_array[0][:].astype(int), 8) # pylint: disable=assignment-from-no-return    
        b = output_array[2][:].astype(int)
        rgb = np.bitwise_or(np.bitwise_or(r, g), b).astype(int)

        # You can only use ws2811_leds_set with the custom version.
        #ws.ws2811_leds_set(self.channel, rgb)
        for i in range(self._led_count):
            ws.ws2811_led_set(self.channel, i, rgb[i].item())


        resp = ws.ws2811_render(self._leds)

        if resp != ws.WS2811_SUCCESS:
            message = ws.ws2811_get_return_t_str(resp)
            raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, message)) 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
Source File: readDatFiles.py    From tierpsy-tracker with MIT License 5 votes vote down vote up
def __init__(self, dirName):
        self.fid = dirName
        if not os.path.exists(self.fid):
            print('Error: Directory (%s) does not exist.' % self.fid)
            exit()

        self.files = glob.glob(os.path.join(self.fid, '*.dat'))
        # TODO: figure out how to really do this. This file order works half of the time
        # get the order of the frames from the file name.
        file_num_str = [os.path.split(x)[1].partition('spool')[
            0] for x in self.files]
        # first we assume that the filename contains the frame number 00001,
        # 00002, 00003
        self.dat_order = sorted([int(x) for x in file_num_str])
        # check in the indexes in the file order are really continuous. The
        # ordered index should go 1, 2, 3, 4
        is_continous = all(np.diff(self.dat_order) == 1)
        if not is_continous:
            # the file name can contain the image number as an inverted string,
            # e.g. 6100000 -> 0000016
            self.dat_order = sorted([int(x[::-1]) for x in file_num_str])

            # check again in the indexes in the file order are really
            # continuous. This will throw and error if it is not the case
            assert all(np.diff(self.dat_order) == 1)

        # It seems that the last 40 bytes of each file are the header (it
        # contains zeros and the size of the image 2080*2156)
        bin_dat = np.fromfile(self.files[0], np.uint8)
        header = bin_dat[-40:].astype(np.uint16)
        header = np.left_shift(header[1::2], 8) + header[0::2]
        im_size = header[14:16]
        self.height = im_size[1]
        self.width = im_size[0]
        self.dtype = np.uint16
        self.num_frames = len(self.dat_order)
        # initialize pointer for frames
        self.curr_frame = -1 
Example #21
Source File: column.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _wrapx(input, output, repeat):
    """
    Wrap the X format column Boolean array into an ``UInt8`` array.

    Parameters
    ----------
    input
        input Boolean array of shape (`s`, `repeat`)

    output
        output ``Uint8`` array of shape (`s`, `nbytes`)

    repeat
        number of bits
    """

    output[...] = 0  # reset the output
    nbytes = ((repeat - 1) // 8) + 1
    unused = nbytes * 8 - repeat
    for i in range(nbytes):
        _min = i * 8
        _max = min((i + 1) * 8, repeat)
        for j in range(_min, _max):
            if j != _min:
                np.left_shift(output[..., i], 1, output[..., i])
            np.add(output[..., i], input[..., j], output[..., i])

    # shift the unused bits
    np.left_shift(output[..., i], unused, output[..., i]) 
Example #22
Source File: test_target_codegen_llvm.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def np_bf162np_float(arr):
    ''' Convert a numpy array of bf16 (uint16) to a numpy array
    of float'''
    u32 = np.left_shift(arr.astype('uint32'), 16)
    return u32.view('<f4') 
Example #23
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 #24
Source File: seqc.py    From qupulse with MIT License 5 votes vote down vote up
def to_csv_compatible_table(self):
        """The integer values in that file should be 18-bit unsigned integers with the two least significant bits
        being the markers. The values are mapped to 0 => -FS, 262143 => +FS, with FS equal to the full scale.

        >>> np.savetxt(waveform_dir, binary_waveform.to_csv_compatible_table(), fmt='%u')
        """
        table = np.zeros((len(self), 2), dtype=np.uint32)
        table[:, 0] = self.ch1
        table[:, 1] = self.ch2
        np.left_shift(table, 2, out=table)
        table[:, 0] += self.markers_ch1
        table[:, 1] += self.markers_ch2

        return table 
Example #25
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 #26
Source File: payload.py    From baseband with GNU General Public License v3.0 5 votes vote down vote up
def decode_4bit(words):
    """Decode 4-bit data.

    For a given int8 byte containing bits 76543210,
    the first sample is in 3210, the second in 7654, and both are interpreted
    as signed 4-bit integers.
    """
    # left_shift(byte[:,np.newaxis], shift40):  [3210xxxx, 76543210]
    split = np.left_shift(words[:, np.newaxis], shift40).ravel()
    # right_shift(..., 4):                      [33333210, 77777654]
    # so least significant bits go first.
    split >>= 4
    return split.astype(np.float32) 
Example #27
Source File: photometric.py    From mmcv with Apache License 2.0 5 votes vote down vote up
def posterize(img, bits):
    """Posterize an image (reduce the number of bits for each color channel)

    Args:
        img (ndarray): Image to be posterized.
        bits (int): Number of bits (1 to 8) to use for posterizing.

    Returns:
        ndarray: The posterized image.
    """
    shift = 8 - bits
    img = np.left_shift(np.right_shift(img, shift), shift)
    return img 
Example #28
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) 
Example #29
Source File: spcreader.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def load_spc(fname):
    """Load data from Becker&Hickl SPC files.

    Returns:
        3 numpy arrays: timestamps, detector, nanotime
    """
    spc_dtype = np.dtype([('field0', '<u2'), ('b', '<u1'), ('c', '<u1'),
                          ('a', '<u2')])
    data = np.fromfile(fname, dtype=spc_dtype)

    nanotime =  4095 - np.bitwise_and(data['field0'], 0x0FFF)
    detector = data['c']

    # Build the macrotime (timestamps) using in-place operation for efficiency
    timestamps = data['b'].astype('int64')
    np.left_shift(timestamps, 16, out=timestamps)
    timestamps += data['a']

    # extract the 13-th bit from data['field0']
    overflow = np.bitwise_and(np.right_shift(data['field0'], 13), 1)
    overflow = np.cumsum(overflow, dtype='int64')

    # Add the overflow bits
    timestamps += np.left_shift(overflow, 24)

    return timestamps, detector, nanotime 
Example #30
Source File: sunrgbd_dataset.py    From DepthAwareCNN with MIT License 5 votes vote down vote up
def __getitem__(self, index):
        #self.paths['images'][index]
        img = np.asarray(Image.open(self.paths_dict['images'][index]))#.astype(np.uint8)
        HHA = np.asarray(Image.open(self.paths_dict['HHAs'][index]))[:,:,::-1]
        seg = np.asarray(Image.open(self.paths_dict['segs'][index])).astype(np.uint8)-1
        depth = np.asarray(Image.open(self.paths_dict['depths'][index])).astype(np.uint16)
        depth = np.bitwise_or(np.right_shift(depth,3),np.left_shift(depth,16-3))
        depth = depth.astype(np.float32)/120. # 1/5 * depth

        assert (img.shape[0]==HHA.shape[0]==seg.shape[0]==depth.shape[0])
        assert (img.shape[1]==HHA.shape[1]==seg.shape[1]==depth.shape[1])

        params = get_params_sunrgbd(self.opt, seg.shape, test=True)
        depth_tensor_tranformed = transform(depth, params, normalize=False,istrain=self.opt.isTrain)
        seg_tensor_tranformed = transform(seg, params, normalize=False,method='nearest',istrain=self.opt.isTrain)
        # HHA_tensor_tranformed = transform(HHA, params,istrain=self.opt.isTrain)
        if self.opt.inputmode == 'bgr-mean':
            img_tensor_tranformed = transform(img, params, normalize=False, istrain=self.opt.isTrain, option=1)
            HHA_tensor_tranformed = transform(HHA, params, normalize=False, istrain=self.opt.isTrain, option=2)
        else:
            img_tensor_tranformed = transform(img, params, istrain=self.opt.isTrain, option=1)
            HHA_tensor_tranformed = transform(HHA, params, istrain=self.opt.isTrain, option=2)

        return {'image':img_tensor_tranformed,
                'depth':depth_tensor_tranformed,
                'seg': seg_tensor_tranformed,
                'HHA': HHA_tensor_tranformed,
                'imgpath': self.paths_dict['segs'][index]}