Python numpy.ubyte() Examples

The following are 30 code examples of numpy.ubyte(). 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: GXNumpy.py    From gxpy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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"); 
Example #2
Source File: colormap.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: test_functions.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: GLViewWidget.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: test_functions.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: GradientEditorItem.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: views.py    From dm_control with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: colormap.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: GLViewWidget.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #10
Source File: GradientEditorItem.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
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 
Example #11
Source File: histograms.py    From coffeegrindsize 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 #12
Source File: GradientEditorItem.py    From soapy with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #13
Source File: colormap.py    From soapy with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #14
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 #15
Source File: test_functions.py    From soapy with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #16
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 #17
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 #18
Source File: qtGraph.py    From simulator with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #19
Source File: GLViewWidget.py    From soapy with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #20
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 #21
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 #22
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 #23
Source File: __init__.py    From h2o4gpu with Apache License 2.0 5 votes vote down vote up
def readTextFile(dataset_filename):
    data_list = []
    with open(dataset_filename, 'r') as f:
        lines = f.readlines()
        for line in lines:
            data_list.append(tuple([float(x) for x in line.split(',')[:-1]]))
    return np.array(data_list, dtype=np.ubyte).flatten() 
Example #24
Source File: functions.py    From soapy with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #25
Source File: buffer.py    From phy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _update(self):
        """ Upload all pending data to GPU. """

        if self.pending_data:
            start, stop = self.pending_data
            offset, nbytes = start, stop - start
            # offset, nbytes = self.pending_data
            data = self.ravel().view(np.ubyte)[offset:offset + nbytes]
            gl.glBufferSubData(self.target, offset, nbytes, data)
        self._pending_data = None
        self._need_update = False 
Example #26
Source File: display.py    From OpenNFB with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, **config):
        self.img = pg.ImageItem()
        self.plot_widget = pg.PlotWidget(title=name)
        self.plot_widget.block = self

        self.plot_widget.addItem(self.img)

        #self.img_array = np.zeros((1000, self.CHUNKSZ/2+1))
        self.img_array = np.zeros((1000, 48))

        # bipolar colormap
        pos = np.array([0., 1., 0.5, 0.25, 0.75])
        color = np.array([[0,255,255,255], [255,255,0,255], [0,0,0,255], (0, 0, 255, 255), (255, 0, 0, 255)], dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        lut = cmap.getLookupTable(0.0, 1.0, 256)

        self.img.setLookupTable(lut)
        self.img.setLevels([-2,7])

        FS = 48 * 2

        freq = np.arange((self.CHUNKSZ/2)+1)/(float(self.CHUNKSZ)/FS)
        yscale = 1.0/(self.img_array.shape[1]/freq[-1])
        self.img.scale((1./FS)*self.CHUNKSZ, yscale)

        self.plot_widget.setLabel('left', 'Frequency', units='Hz')

        self.win = np.hanning(self.CHUNKSZ)
        #self.show()
        super(Spectrograph, self).__init__(**config) 
Example #27
Source File: GradientEditorItem.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def colorMap(self):
        """Return a ColorMap object representing the current state of the editor."""
        if self.colorMode == 'hsv':
            raise NotImplementedError('hsv colormaps not yet supported')
        pos = []
        color = []
        for t,x in self.listTicks():
            pos.append(x)
            c = t.color
            color.append([c.red(), c.green(), c.blue(), c.alpha()])
        return ColorMap(np.array(pos), np.array(color, dtype=np.ubyte)) 
Example #28
Source File: SpectrogramWidget.py    From OpenNFB with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, blockSize = 1024, samplingFreq = 250):
        super(SpectrogramWidget, self).__init__()

        self.blockSize = blockSize

        self.img = pg.ImageItem()
        self.addItem(self.img)

        self.img_array = np.zeros((100, (blockSize/2)+1))

        # bipolar colormap
        pos = np.array([0., 1., 0.5, 0.25, 0.75])
        color = np.array([[0,255,255,255], [255,255,0,255], [0,0,0,255], (0, 0, 255, 255), (255, 0, 0, 255)], dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        lut = cmap.getLookupTable(0.0, 1.0, 256)

        self.img.setLookupTable(lut)
        self.img.setLevels([-50,40])

        freq = np.arange((blockSize/2)+1)/(float(blockSize)/samplingFreq)
        yscale = 1.0/(self.img_array.shape[1]/freq[-1])
        self.img.scale((1./samplingFreq)*blockSize, yscale)

        self.setLabel('left', 'Frequency', units='Hz')

        self.win = np.hanning(blockSize)
        self.show()

        self.buffer = np.zeros(blockSize) 
Example #29
Source File: streetlearn_engine_test.py    From streetlearn with Apache License 2.0 5 votes vote down vote up
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)) 
Example #30
Source File: alignface.py    From deepfeatinterp with GNU General Public License v3.0 5 votes vote down vote up
def detect_landmarks(ipath,detector,predictor,upsample=0,image=None):
  if image is None:
    original255=skimage.io.imread(ipath).astype(numpy.ubyte)
    original=original255/255.0
  else:
    original=image
    original255=(original.clip(0,1)*255).round().astype(numpy.ubyte)
  dets=detector(original255,upsample)
  if len(dets)!=1: raise FitError('{}: detected zero or more than one face.'.format(ipath))

  for k,d in enumerate(dets):
    shape=predictor(original255,d)
    X=numpy.array([[shape.part(i).y,shape.part(i).x] for i in range(68)]).astype(numpy.float64)
  return X,original