Python numpy.uint() Examples

The following are 30 code examples of numpy.uint(). 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: subsample.py    From fastMRI with MIT License 6 votes vote down vote up
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 
Example #2
Source File: main.py    From sbb_textline_detection with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: main.py    From sbb_textline_detection with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: conv_sup_cc_4ch.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #5
Source File: conv_sup_cc_mllsll.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #6
Source File: histogram.py    From mars with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: conv_sup_cc_lbp.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #8
Source File: conv_sup_cc.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #9
Source File: conv_sup_cc_4ch_rot.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #10
Source File: conv_sup_cc_lbp.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #11
Source File: conv_sup_cc.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #12
Source File: conv_sup_cc_mllsll.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #13
Source File: test_scaling.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
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) 
Example #14
Source File: conv_sup_cc_lbp.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hit_mis(classn, Pr, Tr):
    print("Hit matrix:");
    hit = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 1:
                hit[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in hit);

    print("Mis matrix:");
    mis = np.zeros(shape=(classn, 2), dtype=np.uint);
    for i in range(Tr.shape[0]):
        for truth_ind in range(Tr.shape[1]):
            if Tr[i][truth_ind] == 0:
                mis[truth_ind, Pr[i][truth_ind]] += 1;
    print '\n'.join('\t'.join(str(cell) for cell in row) for row in mis); 
Example #15
Source File: GLViewWidget.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
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] 
Example #16
Source File: data_process.py    From FashionAI_KeyPoint_Detection_Challenge_Keras with MIT License 6 votes vote down vote up
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)) 
Example #17
Source File: histograms.py    From lambda-packs with MIT License 6 votes vote down vote up
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) 
Example #18
Source File: test_root.py    From sonata with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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'])) 
Example #19
Source File: histograms.py    From pySINDy with MIT License 6 votes vote down vote up
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) 
Example #20
Source File: mnist_training.py    From ngraph-python with Apache License 2.0 6 votes vote down vote up
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) 
Example #21
Source File: pauli.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
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)) 
Example #22
Source File: numpy_helpers.py    From Amulet-Core with MIT License 6 votes vote down vote up
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) 
Example #23
Source File: test_distance.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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) 
Example #24
Source File: mnist_softmax_cntk.py    From ai-gym with MIT License 6 votes vote down vote up
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) 
Example #25
Source File: histograms.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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) 
Example #26
Source File: histograms.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
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) 
Example #27
Source File: dtypes_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
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)])) 
Example #28
Source File: histograms.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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) 
Example #29
Source File: sputils.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def get_sum_dtype(dtype):
    """Mimic numpy's casting for np.sum"""
    if np.issubdtype(dtype, np.float_):
        return np.float_
    if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
        return np.uint
    if np.can_cast(dtype, np.int_):
        return np.int_
    return dtype 
Example #30
Source File: deskew.py    From lpr with Apache License 2.0 5 votes vote down vote up
def skew_detection(image_gray):
    h, w = image_gray.shape[:2]
    eigen = cv2.cornerEigenValsAndVecs(image_gray,12, 5)
    angle_sur = np.zeros(180,np.uint)
    eigen = eigen.reshape(h, w, 3, 2)
    flow = eigen[:,:,2]
    vis = image_gray.copy()
    vis[:] = (192 + np.uint32(vis)) / 2
    d = 12
    points =  np.dstack( np.mgrid[d/2:w:d, d/2:h:d] ).reshape(-1, 2)
    for x, y in points:
        vx, vy = np.int32(flow[int(y), int(x)]*d)
        # cv2.line(rgb, (x-vx, y-vy), (x+vx, y+vy), (0, 355, 0), 1, cv2.LINE_AA)
        ang = angle(vx,vy)
        angle_sur[(ang+180)%180] +=1

    # torr_bin = 30
    angle_sur = angle_sur.astype(np.float)
    angle_sur = (angle_sur-angle_sur.min())/(angle_sur.max()-angle_sur.min())
    angle_sur = filters.gaussian_filter1d(angle_sur,5)
    skew_v_val =  angle_sur[20:180-20].max()
    skew_v = angle_sur[30:180-30].argmax() + 30
    skew_h_A = angle_sur[0:30].max()
    skew_h_B = angle_sur[150:180].max()
    skew_h = 0
    if (skew_h_A > skew_v_val*0.3 or skew_h_B > skew_v_val*0.3):
        if skew_h_A>=skew_h_B:
            skew_h = angle_sur[0:20].argmax()
        else:
            skew_h = - angle_sur[160:180].argmax()
    return skew_h,skew_v