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


Python numpy.ubyte方法代碼示例

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


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

示例1: _unsigned_subtract

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [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

示例2: readQImage

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def readQImage(self):
        """
        Read the current buffer pixels out as a QImage.
        """
        w = self.width()
        h = self.height()
        self.repaint()
        pixels = np.empty((h, w, 4), dtype=np.ubyte)
        pixels[:] = 128
        pixels[...,0] = 50
        pixels[...,3] = 255
        
        glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels)
        
        # swap B,R channels for Qt
        tmp = pixels[...,0].copy()
        pixels[...,0] = pixels[...,2]
        pixels[...,2] = tmp
        pixels = pixels[::-1] # flip vertical
        
        img = fn.makeQImage(pixels, transpose=False)
        return img 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:24,代碼來源:GLViewWidget.py

示例3: test_rescaleData

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def test_rescaleData():
    dtypes = map(np.dtype, ('ubyte', 'uint16', 'byte', 'int16', 'int', 'float'))
    for dtype1 in dtypes:
        for dtype2 in dtypes:
            data = (np.random.random(size=10) * 2**32 - 2**31).astype(dtype1)
            for scale, offset in [(10, 0), (10., 0.), (1, -50), (0.2, 0.5), (0.001, 0)]:
                if dtype2.kind in 'iu':
                    lim = np.iinfo(dtype2)
                    lim = lim.min, lim.max
                else:
                    lim = (-np.inf, np.inf)
                s1 = np.clip(float(scale) * (data-float(offset)), *lim).astype(dtype2)
                s2 = pg.rescaleData(data, scale, offset, dtype2)
                assert s1.dtype == s2.dtype
                if dtype2.kind in 'iu':
                    assert np.all(s1 == s2)
                else:
                    assert np.allclose(s1, s2) 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:20,代碼來源:test_functions.py

示例4: getColors

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def getColors(self, mode=None):
        """Return list of all color stops converted to the specified mode.
        If mode is None, then no conversion is done."""
        if isinstance(mode, basestring):
            mode = self.enumMap[mode.lower()]
        
        color = self.color
        if mode in [self.BYTE, self.QCOLOR] and color.dtype.kind == 'f':
            color = (color * 255).astype(np.ubyte)
        elif mode == self.FLOAT and color.dtype.kind != 'f':
            color = color.astype(float) / 255.
            
        if mode == self.QCOLOR:
            color = [QtGui.QColor(*x) for x in color]
            
        return color 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:18,代碼來源:colormap.py

示例5: getLookupTable

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def getLookupTable(self, nPts, alpha=None):
        """
        Return an RGB(A) lookup table (ndarray). 
        
        ==============  ============================================================================
        **Arguments:**
        nPts            The number of points in the returned lookup table.
        alpha           True, False, or None - Specifies whether or not alpha values are included
                        in the table.If alpha is None, alpha will be automatically determined.
        ==============  ============================================================================
        """
        if alpha is None:
            alpha = self.usesAlpha()
        if alpha:
            table = np.empty((nPts,4), dtype=np.ubyte)
        else:
            table = np.empty((nPts,3), dtype=np.ubyte)
            
        for i in range(nPts):
            x = float(i)/(nPts-1)
            color = self.getColor(x, toQColor=False)
            table[i] = color[:table.shape[1]]
            
        return table 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:26,代碼來源:GradientEditorItem.py

示例6: _unsigned_subtract

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [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

示例7: remove_node

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def remove_node(self, name):
        if name not in self.texts:
            print("Such node not exist")
            return
        n = self.texts.index(name)
        self.edges = [[0, 0]] + [edge for edge in self.edges[1:] if edge[0] != n and edge[1] != n]
        for edge in self.edges:
            if edge[0] > n:
                edge[0] -= 1
            if edge[1] > n:
                edge[1] -= 1
        del self.nodeColors[n]
        del self.texts[n]
        self.V -= 1
        if self.V > 0:
            self.pos = self.getNodePosn(self.V)   # Get position for V-1 nodes
            self.setData(pos=np.array(self.pos, dtype=float),
                         adj=np.array(self.edges, dtype=int), size=0.1, pxMode=False, text=self.texts,
                         symbolBrush=np.array(self.nodeColors,
                                              dtype=[('red', np.ubyte), ('green', np.ubyte),
                                                     ('blue', np.ubyte), ('alpha', np.ubyte)]))
            print("{} removed ".format(name)) 
開發者ID:P2PSP,項目名稱:simulator,代碼行數:24,代碼來源:qtGraph.py

示例8: make_pil_image

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def make_pil_image(*args, **kwargs):
    '''Creates a PIL Image object.

    USAGE: make_pil_image(source [, bands] [stretch=True] [stretch_all=False],
                          [bounds = (lower, upper)] )

    See `get_rgb` for description of arguments.
    '''
    try:
        from PIL import Image, ImageDraw
    except ImportError:
        import Image
        import ImageDraw

    rgb = get_rgb(*args, **kwargs)
    rgb = (rgb * 255).astype(np.ubyte)
    img = Image.fromarray(rgb)
    return img 
開發者ID:spectralpython,項目名稱:spectral,代碼行數:20,代碼來源:graphics.py

示例9: gs_from_np

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def gs_from_np(dtype):
    dtype = np.dtype(dtype)
    if dtype == np.byte:
        return gxa.GS_BYTE
    elif dtype == np.ubyte:
        return gxa.GS_UBYTE
    elif dtype == np.int16:
        return gxa.GS_SHORT
    elif dtype == np.uint16:
        return gxa.GS_USHORT
    elif dtype == np.int32:
        return gxa.GS_LONG
    elif dtype == np.uint32:
        return gxa.GS_ULONG
    elif dtype == np.int64:
        return gxa.GS_LONG64
    elif dtype == np.uint64:
        return gxa.GS_ULONG64
    elif dtype == np.float32:
        return gxa.GS_FLOAT
    elif dtype == np.float64:
        return gxa.GS_DOUBLE
    else:
        raise gxa.GXAPIError("Numpy array type does not map to one of the supported GS_TYPES"); 
開發者ID:GeosoftInc,項目名稱:gxpy,代碼行數:26,代碼來源:GXNumpy.py

示例10: render

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def render(self, context, viewport):
    """Renders the overlay on screen.

    Args:
      context: MjrContext instance.
      viewport: MJRRECT instance.
    """
    width_adjustment = viewport.width % 4
    rect_shape = (viewport.width - width_adjustment, viewport.height)

    if self._depth_buffer is None or self._depth_buffer.shape != rect_shape:
      self._depth_buffer = np.empty(
          (viewport.width, viewport.height), np.float32)

    mjlib.mjr_readPixels(
        None, self._depth_buffer, viewport.mujoco_rect, context.ptr)

    # Subsample by 4, convert to RGB, and cast to unsigned bytes.
    depth_rgb = np.repeat(self._depth_buffer[::4, ::4, None] * 255, 3,
                          -1).astype(np.ubyte)

    pos = types.MJRRECT(
        int(3 * viewport.width / 4) + width_adjustment, 0,
        int(viewport.width / 4), int(viewport.height / 4))
    mjlib.mjr_drawPixels(depth_rgb, None, pos, context.ptr) 
開發者ID:deepmind,項目名稱:dm_control,代碼行數:27,代碼來源:views.py

示例11: test_observation

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def test_observation(self):
    engine = streetlearn_engine.StreetLearnEngine.Create(
        self.dataset_path, TestDataset.kImageWidth, TestDataset.kImageHeight)
    engine.InitEpisode(0, 0)
    engine.BuildGraphWithRoot('1')

    # Check that obervations have the right values.
    buffer_size = 3 * TestDataset.kImageWidth * TestDataset.kImageHeight
    obs = np.zeros(buffer_size, dtype=np.ubyte)
    engine.RenderObservation(obs)
    for i in range(0, TestDataset.kImageHeight):
      for j in range(0, TestDataset.kImageWidth):
        index = i * TestDataset.kImageWidth + j
        self.assertIn(obs[index], range(0, 232)) 
開發者ID:deepmind,項目名稱:streetlearn,代碼行數:16,代碼來源:streetlearn_engine_test.py

示例12: imageToArray

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def imageToArray(img, copy=False, transpose=True):
    """
    Convert a QImage into numpy array. The image must have format RGB32, ARGB32, or ARGB32_Premultiplied.
    By default, the image is not copied; changes made to the array will appear in the QImage as well (beware: if 
    the QImage is collected before the array, there may be trouble).
    The array will have shape (width, height, (b,g,r,a)).
    """
    fmt = img.format()
    ptr = img.bits()
    if USE_PYSIDE:
        arr = np.frombuffer(ptr, dtype=np.ubyte)
    else:
        ptr.setsize(img.byteCount())
        arr = np.asarray(ptr)
        if img.byteCount() != arr.size * arr.itemsize:
            # Required for Python 2.6, PyQt 4.10
            # If this works on all platforms, then there is no need to use np.asarray..
            arr = np.frombuffer(ptr, np.ubyte, img.byteCount())
    
    arr = arr.reshape(img.height(), img.width(), 4)
    if fmt == img.Format_RGB32:
        arr[...,3] = 255
    
    if copy:
        arr = arr.copy()
        
    if transpose:
        return arr.transpose((1,0,2))
    else:
        return arr 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:32,代碼來源:functions.py

示例13: saveFailedTest

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def saveFailedTest(data, expect, filename):
    """Upload failed test images to web server to allow CI test debugging.
    """
    commit = runSubprocess(['git', 'rev-parse',  'HEAD'])
    name = filename.split('/')
    name.insert(-1, commit.strip())
    filename = '/'.join(name)
    host = 'data.pyqtgraph.org'

    # concatenate data, expect, and diff into a single image
    ds = data.shape
    es = expect.shape

    shape = (max(ds[0], es[0]) + 4, ds[1] + es[1] + 8 + max(ds[1], es[1]), 4)
    img = np.empty(shape, dtype=np.ubyte)
    img[..., :3] = 100
    img[..., 3] = 255

    img[2:2+ds[0], 2:2+ds[1], :ds[2]] = data
    img[2:2+es[0], ds[1]+4:ds[1]+4+es[1], :es[2]] = expect

    diff = makeDiffImage(data, expect)
    img[2:2+diff.shape[0], -diff.shape[1]-2:-2] = diff

    png = makePng(img)
    
    conn = httplib.HTTPConnection(host)
    req = urllib.urlencode({'name': filename,
                            'data': base64.b64encode(png)})
    conn.request('POST', '/upload.py', req)
    response = conn.getresponse().read()
    conn.close()
    print("\nImage comparison failed. Test result: %s %s   Expected result: "
          "%s %s" % (data.shape, data.dtype, expect.shape, expect.dtype))
    print("Uploaded to: \nhttp://%s/data/%s" % (host, filename))
    if not response.startswith(b'OK'):
        print("WARNING: Error uploading data to %s" % host)
        print(response) 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:40,代碼來源:image_testing.py

示例14: makeDiffImage

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def makeDiffImage(im1, im2):
    """Return image array showing the differences between im1 and im2.

    Handles images of different shape. Alpha channels are not compared.
    """
    ds = im1.shape
    es = im2.shape

    diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
    diff[..., :3] = 128
    diff[..., 3] = 255
    diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
    diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
    diff = np.clip(diff, 0, 255).astype(np.ubyte)
    return diff 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:17,代碼來源:image_testing.py

示例15: test

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ubyte [as 別名]
def test(self, im1, im2, message):
        """Ask the user to decide whether an image test passes or fails.
        
        This method displays the test image, reference image, and the difference
        between the two. It then blocks until the user selects the test output
        by clicking a pass/fail button or typing p/f. If the user fails the test,
        then an exception is raised.
        """
        self.show()
        if im2 is None:
            message += '\nImage1: %s %s   Image2: [no standard]' % (im1.shape, im1.dtype)
            im2 = np.zeros((1, 1, 3), dtype=np.ubyte)
        else:
            message += '\nImage1: %s %s   Image2: %s %s' % (im1.shape, im1.dtype, im2.shape, im2.dtype)
        self.label.setText(message)
        
        self.views[0].image.setImage(im1)
        self.views[1].image.setImage(im2)
        diff = makeDiffImage(im1, im2)

        self.views[2].image.setImage(diff)
        self.views[0].autoRange()

        while True:
            QtGui.QApplication.processEvents()
            lastKey = self.lastKey
            
            self.lastKey = None
            if lastKey in ('f', 'esc') or not self.isVisible():
                raise Exception("User rejected test result.")
            elif lastKey == 'p':
                break
            time.sleep(0.03)

        for v in self.views:
            v.image.setImage(np.zeros((1, 1, 3), dtype=np.ubyte)) 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:38,代碼來源:image_testing.py


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