• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python numpy.unpackbits函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中numpy.unpackbits函数的典型用法代码示例。如果您正苦于以下问题:Python unpackbits函数的具体用法?Python unpackbits怎么用?Python unpackbits使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了unpackbits函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: build_syndrom_table

def build_syndrom_table(H):
    """
    >>> H = np.array([[0, 1, 1, 0, 1],\
                      [1, 1, 1, 1, 0],\
                      [1, 0, 0, 1, 0]], np.uint8)
    >>> for a, b in build_syndrom_table(H):\
            print("{}: {}".format(a, b))
    [0 1 1]: [0 0 0 1 0]
    [1 1 0]: [0 0 1 0 0]
    [1 0 1]: [0 0 1 1 0]
    [1 0 0]: [0 0 0 0 1]
    [1 1 1]: [0 0 0 1 1]
    [0 1 0]: [0 0 1 0 1]
    [0 0 1]: [0 0 1 1 1]
    """
    r, n = H.shape
    table = []
    already = set()
    for y in range(0, 2 ** n):
        y = np.unpackbits(np.array([y], np.int64).view(np.uint8).reshape(-1, 1), axis=-1)[:, ::-1].ravel()[:n]
        s = np.dot(y, H.T) % 2
        if np.all(s == 0) or str(s) in already:
            continue
        already.add(str(s))
        best_e = None
        for e in range(0, 2 ** n):
            e = np.unpackbits(np.array([e], np.int64).view(np.uint8).reshape(-1, 1), axis=-1)[:, ::-1].ravel()[:n]
            if not np.all(s == np.dot(e, H.T) % 2):
                continue
            if best_e is None or np.sum(e) <= np.sum(best_e):
                best_e = e
        table.append((s, best_e))
    return table
开发者ID:isae,项目名称:itmo_summaries_4_course,代码行数:33,代码来源:t23_27.py


示例2: _read_bcd

def _read_bcd(fi, length, left_part):
    """
    Interprets a byte string as binary coded decimals.

    See: https://en.wikipedia.org/wiki/Binary-coded_decimal#Basics

    :param fi: A buffer containing the bytes to read.
    :param length: number of bytes to read.
    :type length: int or float
    :param left_part: If True, start the reading from the first half part
        of the first byte. If False, start the reading from
        the second half part of the first byte.
    :type left_part: bool
    """
    tens = np.power(10, range(12))[::-1]
    nbr_half_bytes = round(2*length)
    if isinstance(length, float):
        length = int(length) + 1
    byte_values = fi.read(length)
    ints = np.frombuffer(byte_values, dtype='<u1', count=length)
    if left_part is True:
        unpack_bits = np.unpackbits(ints).reshape(-1, 4)[0:nbr_half_bytes]
    else:
        unpack_bits = np.unpackbits(ints).reshape(-1, 4)[1:nbr_half_bytes+1]
    bits = np.dot(unpack_bits, np.array([1, 2, 4, 8])[::-1].reshape(4, 1))
    if np.any(bits > 9):
        raise ValueError('invalid bcd values encountered')
    return np.dot(tens[-len(bits):], bits)[0]
开发者ID:Brtle,项目名称:obspy,代码行数:28,代码来源:util.py


示例3: fix

 def fix(index):
     ep = self.index[index]
     ev = v
     if self._metric == "hamming":
         ep = numpy.unpackbits(ep)
         ev = numpy.unpackbits(ev)
     return (index, pd[self._metric]['distance'](ep, ev))
开发者ID:ilyaraz,项目名称:ann-benchmarks,代码行数:7,代码来源:bruteforce.py


示例4: write_tune_mask

 def write_tune_mask(self, mask):
         # 1  -> Sign = 1, TDac = 15 1111(lowest)
         # ...
         # 15 -> Sign = 1, TDac = 0  0000
         # 16 -> Sign = 0, TDac = 0  0001
         # ...
         # 31 -> Sign = 0, TDac = 15 1111
         
         mask_out = np.copy(mask)
         mask_bits = np.unpackbits(mask_out)
         mask_bits_array = np.reshape(mask_bits, (64,64,8))
         mask_out[mask_bits_array[:,:,3] == 0] = 16 - mask_out[mask_bits_array[:,:,3] == 0]#15
         #investigate here how to set 0 to 0
         mask_bits = np.unpackbits(mask_out)
         mask_bits_array = np.reshape(mask_bits, (64,64,8)).astype(np.bool)
         mask_bits_array[:,:,3] = ~mask_bits_array[:,:,3]
          
         for bit in range(4):
             mask_bits_sel = mask_bits_array[:,:,7-bit]
             self.write_pixel(mask_bits_sel)
             self['global_conf']['TDacLd'][bit] = 1
             self.write_global()
             self['global_conf']['TDacLd'][bit] = 0
         
         mask_bits_sel = mask_bits_array[:,:,3]
         self.write_pixel(mask_bits_sel)
         self['global_conf']['SignLd'] = 1
         self.write_global()
         self['global_conf']['SignLd'] = 0
开发者ID:Marrkson,项目名称:fe65_p2,代码行数:29,代码来源:fe65p2.py


示例5: get_batch

def get_batch(batch_size, binary=False):
    """Gets a batch of data.

    Args:
        batch_size (int): how much data to generate.
        binary (Optional[bool]): whether the data should be scalars in (0,1]
            or binary vectors (8 bit, with 16 bit results).

    Returns:
        batch: (a, b, target) where target = ab (elementwise).
    """
    if not binary:
        # eas
        input_a = np.random.random((batch_size, 1))
        input_b = np.random.random((batch_size, 1))
        target = input_a * input_b
    else:
        input_a = np.random.randint(256, size=(batch_size, 1))
        input_b = np.random.randint(256, size=(batch_size, 1))
        target = input_a * input_b
        input_a = np.unpackbits(input_a.astype(np.uint8))
        input_b = np.unpackbits(input_b.astype(np.uint8))
        # now do target
        target_lsb = target & 0xff
        target_lsb = np.unpackbits(target_lsb.astype(np.uint8))
        target_msb = target >> 8
        target_msb = np.unpackbits(target_msb.astype(np.uint8))
        target = np.hstack((target_msb.reshape(batch_size, 8),
                            target_lsb.reshape(batch_size, 8)))
    return input_a, input_b, target
开发者ID:PFCM,项目名称:rnns,代码行数:30,代码来源:multiplication.py


示例6: decodeStripe

 def decodeStripe(self, off, length, nStripe):
     stripeOff = off
     end = off + length
     x = 8 * nStripe
     y = 0
     while (stripeOff < end):
         count = self.res.data[stripeOff]
         stripeOff += 1
         if (count & 0x80):
             count &= 0x7F
             bits = unpackbits(uint8(self.res.data[stripeOff]))
             stripeOff += 1
             for j in range(0, count):
                 for k in range(0, 8):
                     if bits[k] == 1:
                         self.emptyMask = False
                         self.img.putpixel((x + k, y), 1)
                 y += 1
         else:
             for j in range(0, count):
                 bits = unpackbits(uint8(self.res.data[stripeOff]))
                 stripeOff += 1
                 for k in range(0, 8):
                     if bits[k] == 1:
                         self.emptyMask = False
                         self.img.putpixel((x + k, y), 1)
                 y += 1
开发者ID:numeroband,项目名称:lage,代码行数:27,代码来源:images.py


示例7: elucidate_cc_split

def elucidate_cc_split(parent_id, split_id):
	parent_id_bytes = numpy.array(tuple(parent_id)).view(dtype = numpy.uint8)
	split_id_bytes = numpy.array(tuple(split_id)).view(dtype = numpy.uint8)

	parent_id_bits = numpy.unpackbits(parent_id_bytes)
	split_id_bits = numpy.unpackbits(split_id_bytes)

	n_parent_bits = len(parent_id_bits)
	n_split_bits = len(split_id_bits)

	child1_bits = numpy.zeros(n_parent_bits, dtype = numpy.uint8)
	child2_bits = numpy.zeros(n_parent_bits, dtype = numpy.uint8)

	j = 0
	for i in range(n_parent_bits):
		if parent_id_bits[i] == 1:
			if j < n_split_bits:
				if split_id_bits[j] == 1:
					child1_bits[i] = 1
				else:
					child2_bits[i] = 1
			else:
				child2_bits[i] = 1

			j += 1

	child1_bytes = numpy.packbits(child1_bits)
	child2_bytes = numpy.packbits(child2_bits)

	child1_id = child1_bytes.tostring().rstrip("\x00") # urgh C (null terminated strings)
	child2_id = child2_bytes.tostring().rstrip("\x00") # vs Python (not null terminated) strings

	return child1_id, child2_id
开发者ID:genomescale,项目名称:scculs,代码行数:33,代码来源:libscculs.py


示例8: __init__

 def __init__(self, filename="mario_ROM.zip", offset=2049):
     self.offset = offset
     if zipfile.is_zipfile(filename):
         zp = zipfile.ZipFile(filename)
         data = np.unpackbits(np.frombuffer(zp.read(zp.filelist[0]), dtype=np.uint8))
     else:
         data = np.unpackbits(np.fromfile(filename, dtype=np.uint8))
     self.data = data.reshape((-1, 8, 8))
开发者ID:rexyroo,项目名称:PythonicPerambulations,代码行数:8,代码来源:animate_mario.py


示例9: set_color

 def set_color(self, led, intensity, color):
     addr_b = np.unpackbits(np.array([led], dtype=np.uint8))[2:]
     intensity_b = np.unpackbits(np.array([intensity], dtype=np.uint8))
     color_b = itertools.chain(*[np.unpackbits(np.array([c>>4], dtype=np.uint8))[4:] for c in reversed(color)])
     self.write_begin()
     for b in itertools.chain(addr_b, intensity_b, color_b):
         self.write_bit(b)
     self.write_end()
开发者ID:mboyd,项目名称:Bemis-100,代码行数:8,代码来源:rpi_ctl.py


示例10: main

def main(args):
    x1 = np.load(args.infile1)
    x2 = np.load(args.infile2)
    assert len(x1.shape) == 2, 'infile1 should be 2d array!'
    assert len(x2.shape) == 2, 'infile2 should be 2d array!'
    assert x1.shape[0] == x2.shape[0], 'two infile should have same rows!'
    x1 = np.unpackbits(x1, axis=1)
    x2 = np.unpackbits(x2, axis=1)
    r1 = x1.shape[1] if args.row1 == 0 else args.row1
    r2 = x2.shape[1] if args.row2 == 0 else args.row2
    N = x1.shape[0]
    print(r1, r2, N)
    x1 = np.packbits(x1[:, :r1].T, axis=1)
    x2 = np.packbits(x2[:, :r2].T, axis=1)

    if args.gpu >= 0:
        chainer.cuda.get_device(args.gpu).use()
        x1 = cuda.to_gpu(x1)
        x2 = cuda.to_gpu(x2)
        xp = cupy
    else:
        xp = np
    # popcount LUT
    pc = xp.zeros(256, dtype=np.uint8)
    for i in range(256):
        pc[i] = ( i & 1 ) + pc[i/2]

    hamm = xp.zeros((r1, r2), dtype=np.int32)
    for i in tqdm(range(r1)):
        x1i = xp.tile(x1[i], (r2, 1))
        if args.operation == 'xor':
            hamm[i] = xp.take(pc, xp.bitwise_xor(x1i, x2).astype(np.int32)).sum(axis=1)
        elif args.operation == 'nand':
            hamm[i] = xp.take(pc, xp.invert(xp.bitwise_and(x1i, x2)).astype(np.int32)).sum(axis=1)
        #for j in range(r2):
            #hamm[i, j] = xp.take(pc, xp.bitwise_xor(x1[i], x2[j])).sum()
    x1non0 = xp.tile((x1.sum(axis=1)>0), (r2, 1)).T.astype(np.int32)
    x2non0 = xp.tile((x2.sum(axis=1)>0), (r1, 1)).astype(np.int32)
    print(x1non0.shape, x2non0.shape)
    non0filter = x1non0 * x2non0
    print(non0filter.max(), non0filter.min())
    hamm = non0filter * hamm + np.iinfo(np.int32).max * (1 - non0filter)
    #non0filter *= np.iinfo(np.int32).max
    #hamm *= non0filter
    if xp == cupy:
        hamm = hamm.get()
    #xp.savetxt(args.out, hamm, delimiter=args.delim)
    np.save(args.out, hamm)

    if args.nearest > 0:
        hamm_s = np.sort(hamm.flatten())
        hamm_as = np.argsort(hamm.flatten())
        x, y = np.unravel_index(hamm_as[:args.nearest], hamm.shape)
        fname, ext = os.path.splitext(args.out)
        np.savetxt(fname + '_top{0}.tsv'.format(args.nearest),
            np.concatenate((x[np.newaxis], y[np.newaxis], hamm_s[np.newaxis,:args.nearest]), axis=0).T,
            fmt='%d', delimiter='\t')
开发者ID:isl-kobayan,项目名称:chainer-minc-2500,代码行数:57,代码来源:hamm_dist.py


示例11: test_unpackbits_large

def test_unpackbits_large():
    # test all possible numbers via comparison to already tested packbits
    d = np.arange(277, dtype=np.uint8)
    assert_array_equal(np.packbits(np.unpackbits(d)), d)
    assert_array_equal(np.packbits(np.unpackbits(d[::2])), d[::2])
    d = np.tile(d, (3, 1))
    assert_array_equal(np.packbits(np.unpackbits(d, axis=1), axis=1), d)
    d = d.T.copy()
    assert_array_equal(np.packbits(np.unpackbits(d, axis=0), axis=0), d)
开发者ID:anntzer,项目名称:numpy,代码行数:9,代码来源:test_packbits.py


示例12: test_unpackbits_count

def test_unpackbits_count():
    # test complete invertibility of packbits and unpackbits with count
    x = np.array([
        [1, 0, 1, 0, 0, 1, 0],
        [0, 1, 1, 1, 0, 0, 0],
        [0, 0, 1, 0, 0, 1, 1],
        [1, 1, 0, 0, 0, 1, 1],
        [1, 0, 1, 0, 1, 0, 1],
        [0, 0, 1, 1, 1, 0, 0],
        [0, 1, 0, 1, 0, 1, 0],
    ], dtype=np.uint8)

    padded1 = np.zeros(57, dtype=np.uint8)
    padded1[:49] = x.ravel()

    packed = np.packbits(x)
    for count in range(58):
        unpacked = np.unpackbits(packed, count=count)
        assert_equal(unpacked.dtype, np.uint8)
        assert_array_equal(unpacked, padded1[:count])
    for count in range(-1, -57, -1):
        unpacked = np.unpackbits(packed, count=count)
        assert_equal(unpacked.dtype, np.uint8)
        # count -1 because padded1 has 57 instead of 56 elements
        assert_array_equal(unpacked, padded1[:count-1])
    for kwargs in [{}, {'count': None}]:
        unpacked = np.unpackbits(packed, **kwargs)
        assert_equal(unpacked.dtype, np.uint8)
        assert_array_equal(unpacked, padded1[:-1])
    assert_raises(ValueError, np.unpackbits, packed, count=-57)

    padded2 = np.zeros((9, 9), dtype=np.uint8)
    padded2[:7, :7] = x

    packed0 = np.packbits(x, axis=0)
    packed1 = np.packbits(x, axis=1)
    for count in range(10):
        unpacked0 = np.unpackbits(packed0, axis=0, count=count)
        assert_equal(unpacked0.dtype, np.uint8)
        assert_array_equal(unpacked0, padded2[:count, :x.shape[1]])
        unpacked1 = np.unpackbits(packed1, axis=1, count=count)
        assert_equal(unpacked1.dtype, np.uint8)
        assert_array_equal(unpacked1, padded2[:x.shape[1], :count])
    for count in range(-1, -9, -1):
        unpacked0 = np.unpackbits(packed0, axis=0, count=count)
        assert_equal(unpacked0.dtype, np.uint8)
        # count -1 because one extra zero of padding
        assert_array_equal(unpacked0, padded2[:count-1, :x.shape[1]])
        unpacked1 = np.unpackbits(packed1, axis=1, count=count)
        assert_equal(unpacked1.dtype, np.uint8)
        assert_array_equal(unpacked1, padded2[:x.shape[0], :count-1])
    for kwargs in [{}, {'count': None}]:
        unpacked0 = np.unpackbits(packed0, axis=0, **kwargs)
        assert_equal(unpacked0.dtype, np.uint8)
        assert_array_equal(unpacked0, padded2[:-1, :x.shape[1]])
        unpacked1 = np.unpackbits(packed1, axis=1, **kwargs)
        assert_equal(unpacked1.dtype, np.uint8)
        assert_array_equal(unpacked1, padded2[:x.shape[0], :-1])
    assert_raises(ValueError, np.unpackbits, packed0, axis=0, count=-9)
    assert_raises(ValueError, np.unpackbits, packed1, axis=1, count=-9)
开发者ID:anntzer,项目名称:numpy,代码行数:60,代码来源:test_packbits.py


示例13: get_keys

    def get_keys(self, key_array=None, offset=0, n_keys=None):
        """ Get the ordered list of keys that the combination allows

        :param key_array: \
            Optional array into which the returned keys will be placed
        :type key_array: array-like of int
        :param offset: \
            Optional offset into the array at which to start placing keys
        :type offset: int
        :param n_keys: \
            Optional limit on the number of keys returned. If less than this\
            number of keys are available, only the keys available will be added
        :type n_keys: int
        :return: A tuple of an array of keys and the number of keys added to\
            the array
        :rtype: tuple(array-like of int, int)
        """
        # Get the position of the zeros in the mask - assume 32-bits
        unwrapped_mask = numpy.unpackbits(
            numpy.asarray([self._mask], dtype=">u4").view(dtype="uint8"))
        zeros = numpy.where(unwrapped_mask == 0)[0]

        # If there are no zeros, there is only one key in the range, so
        # return that
        if len(zeros) == 0:
            if key_array is None:
                key_array = numpy.zeros(1, dtype=">u4")
            key_array[offset] = self._base_key
            return key_array, 1

        # We now know how many values there are - 2^len(zeros)
        max_n_keys = 2 ** len(zeros)
        if key_array is not None and len(key_array) < max_n_keys:
            max_n_keys = len(key_array)
        if n_keys is None or n_keys > max_n_keys:
            n_keys = max_n_keys
        if key_array is None:
            key_array = numpy.zeros(n_keys, dtype=">u4")

        # Create a list of 2^len(zeros) keys
        unwrapped_key = numpy.unpackbits(
            numpy.asarray([self._base_key], dtype=">u4").view(dtype="uint8"))

        # for each key, create its key with the idea of a neuron ID being
        # continuous and live at an offset position from the bottom of
        # the key
        for value in range(n_keys):
            key = numpy.copy(unwrapped_key)
            unwrapped_value = numpy.unpackbits(
                numpy.asarray([value], dtype=">u4")
                     .view(dtype="uint8"))[-len(zeros):]
            key[zeros] = unwrapped_value
            key_array[value + offset] = \
                numpy.packbits(key).view(dtype=">u4")[0].item()
        return key_array, n_keys
开发者ID:SpiNNakerManchester,项目名称:PACMAN,代码行数:55,代码来源:base_key_and_mask.py


示例14: test_pack_unpack_order

def test_pack_unpack_order():
    a = np.array([[2], [7], [23]], dtype=np.uint8)
    b = np.unpackbits(a, axis=1)
    assert_equal(b.dtype, np.uint8)
    b_little = np.unpackbits(a, axis=1, bitorder='little')
    b_big = np.unpackbits(a, axis=1, bitorder='big')
    assert_array_equal(b, b_big)
    assert_array_equal(a, np.packbits(b_little, axis=1, bitorder='little'))
    assert_array_equal(b[:,::-1], b_little)
    assert_array_equal(a, np.packbits(b_big, axis=1, bitorder='big'))
    assert_raises(ValueError, np.unpackbits, a, bitorder='r')
    assert_raises(TypeError, np.unpackbits, a, bitorder=10)
开发者ID:numpy,项目名称:numpy,代码行数:12,代码来源:test_packbits.py


示例15: makePGA2311AttenSig

def makePGA2311AttenSig(attenLvlRight,attenLvlLeft):
    numpts = 16*2 + 2   # one clock cycle is 2 steps and there are 16 data bits. Plus, an extra bit on either side to raise the CS line
    
    # CS load signal 
    loadSig = np.zeros(numpts, dtype=np.uint8)
    loadSig[0] = 1 
    loadSig[-1] = 1  

    # SCLK clock signal (low on first half, high on second half)    
    clkSig = np.zeros(numpts, dtype=np.uint8)
    bitTracker=np.zeros(numpts, dtype=np.uint8)     
    for n in range(0, 16):
        clkSig[n*2+2] = 1
        bitTracker[n*2+2] = n % 8
        
    # SDI Data signal
    dataSig =  np.zeros(numpts, dtype=np.uint8) 
    # first byte: right side
    Nright=255-(31.5+attenLvlRight)*2
    Nright=np.uint8(np.clip(Nright,0,255)) 
    dataR=np.unpackbits(Nright)
    for n in range(0, 8):
        dataSig[n*2+1]=dataR[n]
        dataSig[n*2+2]=dataR[n]
    
    # second byte: left side 
    Nleft=255-(31.5+attenLvlLeft)*2
    Nleft=np.uint8(np.clip(Nleft,0,255)) 
    dataL=np.unpackbits(Nleft)
    for n in range(0, 8):
        dataSig[n*2+16+1]=dataL[n]
        dataSig[n*2+16+2]=dataL[n]

#    print(loadSig)
#    print(clkSig)
#    print(dataSig)
#    print(bitTracker)
#    print('data',data)
      
    # combine the signals together and then form 8-bit numbers
    # bit 0=CS, 1=SDI, 2=SCLK    
    sig = np.zeros(numpts, dtype=np.uint8)
    combinedData=np.transpose(np.vstack((sig,sig,sig,sig,sig,clkSig,dataSig,loadSig)))
#    combinedData=np.transpose(np.vstack((clkSig,dataSig,loadSig)))    
    sig=np.packbits(combinedData,axis=1)
#    print(combinedData.shape, sig.shape)
#    print(combinedData)
#    print(sig)
        
    return sig
开发者ID:udayragakiran,项目名称:PyCMP,代码行数:50,代码来源:AudioHardware.py


示例16: to_bit_sequence

    def to_bit_sequence(self, event):
        """ Creates an array of bits containing the details in the event
        dictionary. This array is then upsampled and converted to float64 to be
        sent down an analog output. Once created, the array is cached to speed
        up future calls.

        Parameters
        ----------
        event: dict
            A dictionary describing the current component event. It should have
            3 keys: name, action, and metadata.

        Returns
        -------
        The array of bits expressed as analog values
        """

        key = (event["name"], event["action"], event["metadata"])
        # Check if the bit string is already stored
        if key in self.map_to_bit:
            return self.map_to_bit[key]

        trim = lambda ss, l: ss.ljust(l)[:l]
        # Set up int8 arrays where strings are converted to integers using ord
        name_array = np.array(map(ord, trim(event["name"], self.name_bytes)),
                              dtype=np.uint8)
        action_array = np.array(map(ord, trim(event["action"],
                                              self.action_bytes)),
                                dtype=np.uint8)

        # Add the metadata array if a value was passed
        if event["metadata"] is not None:
            metadata_array = np.array(map(ord, trim(event["metadata"],
                                                    self.metadata_bytes)),
                                      dtype=np.uint8)
        else:
            metadata_array = np.array([], dtype=np.uint8)

        sequence = ([True] +
                    np.unpackbits(name_array).astype(bool).tolist() +
                    np.unpackbits(action_array).astype(bool).tolist() +
                    np.unpackbits(metadata_array).astype(bool).tolist() +
                    [False])
        sequence = np.repeat(sequence, self.upsample_factor).astype("float64")
        sequence *= self.scaling

        self.map_to_bit[key] = sequence

        return sequence
开发者ID:siriuslee,项目名称:pyoperant,代码行数:49,代码来源:events.py


示例17: text2bits

 def text2bits(self, filename):
     # Given a text file, convert to bits
     with open(filename, 'r') as f:
         lines = f.read().split('\n')
     bit_array = np.array([], bool)
     for i, line in enumerate(lines):
         for ch in line:
             int_val = ord(ch)
             char_bits = np.unpackbits(np.array([int_val], dtype=np.uint8))
             bit_array = np.append(bit_array, char_bits) 
         if i != (len(lines) - 1):
             n_int_val = ord('\n')
             n_char_bits = np.unpackbits(np.array([n_int_val], dtype=np.uint8))
             bit_array = np.append(bit_array, n_char_bits)
     return bit_array            
开发者ID:diegoc1,项目名称:E40Project,代码行数:15,代码来源:source.py


示例18: _get_voc_color_map

def _get_voc_color_map(n=256):
    color_map = np.zeros((n, 3))
    for i in xrange(n):
        r = b = g = 0
        cid = i
        for j in xrange(0, 8):
            r = np.bitwise_or(r, np.left_shift(np.unpackbits(np.array([cid], dtype=np.uint8))[-1], 7-j))
            g = np.bitwise_or(g, np.left_shift(np.unpackbits(np.array([cid], dtype=np.uint8))[-2], 7-j))
            b = np.bitwise_or(b, np.left_shift(np.unpackbits(np.array([cid], dtype=np.uint8))[-3], 7-j))
            cid = np.right_shift(cid, 3)

        color_map[i][0] = r
        color_map[i][1] = g
        color_map[i][2] = b
    return color_map
开发者ID:1165048017,项目名称:MNC,代码行数:15,代码来源:vis_seg.py


示例19: unpackbits_axis

def unpackbits_axis(x, axis=-1, axissize=None):
    """Inverse of packbits_axis

    Parameters
    ----------
    x : ndarray
        record array of any shape, with multiple data of type uint8
    axissize : integer
        max size of expanded axis. Default is 8 * len(x.dtype)

    Returns
    -------
    X : ndarray
        array of shape x.shape[:axis] + (8 * d,) + x.shape[axis:]
        where d is the number of unsigned ints in each element of the
        record array.
    """
    assert all(x.dtype[i] == np.uint8 for i in range(len(x.dtype)))
    X = np.ndarray(x.shape + (len(x.dtype),), dtype=np.uint8, buffer=x)
    X = np.unpackbits(X, -1)

    if axissize is not None:
        slices = [slice(None) for i in range(X.ndim)]
        slices[-1] = slice(0, axissize)
        X = X[slices]

    return np.rollaxis(X, -1, axis)
开发者ID:tonygrey,项目名称:klsh,代码行数:27,代码来源:utils.py


示例20: _unpack_glyph

 def _unpack_glyph(
         face, code_height, code_width, req_height, req_width,
         force_double, force_single, carry_col_9, carry_row_9
     ):
     """Convert byte list to glyph pixels, numpy implementation."""
     glyph = numpy.unpackbits(face, axis=0).reshape((code_height, code_width)).astype(bool)
     # repeat last rows (e.g. for 9-bit high chars)
     if req_height > glyph.shape[0]:
         if carry_row_9:
             repeat_row = glyph[-1]
         else:
             repeat_row = numpy.zeros((1, code_width), dtype=numpy.uint8)
         while req_height > glyph.shape[0]:
             glyph = numpy.vstack((glyph, repeat_row))
     if force_double:
         glyph = glyph.repeat(2, axis=1)
     elif force_single:
         glyph = glyph[:, ::2]
     # repeat last cols (e.g. for 9-bit wide chars)
     if req_width > glyph.shape[1]:
         if carry_col_9:
             repeat_col = numpy.atleast_2d(glyph[:,-1]).T
         else:
             repeat_col = numpy.zeros((code_height, 1), dtype=numpy.uint8)
         while req_width > glyph.shape[1]:
             glyph = numpy.hstack((glyph, repeat_col))
     return glyph
开发者ID:robhagemans,项目名称:pcbasic,代码行数:27,代码来源:font.py



注:本文中的numpy.unpackbits函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python numpy.unravel_index函数代码示例发布时间:2022-05-27
下一篇:
Python numpy.unique1d函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap