當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.uint方法代碼示例

本文整理匯總了Python中numpy.uint方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.uint方法的具體用法?Python numpy.uint怎麽用?Python numpy.uint使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.uint方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_scaling_in_abstract

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def test_scaling_in_abstract():
    # Confirm that, for all ints and uints as input, and all possible outputs,
    # for any simple way of doing the calculation, the result is near enough
    for category0, category1 in (('int', 'int'),
                                 ('uint', 'int'),
                                ):
        for in_type in np.sctypes[category0]:
            for out_type in np.sctypes[category1]:
                check_int_a2f(in_type, out_type)
    # Converting floats to integer
    for category0, category1 in (('float', 'int'),
                                 ('float', 'uint'),
                                 ('complex', 'int'),
                                 ('complex', 'uint'),
                                ):
        for in_type in np.sctypes[category0]:
            for out_type in np.sctypes[category1]:
                check_int_a2f(in_type, out_type) 
開發者ID:ME-ICA,項目名稱:me-ica,代碼行數:20,代碼來源:test_scaling.py

示例2: _unsigned_subtract

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:histograms.py

示例3: itemsAt

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def itemsAt(self, region=None):
        """
        Return a list of the items displayed in the region (x, y, w, h)
        relative to the widget.        
        """
        region = (region[0], self.height()-(region[1]+region[3]), region[2], region[3])
        
        #buf = np.zeros(100000, dtype=np.uint)
        buf = glSelectBuffer(100000)
        try:
            glRenderMode(GL_SELECT)
            glInitNames()
            glPushName(0)
            self._itemNames = {}
            self.paintGL(region=region, useItemNames=True)
            
        finally:
            hits = glRenderMode(GL_RENDER)
            
        items = [(h.near, h.names[0]) for h in hits]
        items.sort(key=lambda i: i[0])
        return [self._itemNames[i[1]] for i in items] 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:24,代碼來源:GLViewWidget.py

示例4: _unsigned_subtract

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:  # pragma: no cover
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
開發者ID:mars-project,項目名稱:mars,代碼行數:26,代碼來源:histogram.py

示例5: savetxt

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def savetxt(filename, ndarray):
    dir = os.path.dirname(filename)

    if not os.path.exists(dir):
        os.makedirs(dir)

    if not os.path.isfile(filename):
        with open(filename, 'w') as f:
            labels = list(map(' '.join, np.eye(10, dtype=np.uint).astype(str)))
            for row in ndarray:
                row_str = row.astype(str)
                label_str = labels[row[-1]]
                feature_str = ' '.join(row_str[:-1])
                f.write('|labels {} |features {}\n'.format(label_str, feature_str))
    else:
        print("File already exists", filename) 
開發者ID:NervanaSystems,項目名稱:ngraph-python,代碼行數:18,代碼來源:mnist_training.py

示例6: save_as_txt

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def save_as_txt(filename, ndarray):
    dir = os.path.dirname(filename)

    if not os.path.exists(dir):
        os.makedirs(dir)

    if not os.path.isfile(filename):
        print("Saving to ", filename, end=" ")
        with open(filename, 'w') as f:
            labels = list(map(' '.join, np.eye(10, dtype=np.uint).astype(str)))
            for row in ndarray:
                row_str = row.astype(str)
                label_str = labels[row[-1]]
                feature_str = ' '.join(row_str[:-1])
                f.write('|labels {} |features {}\n'.format(label_str, feature_str))
    else:
        print("File already exists", filename) 
開發者ID:MattChanTK,項目名稱:ai-gym,代碼行數:19,代碼來源:mnist_softmax_cntk.py

示例7: __call__

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def __call__(self, shape, seed, offset=None):
       fraction_low_freqs, acceleration = self.choose_acceleration(seed)
       num_cols = shape[-2]
       num_low_freqs = int(round(num_cols * fraction_low_freqs))

       # Create the mask
       mask = np.zeros(num_cols, dtype=np.float32)
       pad = (num_cols - num_low_freqs + 1) // 2
       mask[pad:pad + num_low_freqs] = True

       # Determine acceleration rate by adjusting for the number of low frequencies
       adjusted_accel = (acceleration * (num_low_freqs - num_cols)) / (num_low_freqs * acceleration - num_cols)
       if offset == None:
           offset = random.randrange(round(adjusted_accel))

       accel_samples = np.arange(offset, num_cols - 1, adjusted_accel)
       accel_samples = np.around(accel_samples).astype(np.uint)
       mask[accel_samples] = True

       # Reshape the mask
       mask_shape = [1 for _ in shape]
       mask_shape[-2] = num_cols
       mask = torch.from_numpy(mask.reshape(*mask_shape).astype(np.float32))

       return mask, num_low_freqs 
開發者ID:facebookresearch,項目名稱:fastMRI,代碼行數:27,代碼來源:subsample.py

示例8: brute_sort_objects_no_hash

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def brute_sort_objects_no_hash(data) -> Tuple[numpy.ndarray, numpy.ndarray]:
    unique = []
    inverse = numpy.zeros(dtype=numpy.uint, shape=len(data))
    for i, d in enumerate(data):
        try:
            index = unique.index(d)
        except ValueError:
            index = len(unique)
            unique.append(d)
        inverse[i] = index

    unique_ = numpy.empty(len(unique), dtype=object)
    for index, obj in enumerate(unique):
        unique_[index] = obj

    return unique_, numpy.array(inverse) 
開發者ID:Amulet-Team,項目名稱:Amulet-Core,代碼行數:18,代碼來源:numpy_helpers.py

示例9: test_save_gids

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def test_save_gids(thalamocortical):
    if os.path.exists('tmp/gid_table.h5'):
        os.remove('tmp/gid_table.h5')

    assert(thalamocortical.nodes.has_gids == False)
    thalamocortical.nodes.generate_gids(file_name='tmp/gid_table.h5')
    assert(os.path.exists('tmp/gid_table.h5'))

    gid_h5 = h5py.File('tmp/gid_table.h5', mode='r')
    assert('gid' in gid_h5)
    assert(len(gid_h5['gid']) == 9449)
    assert(np.issubdtype(gid_h5['gid'].dtype, np.uint))

    assert('node_id' in gid_h5)
    assert(len(gid_h5['node_id']) == 9449)
    assert(np.issubdtype(gid_h5['node_id'].dtype, np.uint))

    assert('population' in gid_h5)
    assert(len(gid_h5['population']) == 9449)

    print(gid_h5['population'])

    assert(np.issubdtype(gid_h5['population'].dtype, np.integer))
    assert(set(np.unique(gid_h5['population'][...])) == set([0, 1]))
    assert(set(np.unique(gid_h5['population_names'][...])) == set(['v1', 'lgn'])) 
開發者ID:AllenInstitute,項目名稱:sonata,代碼行數:27,代碼來源:test_root.py

示例10: test_pdist_dtype_equivalence

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def test_pdist_dtype_equivalence(self):
        # Tests that the result is not affected by type up-casting
        eps = 1e-07
        tests = [(eo['random-bool-data'], self.valid_upcasts['bool']),
                 (eo['random-uint-data'], self.valid_upcasts['uint']),
                 (eo['random-int-data'], self.valid_upcasts['int']),
                 (eo['random-float32-data'], self.valid_upcasts['float32'])]
        for metric in _METRICS_NAMES:
            for test in tests:
                X1 = test[0][::5, ::2]
                try:
                    y1 = pdist(X1, metric=metric)
                except Exception as e:
                    e_cls = e.__class__
                    if verbose > 2:
                        print(e_cls.__name__)
                        print(e)
                    for new_type in test[1]:
                        X2 = new_type(X1)
                        assert_raises(e_cls, pdist, X2, metric=metric)
                else:
                    for new_type in test[1]:
                        y2 = pdist(new_type(X1), metric=metric)
                        _assert_within_tol(y1, y2, eps, verbose > 2) 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:26,代碼來源:test_distance.py

示例11: testNumpyConversion

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def testNumpyConversion(self):
    self.assertIs(tf.float32, tf.as_dtype(np.float32))
    self.assertIs(tf.float64, tf.as_dtype(np.float64))
    self.assertIs(tf.int32, tf.as_dtype(np.int32))
    self.assertIs(tf.int64, tf.as_dtype(np.int64))
    self.assertIs(tf.uint8, tf.as_dtype(np.uint8))
    self.assertIs(tf.uint16, tf.as_dtype(np.uint16))
    self.assertIs(tf.int16, tf.as_dtype(np.int16))
    self.assertIs(tf.int8, tf.as_dtype(np.int8))
    self.assertIs(tf.complex64, tf.as_dtype(np.complex64))
    self.assertIs(tf.complex128, tf.as_dtype(np.complex128))
    self.assertIs(tf.string, tf.as_dtype(np.object))
    self.assertIs(tf.string, tf.as_dtype(np.array(["foo", "bar"]).dtype))
    self.assertIs(tf.bool, tf.as_dtype(np.bool))
    with self.assertRaises(TypeError):
      tf.as_dtype(np.dtype([("f1", np.uint), ("f2", np.int32)])) 
開發者ID:tobegit3hub,項目名稱:deep_image_model,代碼行數:18,代碼來源:dtypes_test.py

示例12: to_spmatrix

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def to_spmatrix(self):
        r"""
        Convert Pauli to a sparse matrix representation (CSR format).

        Order is q_{n-1} .... q_0, i.e., $P_{n-1} \otimes ... P_0$

        Returns:
            scipy.sparse.csr_matrix: a sparse matrix with CSR format that
            represents the pauli.
        """
        _x, _z = self._x, self._z
        n = 2**len(_x)
        twos_array = 1 << np.arange(len(_x))
        xs = np.array(_x).dot(twos_array)
        zs = np.array(_z).dot(twos_array)
        rows = np.arange(n+1, dtype=np.uint)
        columns = rows ^ xs
        global_factor = (-1j)**np.dot(np.array(_x, dtype=np.uint), _z)
        data = global_factor*(-1)**np.mod(_count_set_bits(zs & rows), 2)
        return sparse.csr_matrix((data, columns, rows), shape=(n, n)) 
開發者ID:Qiskit,項目名稱:qiskit-terra,代碼行數:22,代碼來源:pauli.py

示例13: rotate_image_with_invrmat

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def rotate_image_with_invrmat(cvmat, rotateAngle):

    assert (cvmat.dtype == np.uint8) , " only support normalize np.uint  in rotate_image_with_invrmat'"

    ##Make sure cvmat is square?
    height, width, channel = cvmat.shape

    center = ( width//2, height//2)
    rotateMatrix = cv2.getRotationMatrix2D(center, rotateAngle, 1.0)

    cos, sin = np.abs(rotateMatrix[0,0]), np.abs(rotateMatrix[0, 1])
    newH = int((height*sin)+(width*cos))
    newW = int((height*cos)+(width*sin))

    rotateMatrix[0,2] += (newW/2) - center[0] #x
    rotateMatrix[1,2] += (newH/2) - center[1] #y

    # rotate image
    outMat = cv2.warpAffine(cvmat, rotateMatrix, (newH, newW), borderValue=(128, 128, 128))

    # generate inv rotate matrix
    invRotateMatrix = cv2.invertAffineTransform(rotateMatrix)

    return (outMat, invRotateMatrix, (width, height)) 
開發者ID:yuanyuanli85,項目名稱:FashionAI_KeyPoint_Detection_Challenge_Keras,代碼行數:26,代碼來源:data_process.py

示例14: filter_contours_area_of_image

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def filter_contours_area_of_image(self, image, contours, hierarchy, max_area, min_area):
        found_polygons_early = list()

        jv = 0
        for c in contours:
            if len(c) < 3:  # A polygon cannot have less than 3 points
                continue

            polygon = geometry.Polygon([point[0] for point in c])
            area = polygon.area
            if area >= min_area * np.prod(image.shape[:2]) and area <= max_area * np.prod(
                    image.shape[:2]) and hierarchy[0][jv][3] == -1 :  # and hierarchy[0][jv][3]==-1 :
                found_polygons_early.append(
                    np.array([ [point] for point in polygon.exterior.coords], dtype=np.uint))
            jv += 1
        return found_polygons_early 
開發者ID:qurator-spk,項目名稱:sbb_textline_detection,代碼行數:18,代碼來源:main.py

示例15: filter_contours_area_of_image_interiors

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import uint [as 別名]
def filter_contours_area_of_image_interiors(self, image, contours, hierarchy, max_area, min_area):
        found_polygons_early = list()

        jv = 0
        for c in contours:
            if len(c) < 3:  # A polygon cannot have less than 3 points
                continue

            polygon = geometry.Polygon([point[0] for point in c])
            area = polygon.area
            if area >= min_area * np.prod(image.shape[:2]) and area <= max_area * np.prod(image.shape[:2]) and \
                    hierarchy[0][jv][3] != -1:
                # print(c[0][0][1])
                found_polygons_early.append(
                    np.array([point for point in polygon.exterior.coords], dtype=np.uint))
            jv += 1
        return found_polygons_early 
開發者ID:qurator-spk,項目名稱:sbb_textline_detection,代碼行數:19,代碼來源:main.py


注:本文中的numpy.uint方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。