Python numpy.left_shift() Examples

The following are 30 code examples for showing how to use numpy.left_shift(). 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_ufunc.py    License: 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 2
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_ufunc.py    License: 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 3
Project: vnpy_crypto   Author: birforce   File: test_ufunc.py    License: 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 4
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_ufunc.py    License: 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 5
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_ufunc.py    License: 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 6
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
Project: pySINDy   Author: luckystarufo   File: test_ufunc.py    License: 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 8
Project: mxnet-lambda   Author: awslabs   File: test_ufunc.py    License: 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
Project: music_led_strip_control   Author: TobKra96   File: output.py    License: 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 10
Project: Systematic-LEDs   Author: not-matt   File: devices.py    License: 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 11
Project: Systematic-LEDs   Author: not-matt   File: led.py    License: 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 12
Project: elasticintel   Author: securityclippy   File: test_ufunc.py    License: 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 13
Project: Piano-LED-Visualizer   Author: onlaj   File: LCD_1in44.py    License: 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 14
Project: coffeegrindsize   Author: jgagneastro   File: test_ufunc.py    License: 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 15
Project: audio-reactive-led-strip   Author: scottlawsonbc   File: led.py    License: 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 16
Project: incubator-tvm   Author: apache   File: test_op_level4.py    License: 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 17
Project: Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda   Author: PacktPublishing   File: test_ufunc.py    License: 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
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_ufunc.py    License: 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
Project: keras-lambda   Author: sunilmallya   File: test_ufunc.py    License: 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 20
Project: baseband   Author: mhvk   File: payload.py    License: 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 21
Project: nesmdb   Author: chrisdonahue   File: exprsco.py    License: MIT License 5 votes vote down vote up
def rawsco_to_exprsco(rawsco, midi_valid_range=(21, 108)):
  clock, rate, nsamps, rawsco = rawsco
  assert rate == 44100
  assert rawsco.shape[0] == nsamps

  nsamps = rawsco.shape[0]

  t = rawsco[:, :3, :2].astype(np.uint16)
  t = np.left_shift(t[:, :, 0], 8) + t[:, :, 1]
  t = t.astype(np.float32)

  t_p, t_tr = t[:, :2], t[:, 2:]

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

  m = 69 + (12 * np.log(f / 440)) / np.log(2)
  m = np.round(m)

  # Clip notes to midi range
  m[np.where(m < midi_valid_range[0])] = 0
  m[np.where(m > midi_valid_range[1])] = 0
  m = m.astype(np.uint8)

  # Create output score
  exprsco = np.zeros((nsamps, 4, 3), dtype=np.uint8)

  # Set notes
  exprsco[:, :3, 0] = m
  exprsco[:, 3, 0] = rawsco[:, 3, 1]

  # Set velocity
  exprsco[:, :, 1] = np.where(exprsco[:, :, 0] > 0, rawsco[:, :, 2], 0)

  # Set extra
  exprsco[:, :, 2] = rawsco[:, :, 3]

  return (rate, nsamps, exprsco) 
Example 22
Project: st7789-python   Author: pimoroni   File: __init__.py    License: MIT License 5 votes vote down vote up
def image_to_data(self, image, rotation=0):
        """Generator function to convert a PIL image to 16-bit 565 RGB bytes."""
        # NumPy is much faster at doing this. NumPy code provided by:
        # Keith (https://www.blogger.com/profile/02555547344016007163)
        pb = np.rot90(np.array(image.convert('RGB')), rotation // 90).astype('uint8')

        result = np.zeros((self._width, self._height, 2), dtype=np.uint8)
        result[..., [0]] = np.add(np.bitwise_and(pb[..., [0]], 0xF8), np.right_shift(pb[..., [1]], 5))
        result[..., [1]] = np.add(np.bitwise_and(np.left_shift(pb[..., [1]], 3), 0xE0), np.right_shift(pb[..., [2]], 3))
        return result.flatten().tolist() 
Example 23
Project: DepthAwareCNN   Author: laughtervv   File: sunrgbd_dataset.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, index):
        #self.paths['images'][index]
        # print self.opt.scale,self.opt.flip,self.opt.crop,self.opt.colorjitter
        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)

        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])

        depth = np.bitwise_or(np.right_shift(depth,3),np.left_shift(depth,16-3))
        depth = depth.astype(np.float32)/120. # 1/5 * depth




        params = get_params_sunrgbd(self.opt, seg.shape, maxcrop=.7)
        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)
        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)


        # print img_tensor_tranformed
        # print(np.unique(depth_tensor_tranformed.numpy()).shape)
        # print img_tensor_tranformed.size()
        return {'image':img_tensor_tranformed,
                'depth':depth_tensor_tranformed,
                'seg': seg_tensor_tranformed,
                'HHA': HHA_tensor_tranformed,
                'imgpath': self.paths_dict['segs'][index]} 
Example 24
Project: DepthAwareCNN   Author: laughtervv   File: sunrgbd_dataset.py    License: 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]} 
Example 25
Project: FRETBursts   Author: tritemio   File: spcreader.py    License: 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 26
Project: training_results_v0.6   Author: mlperf   File: test_topi_broadcast.py    License: 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 27
Project: mmcv   Author: open-mmlab   File: photometric.py    License: 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
Project: tierpsy-tracker   Author: ver228   File: readDatFiles.py    License: 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 29
Project: tierpsy-tracker   Author: ver228   File: readDatFiles.py    License: 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 30
Project: qupulse   Author: qutech   File: seqc.py    License: 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