当前位置: 首页>>代码示例>>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;未经允许,请勿转载。