示例#1
0
def test_alphamodulated2qimage():
    if not _have_qt:
        return
    
    # create test data such that rounding does not depend on the least significant bit
    a = (numpy.random.randint(255, size=(100,200)).astype(numpy.float32)+0.25)/255.0-0.5
    a[0,0] =-0.5 #make sure we get the correct bounds
    a[0,1] = 0.5
    vigra.impex.writeImage(a.swapaxes(0,1), "tmp1.png")
    
    tintColor = numpy.asarray([0.0, 1.0, 0.0], dtype=numpy.float32)
    
    img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32_Premultiplied)
    n = numpy.asarray([-0.5, 0.5], dtype=numpy.float32)
    
    vigra.colors.alphamodulated2qimage_ARGB32Premultiplied(a, byte_view(img), tintColor, n)
    
    tmp1 = vigra.impex.readImage("tmp1.png").view(numpy.ndarray).squeeze().astype(numpy.uint8)
    tmp2 = byte_view(img)
    tmp2 = tmp2.swapaxes(0,1)
    
    assert_true( tmp1.shape[0:2] == tmp2.shape[0:2] )
    assert_true( tmp2.ndim == 3 )
    assert_true( tmp2.shape[2] == 4 )
    
    assert_true( (tmp2[:,:,0] == 0).all() )
    assert_true( (tmp2[:,:,2] == 0).all() )
    assert_true( (tmp2[:,:,3] == tmp1).all() )
    assert_true( (tmp2[:,:,1] == tmp1).all() )
示例#2
0
    def testEverythingDirtyPropagation( self ):
        self.lsm.append(self.layer2)        
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)
        try:
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == self.CONSTANT))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            NEW_CONSTANT = self.CONSTANT+1
            self.ds2.constant = NEW_CONSTANT
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == NEW_CONSTANT))
                self.assertTrue(np.all(aimg[:,:,3] == 255))
            
        finally:
            tp.notifyThreadsToStop()
            tp.joinThreads()
示例#3
0
    def testSetAllLayersInvisible( self ):
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.sims)

        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == self.GRAY3))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        self.layer1.visible = False
        self.layer2.visible = False
        self.layer3.visible = False
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            # If all tiles are invisible, then no tile is even rendered at all.
            assert tile.qimg is None

        self.layer1.visible = False
        self.layer2.visible = True
        self.layer2.opacity = 1.0
        self.layer3.visible = False
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == self.GRAY2))
            self.assertTrue(np.all(aimg[:,:,3] == 255))
示例#4
0
 def toImage( self ):
     t = time.time()
    
     tWAIT = time.time()
     self._arrayreq.wait()
     tWAIT = 1000.0*(time.time()-tWAIT)
     
     tAR = time.time()
     a = self._arrayreq.getResult()
     tAR = 1000.0*(time.time()-tAR)
     
     assert a.ndim == 2, "GrayscaleImageRequest.toImage(): result has shape %r, which is not 2-D" % (a.shape,)
    
     normalize = self._normalize 
     if not normalize:
         normalize = [0,255]
         
     # FIXME: It is obviously wrong to truncate like this (right?)
     if a.dtype == np.uint64 or a.dtype == np.int64:
         warnings.warn("Truncating 64-bit pixels for display")
         if a.dtype == np.uint64:
             a = a.astype( np.uint32 )
         elif a.dtype == np.int64:
             a = a.astype( np.int32 )
     
     #
     # new conversion
     #
     tImg = None
     if _has_vigra and hasattr(vigra.colors, 'gray2qimage_ARGB32Premultiplied'):
         if self._normalize is None or \
            self._normalize[0] >= self._normalize[1] or \
            self._normalize == [0, 0]: #FIXME: fix volumina conventions
             n = np.asarray([0, 255], dtype=a.dtype)
         else:
             n = np.asarray(self._normalize, dtype=a.dtype)
         tImg = time.time()
         img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32_Premultiplied)
         if not a.flags['C_CONTIGUOUS']:
             a = a.copy()
         vigra.colors.gray2qimage_ARGB32Premultiplied(a, byte_view(img), n)
         tImg = 1000.0*(time.time()-tImg)
     else:
         self.logger.warning("using slow image creation function")
         tImg = time.time()
         if self._normalize:
             #clipping has been implemented in this commit,
             #but it is not yet available in the packages obtained via easy_install
             #http://www.informatik.uni-hamburg.de/~meine/hg/qimage2ndarray/diff/fcddc70a6dea/qimage2ndarray/__init__.py
             a = np.clip(a, *self._normalize)
         img = gray2qimage(a, self._normalize)
         ret = img.convertToFormat(QImage.Format_ARGB32_Premultiplied)
         tImg = 1000.0*(time.time()-tImg)
     
     if self.logger.getEffectiveLevel() >= logging.DEBUG:
         tTOT = 1000.0*(time.time()-t)
         self.logger.debug("toImage (%dx%d, normalize=%r) took %f msec. (array req: %f, wait: %f, img: %f)" % (img.width(), img.height(), normalize, tTOT, tAR, tWAIT, tImg))
         
     return img
 def renderScene( self, s):
     img = QImage(310,290,QImage.Format_ARGB32_Premultiplied)
     p = QPainter(img)
     s.render(p)
     s.joinRendering()
     s.render(p)
     p.end()
     return byte_view(img)
def test_byte_view_rgb32():
    qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_RGB32)
    v = qimage2ndarray.byte_view(qimg)
    qimg.fill(23)
    qimg.setPixel(12, 10, 42)
    assert_equal(v.shape, (240, 320, 4))
    assert_equal(list(v[10,10]), [23, 0, 0, 0xff])
    assert_equal(list(v[10,12]), [42, 0, 0, 0xff])
    assert_equal(v.nbytes, numBytes(qimg))
def test_byte_view_indexed():
    qimg = QtGui.QImage(320, 240, QtGui.QImage.Format_Indexed8)
    setNumColors(qimg, 256)
    v = qimage2ndarray.byte_view(qimg)
    qimg.fill(23)
    qimg.setPixel(12, 10, 42)
    assert_equal(v.shape, (240, 320, 1))
    assert_equal(list(v[10,10]), [23])
    assert_equal(list(v[10,12]), [42])
    assert_equal(v.nbytes, numBytes(qimg))
 def renderScene( self, s, exportFilename=None):
     img = QImage(310,290,QImage.Format_ARGB32_Premultiplied)
     p = QPainter(img)
     s.render(p)
     s.joinRendering()
     s.render(p)
     p.end()
     if exportFilename is not None:
         img.save(exportFilename)
     return byte_view(img)
示例#9
0
        def check(result, codon):
            self.assertEqual(codon, "unique")
            self.assertTrue(type(result) == QImage)

            result_array = qimage2ndarray.byte_view(result)

            assert((result_array[:10, :, -1] == 255).all())
            assert((result_array[-10:, :, -1] == 255).all())
            assert((result_array[:, :10, -1] == 255).all())
            assert((result_array[:, -10:, -1] == 255).all())
示例#10
0
    def testRequest( self ):
        imr = self.ims.request(QRect(0,0,512,512))
        result = imr.wait()
        self.assertTrue(type(result) == QImage)

        result_array = qimage2ndarray.byte_view(result)

        assert((result_array[:10, :, -1] == 255).all())
        assert((result_array[-10:, :, -1] == 255).all())
        assert((result_array[:, :10, -1] == 255).all())
        assert((result_array[:, -10:, -1] == 255).all())
示例#11
0
    def testSetAllLayersInvisible( self ):
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.sims)
        try:
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == self.GRAY3))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            self.layer1.visible = False
            self.layer2.visible = False
            self.layer3.visible = False
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == 255)) # all white
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            self.layer1.visible = False
            self.layer2.visible = True
            self.layer2.opacity = 1.0
            self.layer3.visible = False
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == self.GRAY2))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

        finally:
            tp.notifyThreadsToStop()
            tp.joinThreads()
示例#12
0
    def toImage(self):
        t = time.time()

        tWAIT = time.time()
        self._arrayreq.wait()
        tWAIT = 1000.0 * (time.time() - tWAIT)

        tAR = time.time()
        a = self._arrayreq.getResult()
        tAR = 1000.0 * (time.time() - tAR)

        has_no_mask = not np.ma.is_masked(a)

        tImg = None
        if has_no_mask and _has_vigra and hasattr(vigra.colors, "gray2qimage_ARGB32Premultiplied"):
            if not a.flags.contiguous:
                a = a.copy()
            tImg = time.time()
            img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32_Premultiplied)
            tintColor = np.asarray(
                [self._tintColor.redF(), self._tintColor.greenF(), self._tintColor.blueF()], dtype=np.float32
            )
            normalize = np.asarray(self._normalize, dtype=np.float32)
            if normalize[0] > normalize[1]:
                normalize = np.array((0.0, 255.0)).astype(np.float32)
            vigra.colors.alphamodulated2qimage_ARGB32Premultiplied(a, byte_view(img), tintColor, normalize)
            tImg = 1000.0 * (time.time() - tImg)
        else:
            if has_no_mask:
                self.logger.warning("using unoptimized conversion functions")
            tImg = time.time()
            d = a[..., None].repeat(4, axis=-1)
            d[:, :, 0] = d[:, :, 0] * self._tintColor.redF()
            d[:, :, 1] = d[:, :, 1] * self._tintColor.greenF()
            d[:, :, 2] = d[:, :, 2] * self._tintColor.blueF()

            normalize = self._normalize
            img = array2qimage(d, normalize)
            img = img.convertToFormat(QImage.Format_ARGB32_Premultiplied)
            tImg = 1000.0 * (time.time() - tImg)

        if self.logger.isEnabledFor(logging.DEBUG):
            tTOT = 1000.0 * (time.time() - t)
            self.logger.debug(
                "toImage (%dx%d, normalize=%r) took %f msec. (array req: %f, wait: %f, img: %f)"
                % (img.width(), img.height(), normalize, tTOT, tAR, tWAIT, tImg)
            )

        return img
示例#13
0
    def testRequest( self ):
        imr = self.ims.request(QRect(0,0,512,512))
        result = imr.wait()
        self.assertTrue(type(result) == QImage)

        result_view = qimage2ndarray.byte_view(result)
        if sys.byteorder == "little":
            self.assertTrue((result_view[:1, :, 3] == 0).all())
            self.assertTrue((result_view[-1:, :, 3] == 0).all())
            self.assertTrue((result_view[:, :1, 3] == 0).all())
            self.assertTrue((result_view[:, -1:, 3] == 0).all())
        else:
            self.assertTrue((result_view[:1, :, 0] == 0).all())
            self.assertTrue((result_view[-1:, :, 0] == 0).all())
            self.assertTrue((result_view[:, :1, 0] == 0).all())
            self.assertTrue((result_view[:, -1:, 0] == 0).all())
示例#14
0
        def renderScene( self, s, exportFilename=None, joinRendering=True):
            img = QImage(30,30,QImage.Format_ARGB32_Premultiplied)
            img.fill(Qt.white)
            p = QPainter(img)

            s.render(p) #trigger a rendering of the whole scene
            if joinRendering:
                #wait for all the data to arrive
                s.joinRendering()
                #finally, render everything
                s.render(p)
            p.end()

            if exportFilename is not None:
                img.save(exportFilename)
            return byte_view(img)
示例#15
0
        def check(result, codon):
            self.assertEqual(codon, "unique")
            self.assertTrue(type(result) == QImage)


            result_view = qimage2ndarray.byte_view(result)
            if sys.byteorder == "little":
                self.assertTrue((result_view[:1, :, 3] == 0).all())
                self.assertTrue((result_view[-1:, :, 3] == 0).all())
                self.assertTrue((result_view[:, :1, 3] == 0).all())
                self.assertTrue((result_view[:, -1:, 3] == 0).all())
            else:
                self.assertTrue((result_view[:1, :, 0] == 0).all())
                self.assertTrue((result_view[-1:, :, 0] == 0).all())
                self.assertTrue((result_view[:, :1, 0] == 0).all())
                self.assertTrue((result_view[:, -1:, 0] == 0).all())
示例#16
0
    def toImage( self ):
        t = time.time()
       
        tWAIT = time.time()
        self._arrayreq.wait()
        tWAIT = 1000.0*(time.time()-tWAIT)
        
        tAR = time.time()
        a = self._arrayreq.getResult()
        tAR = 1000.0*(time.time()-tAR)

        tImg = None
        if _has_vigra and hasattr(vigra.colors, 'gray2qimage_ARGB32Premultiplied'):
            if not a.flags.contiguous:
                a = a.copy()
            tImg = time.time()
            img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32_Premultiplied)
            tintColor = np.asarray([self._tintColor.redF(), self._tintColor.greenF(), self._tintColor.blueF()], dtype=np.float32);
            normalize = np.asarray(self._normalize, dtype=a.dtype)
            if normalize[0] > normalize[1]:
                normalize = None
            vigra.colors.alphamodulated2qimage_ARGB32Premultiplied(a, byte_view(img), tintColor, normalize) 
            tImg = 1000.0*(time.time()-tImg)
        else:
            self.logger.warning("using unoptimized conversion functions")
            tImg = time.time()
            shape = a.shape + (4,)
            d = np.empty(shape, dtype=np.float32)
            d[:,:,0] = a[:,:]*self._tintColor.redF()
            d[:,:,1] = a[:,:]*self._tintColor.greenF()
            d[:,:,2] = a[:,:]*self._tintColor.blueF()
            d[:,:,3] = a[:,:]
            normalize = self._normalize
            img = array2qimage(d, normalize)
            img = img.convertToFormat(QImage.Format_ARGB32_Premultiplied)        
            tImg = 1000.0*(time.time()-tImg)
       
        if self.logger.getEffectiveLevel() >= logging.DEBUG:
            tTOT = 1000.0*(time.time()-t)
            self.logger.debug("toImage (%dx%d, normalize=%r) took %f msec. (array req: %f, wait: %f, img: %f)" % (img.width(), img.height(), normalize, tTOT, tAR, tWAIT, tImg))
            
        return img
        
        return img
示例#17
0
def test_gray2qimage():
    if not _have_qt:
        return
    
    # create test data such that rounding does not depend on the least significant bit
    a = (numpy.random.randint(255, size=(100,200)).astype(numpy.float32)+0.25)/255.0-0.5
    a[0,0] =-0.5 #make sure we get the correct bounds
    a[0,1] = 0.5
    vigra.impex.writeImage(a.swapaxes(0,1), "tmp1.png")

    img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32_Premultiplied)
    n = numpy.asarray([-0.5, 0.5], dtype=numpy.float32)
    vigra.colors.gray2qimage_ARGB32Premultiplied(a, byte_view(img), n)
    img.save("tmp2.png")
    
    tmp1 = vigra.impex.readImage("tmp1.png")
    tmp2 = vigra.impex.readImage("tmp2.png")
    
    for i in range(3):
        assert_true( (tmp1 == tmp2[:,:,i]).all() )
    assert_true( (tmp2[:,:,3] == 255).all() )
示例#18
0
	def ObjDetect(self):
		eightbit = QImage.convertToFormat(self._image, QImage.Format_Indexed8)
		eightbit = qim.byte_view(eightbit)
		eightbit = cv2.medianBlur(eightbit, 19)
		thr = cv2.adaptiveThreshold(eightbit, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
		#ret, thr = cv2.threshold(eightbit, 127, 255, cv2.THRESH_BINARY)
		cv2.imshow("NAO", thr)
		k = cv2.waitKey(100) & 0xff
		if k == 27:
			cv2.destroyAllWindows()
			sys.exit(app.exec_())
		contours0, hierarchy = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
		print len(contours0)
		for cnt in contours0[0]:
			contours = cv2.approxPolyDP(cnt, cv2.arcLength(contours0, True), True)
			#contours = cv2.approxPolyDP(contours, .01 * cv2.arcLength(contours, True), True)
			self._array = cv2.drawContours(self._array, [cnt], 0, (255, 0, 0), 2)
		cv2.imshow("NAO", self._array)
		k = cv2.waitKey(100) & 0xff
		if k == 27:
			cv2.destroyAllWindows()
			sys.exit(app.exec_())
示例#19
0
    def toImage( self ):
        a = self._arrayreq.getResult()
        assert a.ndim == 2

        # Use vigra if possible (much faster)
        if _has_vigra and hasattr(vigra.colors, 'applyColortable'):
            img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32) 
            vigra.colors.applyColortable(a, self._colorTable, byte_view(img))

        # Without vigra, do it the slow way 
        else:
            if _has_vigra:
                # If this warning is annoying you, try this:
                # warnings.filterwarnings("once")
                warnings.warn("Using slow colortable images.  Upgrade to VIGRA > 1.9 to use faster implementation.")

            #make sure that a has values in range [0, colortable_length)
            a = np.remainder(a, len(self._colorTable))
            #apply colortable
            colortable = np.roll(np.fliplr(self._colorTable), -1, 1) # self._colorTable is BGRA, but array2qimage wants RGBA
            img = colortable[a]
            img = array2qimage(img)

        return img 
示例#20
0
    def testOutOfViewDirtyPropagation( self ):
        self.lsm.append(self.layer1)
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)

        # Navigate down to the second z-slice
        self.pump.syncedSliceSources.through = [0,1,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()

        # Sanity check: Do we see the right data on the second
        # slice? (should be all 1s)
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == 1))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        # Navigate down to the third z-slice
        self.pump.syncedSliceSources.through = [0,2,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()

        # Sanity check: Do we see the right data on the third
        # slice?(should be all 2s)
        tiles = tp.getTiles(QRectF(100,100,200,200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == 2))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        # Navigate back up to the second z-slice
        self.pump.syncedSliceSources.through = [0,1,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:,:,0:3] == 1))
            self.assertTrue(np.all(aimg[:,:,3] == 255))

        # Change some of the data in the (out-of-view) third z-slice
        slicing = (slice(None), slice(100,300), slice(100,300),
                   slice(2,3), slice(None))
        slicing = tuple(slicing)
        self.ds1._array[slicing] = 99
        self.ds1.setDirty( slicing )

        # Navigate back down to the third z-slice
        self.pump.syncedSliceSources.through = [0,2,0]
        tp.requestRefresh(QRectF(100,100,200,200))
        tp.waitForTiles()

        # Even though the data was out-of-view when it was
        # changed, it should still have new values. If dirtiness
        # wasn't propagated correctly, the cache's old values will
        # be used. (For example, this fails if you comment out the
        # call to setDirty, above.)

        # Shrink accessed rect by 1 pixel on each side (Otherwise,
        # tiling overlap_draw causes getTiles() to return
        # surrounding tiles that we haven't actually touched in
        # this test)
        tiles = tp.getTiles(QRectF(101,101,198,198))

        for tile in tiles:
            aimg = byte_view(tile.qimg)
            # Use any() because the tile borders may not be
            # perfectly aligned with the data we changed.
            self.assertTrue(np.any(aimg[:,:,0:3] == 99))
    def fillArea(self,
                 remove_closed_contour=False,
                 remove_only_current_color=True):

        # Store previous state so we can go back to it
        self._overlay_stack.append(self.mask_pixmap.copy())

        if self.direct_mask_paint:
            self._offscreen_mask_stack.append(self._offscreen_mask.copy())

        # We first convert the mask to a QImage and then to ndarray
        orig_mask = self.mask_pixmap.toImage().convertToFormat(
            QImage.Format_ARGB32)
        msk = alpha_view(orig_mask).copy()

        # Apply simple tresholding and invert the image
        msk[np.where((msk > 0))] = 255
        msk = 255 - msk
        msk1 = np.copy(msk)

        if remove_closed_contour:
            msk1 = 255 - msk1

        if remove_closed_contour:
            if remove_only_current_color:
                the_mask = np.ones(msk1.shape[:2],
                                   np.uint8) * 255  # Initial mask
                fullmask = self.export_ndarray_noalpha(
                )  # Get the colored version
                reds, greens, blues = fullmask[:, :,
                                               0], fullmask[:, :,
                                                            1], fullmask[:, :,
                                                                         2]
                cur_col = list(self.brush_fill_color.getRgb()
                               )[:-1]  # Only current color is considered
                # So that fill happens only for this specific color
                the_mask[
                    np.isclose(reds, cur_col[0], atol=PIXMAP_CONV_BUG_ATOL)
                    & np.isclose(greens, cur_col[1], atol=PIXMAP_CONV_BUG_ATOL)
                    & np.isclose(blues, cur_col[2],
                                 atol=PIXMAP_CONV_BUG_ATOL)] = 0

            else:
                the_mask = np.zeros(msk1.shape[:2], np.uint8)
        else:
            the_mask = cv2.bitwise_not(np.copy(msk))

        the_mask = cv2.copyMakeBorder(the_mask, 1, 1, 1, 1,
                                      cv2.BORDER_CONSTANT, 0)

        # Fill the contour
        seed_point = (int(self.lastCursorLocation.x()),
                      int(self.lastCursorLocation.y()))
        cv2.floodFill(msk1, the_mask, seed_point, 0, 0, 1)

        # We paint in only the newly arrived pixels (or remove the pixels in the contour)
        if remove_closed_contour:
            paintin = msk1
        else:
            paintin = msk - msk1  # This is fill case

        # Take original pixmap image: it has two components, RGB and ALPHA
        new_img = np.dstack((rgb_view(orig_mask), alpha_view(orig_mask)))

        # Fill the newly created area with current brush color
        if not remove_closed_contour:
            new_img[np.where(
                (paintin == 255))] = list(self.brush_fill_color.getRgb())
        else:
            new_img[np.where((paintin == 0))] = (0, 0, 0, 0)  # Erase
        new_qimg = array2qimage(new_img)

        # In case of direct drawing, need to update the offscreen mask as well
        if self.direct_mask_paint:
            omask = byte_view(self._offscreen_mask).copy()
            omask = omask.reshape(omask.shape[:-1])
            if not remove_closed_contour:
                tc = self.d_rgb2gray[self.brush_fill_color.name()]
                omask[np.where((paintin == 255))] = tc
            else:
                omask[np.where((paintin == 0))] = 0
            self._offscreen_mask = QImage(omask.data, omask.shape[1],
                                          omask.shape[0], omask.strides[0],
                                          QImage.Format_Grayscale8)

        # Finally update the screen stuff
        self.mask_pixmap = QPixmap.fromImage(new_qimg)
        self._overlayHandle.setPixmap(self.mask_pixmap)
示例#22
0
    def testOutOfViewDirtyPropagation( self ):
        self.lsm.append(self.layer1)
        tiling = Tiling((900,400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)
        try:
            # Navigate down to the second z-slice
            self.pump.syncedSliceSources.through = [0,1,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()

            # Sanity check: Do we see the right data on the second slice? (should be all 1s)
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == 1))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            # Navigate down to the third z-slice
            self.pump.syncedSliceSources.through = [0,2,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()

            # Sanity check: Do we see the right data on the third slice?(should be all 2s)
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == 2))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            # Navigate back up to the second z-slice
            self.pump.syncedSliceSources.through = [0,1,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                self.assertTrue(np.all(aimg[:,:,0:3] == 1))
                self.assertTrue(np.all(aimg[:,:,3] == 255))

            # Change some of the data in the (out-of-view) third z-slice
            slicing = (slice(None), slice(100,300), slice(100,300), slice(2,3), slice(None))
            slicing = tuple(slicing)
            self.ds1._array[slicing] = 99
            self.ds1.setDirty( slicing )
            
            # Navigate back down to the third z-slice
            self.pump.syncedSliceSources.through = [0,2,0]
            tp.requestRefresh(QRectF(100,100,200,200))
            tp.join()

            # Even though the data was out-of-view when it was changed, it should still have new values.
            # If dirtiness wasn't propagated correctly, the cache's old values will be used.
            # (For example, this fails if you comment out the call to setDirty, above.)
            tiles = tp.getTiles(QRectF(100,100,200,200))
            for tile in tiles:
                aimg = byte_view(tile.qimg)
                # Use any() because the tile borders may not be perfectly aligned with the data we changed.
                self.assertTrue(np.any(aimg[:,:,0:3] == 99))

        finally:
            tp.notifyThreadsToStop()
            tp.joinThreads()
def test_scalar2qimage_normalize_dont_touch_0_255():
    a = numpy.zeros((100, 256), dtype=float)
    a[:] = numpy.arange(256)
    qImg = qimage2ndarray.array2qimage(a, normalize=True)
    b = qimage2ndarray.byte_view(qImg)
    assert numpy.all(a == b[..., 0])
示例#24
0
smap = matplotlib.cm.ScalarMappable(norm = cnrm, cmap = clrmap)

smap.set_array(x);


#colortable = smap.to_rgba(x);

colortable = smap.to_rgba(x, bytes = True);

# note the order of the axes here !
img = QImage(alexa.shape[1], alexa.shape[0], QImage.Format_ARGB32)

a = numpy.asanyarray(alexa, dtype = numpy.uint32)

# aa is an array
aa = vigra.colors.applyColortable(a, colortable, byte_view(img)); # requires qimage2ndarray

# cimg2 copies aa into a new Vigra Image (ARGB)
cimg2 = vigra.VigraArray(aa, axistags = vigra.VigraArray.defaultAxistags('xyc'))

### find out colormaps currently available in matplotlib

from pylab import *
from numpy import outer
rc('text', usetex=False)
a=outer(arange(0,1,0.01),ones(10))
figure(figsize=(10,5))
subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99)
maps=[m for m in cm.datad if not m.endswith("_r")]  ### this idiom is called a list comprehension
maps.sort()
l=len(maps)+1
示例#25
0
    player1X = barPosX - bar_dist
    player2X = player1X + target_dist
    stoneX = player2X + playerWidth - stoneWidth

    #draw
    image.fill(Qt.white)

    painter.fillRect(0, screenHeight - fieldHeight, screenWidth, fieldHeight,
                     fieldColor)
    painter.fillRect(barPosX, barPosY, barWidth, barHeight, fieldColor)

    painter.fillRect(player1X, playerY, playerWidth, playerHeight, playerColor)
    painter.fillRect(player2X, playerY, playerWidth, playerHeight, playerColor)
    painter.fillRect(stoneX, stoneY, stoneWidth, stoneWidth, stoneColor)

    #    image.save('images\\' + str(data[:2]) + '.jpg')
    arr_image = qimage2ndarray.byte_view(image)
    #    cv2.imshow('a', arr_image)
    cropped_image = arr_image[imageCrop:]
    resized_image = cv2.resize(cropped_image, imageResize)
    #    cv2.imwrite('images\\' + str(data[:2]) + '.jpg', resized_image)

    img_data.append(resized_image)
    output.append([180 - data[2], data[3]])

savedData = [img_data, output]

print('saving the data...')
print('Please wait...')
numpy.save('modelImageData.npy', savedData)
print('saved successfully!!')
示例#26
0
def test_byte_view():
    for filename in all_test_images:
        assert isinstance(qimage2ndarray.byte_view(filename), numpy.ndarray)
def test_byte_view():
    for filename in all_test_images:
        assert isinstance(qimage2ndarray.byte_view(filename), numpy.ndarray)
示例#28
0
    def toImage( self ):
        t = time.time()
        
        tWAIT = time.time()
        self._arrayreq.wait()
        tWAIT = 1000.0*(time.time()-tWAIT)
        
        tAR = time.time()
        a = self._arrayreq.getResult()
        tAR = 1000.0*(time.time()-tAR)
        
        assert a.ndim == 2

        if self._normalize and self._normalize[0] < self._normalize[1]:
            nmin, nmax = self._normalize
            if nmin:
                a = a - nmin
            scale = (len(self._colorTable)-1) / float(nmax - nmin + 1e-35) #if max==min
            if scale != 1.0:
                a = a * scale
            if len(self._colorTable) <= 2**8:
                a = np.asanyarray( a, dtype=np.uint8 )
            elif len(self._colorTable) <= 2**16:
                a = np.asanyarray( a, dtype=np.uint16 )
            elif len(self._colorTable) <= 2**32:
                a = np.asanyarray( a, dtype=np.uint32 )

        # Use vigra if possible (much faster)
        tImg = None
        if _has_vigra and hasattr(vigra.colors, 'applyColortable'):
            tImg = time.time()
            img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32)
            if not issubclass( a.dtype.type, np.integer ):
                raise NotImplementedError()
                #FIXME: maybe this should be done in a better way using an operator before the colortable request which properly handles 
                #this problem 
                warnings.warn("Data for colortable layers cannot be float, casting",RuntimeWarning)
                a = np.asanyarray(a, dtype=np.uint32)

            # If we have a masked array with a non-trivial mask, ensure that mask is made transparent.
            _colorTable = self._colorTable
            if np.ma.is_masked(a):
                # Add transparent color at the beginning of the colortable as needed.
                if (_colorTable[0, 3] != 0):
                    # If label 0 is unused, it can be transparent. Otherwise, the transparent color must be inserted.
                    if (a.min() == 0):
                        # If it will overflow simply promote the type. Unless we have reached the max VIGRA type.
                        if (a.max() == np.iinfo(a.dtype).max):
                            a_new_dtype = np.min_scalar_type(np.iinfo(a.dtype).max + 1)
                            if a_new_dtype <= np.dtype(np.uint32):
                                 a = np.asanyarray(a, dtype=a_new_dtype)
                            else:
                                assert (np.iinfo(a.dtype).max >= len(_colorTable)), \
                                       "This is a very large colortable. If it is indeed needed, add a transparent" + \
                                       " color at the beginning of the colortable for displaying masked arrays."

                                # Try to wrap the max value to a smaller value of the same color.
                                a[a == np.iinfo(a.dtype).max] %= len(_colorTable)

                        # Insert space for transparent color and shift labels up.
                        _colorTable = np.insert(_colorTable, 0, 0, axis=0)
                        a += 1
                    else:
                        # Make sure the first color is transparent.
                        _colorTable = _colorTable.copy()
                        _colorTable[0] = 0

                # Make masked values transparent.
                a = np.ma.filled(a, 0)

            vigra.colors.applyColortable(a, _colorTable, byte_view(img))
            tImg = 1000.0*(time.time()-tImg)

        # Without vigra, do it the slow way 
        else:
            raise NotImplementedError()
            if _has_vigra:
                # If this warning is annoying you, try this:
                # warnings.filterwarnings("once")
                warnings.warn("Using slow colortable images.  Upgrade to VIGRA > 1.9 to use faster implementation.")

            #make sure that a has values in range [0, colortable_length)
            a = np.remainder(a, len(self._colorTable))
            #apply colortable
            colortable = np.roll(np.fliplr(self._colorTable), -1, 1) # self._colorTable is BGRA, but array2qimage wants RGBA
            img = colortable[a]
            img = array2qimage(img)
            
        if self.logger.getEffectiveLevel() >= logging.DEBUG:
            tTOT = 1000.0*(time.time()-t)
            self.logger.debug("toImage (%dx%d) took %f msec. (array req: %f, wait: %f, img: %f)" % (img.width(), img.height(), tTOT, tAR, tWAIT, tImg))

        return img 
def test_scalar2qimage_normalize_dont_touch_0_255():
    a = numpy.zeros((100, 256), dtype = float)
    a[:] = numpy.arange(256)
    qImg = qimage2ndarray.array2qimage(a, normalize = True)
    b = qimage2ndarray.byte_view(qImg)
    assert numpy.all(a == b[...,0])
示例#30
0
    def toImage( self ):
        t = time.time()
        
        tWAIT = time.time()
        self._arrayreq.wait()
        tWAIT = 1000.0*(time.time()-tWAIT)
        
        tAR = time.time()
        a = self._arrayreq.getResult()
        tAR = 1000.0*(time.time()-tAR)
        
        assert a.ndim == 2

        if self._normalize and self._normalize[0] < self._normalize[1]:
            nmin, nmax = self._normalize
            if nmin:
                a = a - nmin
            scale = (len(self._colorTable)-1) / float(nmax - nmin + 1e-35) #if max==min
            if scale != 1.0:
                a = a * scale
            if len(self._colorTable) <= 2**8:
                a = np.asarray( a, dtype=np.uint8 )
            elif len(self._colorTable) <= 2**16:
                a = np.asarray( a, dtype=np.uint16 )
            elif len(self._colorTable) <= 2**32:
                a = np.asarray( a, dtype=np.uint32 )

        # Use vigra if possible (much faster)
        tImg = None
        if _has_vigra and hasattr(vigra.colors, 'applyColortable'):
            tImg = time.time()
            img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32)
            if not issubclass( a.dtype.type, np.integer ):
                raise NotImplementedError()
                #FIXME: maybe this should be done in a better way using an operator before the colortable request which properly handles 
                #this problem 
                import warnings
                warnings.warn("Data for colortable layers cannot be float, casting",RuntimeWarning)
                a=a.astype(np.int32)
            vigra.colors.applyColortable(a, self._colorTable, byte_view(img))
            tImg = 1000.0*(time.time()-tImg)

        # Without vigra, do it the slow way 
        else:
            raise NotImplementedError()
            if _has_vigra:
                # If this warning is annoying you, try this:
                # warnings.filterwarnings("once")
                warnings.warn("Using slow colortable images.  Upgrade to VIGRA > 1.9 to use faster implementation.")

            #make sure that a has values in range [0, colortable_length)
            a = np.remainder(a, len(self._colorTable))
            #apply colortable
            colortable = np.roll(np.fliplr(self._colorTable), -1, 1) # self._colorTable is BGRA, but array2qimage wants RGBA
            img = colortable[a]
            img = array2qimage(img)
            
        if self.logger.getEffectiveLevel() >= logging.DEBUG:
            tTOT = 1000.0*(time.time()-t)
            self.logger.debug("toImage (%dx%d) took %f msec. (array req: %f, wait: %f, img: %f)" % (img.width(), img.height(), tTOT, tAR, tWAIT, tImg))

        return img 
示例#31
0
    def testOutOfViewDirtyPropagation(self):
        self.lsm.append(self.layer1)
        tiling = Tiling((900, 400), blockSize=100)
        tp = TileProvider(tiling, self.pump.stackedImageSources)

        # Navigate down to the second z-slice
        self.pump.syncedSliceSources.through = [0, 1, 0]
        tp.requestRefresh(QRectF(100, 100, 200, 200))
        tp.waitForTiles()

        # Sanity check: Do we see the right data on the second
        # slice? (should be all 1s)
        tiles = tp.getTiles(QRectF(100, 100, 200, 200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:, :, 0:3] == 1))
            self.assertTrue(np.all(aimg[:, :, 3] == 255))

        # Navigate down to the third z-slice
        self.pump.syncedSliceSources.through = [0, 2, 0]
        tp.requestRefresh(QRectF(100, 100, 200, 200))
        tp.waitForTiles()

        # Sanity check: Do we see the right data on the third
        # slice?(should be all 2s)
        tiles = tp.getTiles(QRectF(100, 100, 200, 200))
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:, :, 0:3] == 2))
            self.assertTrue(np.all(aimg[:, :, 3] == 255))

        # Navigate back up to the second z-slice
        self.pump.syncedSliceSources.through = [0, 1, 0]
        tp.requestRefresh(QRectF(100, 100, 200, 200))
        tp.waitForTiles()
        for tile in tiles:
            aimg = byte_view(tile.qimg)
            self.assertTrue(np.all(aimg[:, :, 0:3] == 1))
            self.assertTrue(np.all(aimg[:, :, 3] == 255))

        # Change some of the data in the (out-of-view) third z-slice
        slicing = (slice(None), slice(100, 300), slice(100, 300), slice(2, 3), slice(None))
        slicing = tuple(slicing)
        self.ds1._array[slicing] = 99
        self.ds1.setDirty(slicing)

        # Navigate back down to the third z-slice
        self.pump.syncedSliceSources.through = [0, 2, 0]
        tp.requestRefresh(QRectF(100, 100, 200, 200))
        tp.waitForTiles()

        # Even though the data was out-of-view when it was
        # changed, it should still have new values. If dirtiness
        # wasn't propagated correctly, the cache's old values will
        # be used. (For example, this fails if you comment out the
        # call to setDirty, above.)

        # Shrink accessed rect by 1 pixel on each side (Otherwise,
        # tiling overlap_draw causes getTiles() to return
        # surrounding tiles that we haven't actually touched in
        # this test)
        tiles = tp.getTiles(QRectF(101, 101, 198, 198))

        for tile in tiles:
            aimg = byte_view(tile.qimg)
            # Use any() because the tile borders may not be
            # perfectly aligned with the data we changed.
            self.assertTrue(np.any(aimg[:, :, 0:3] == 99))
示例#32
0
    def toImage(self):
        t = time.time()

        tWAIT = time.time()
        a = self._arrayreq.wait()
        tWAIT = 1000.0 * (time.time() - tWAIT)

        assert a.ndim == 2, "GrayscaleImageRequest.toImage(): result has shape %r, which is not 2-D" % (
            a.shape, )

        normalize = self._normalize
        if not normalize:
            normalize = [0, 255]

        # FIXME: It is obviously wrong to truncate like this (right?)
        if a.dtype == np.uint64 or a.dtype == np.int64:
            warnings.warn("Truncating 64-bit pixels for display")
            if a.dtype == np.uint64:
                a = np.asanyarray(a, np.uint32)
            elif a.dtype == np.int64:
                a = np.asanyarray(a, np.int32)

        if a.dtype == np.bool_:
            a = a.view(np.uint8)

        has_no_mask = not np.ma.is_masked(a)

        #
        # new conversion
        #
        tImg = None
        if has_no_mask and _has_vigra and hasattr(
                vigra.colors, "gray2qimage_ARGB32Premultiplied"):
            if (not self._normalize or self._normalize[0] >= self._normalize[1]
                    or self._normalize
                    == [0, 0]):  # FIXME: fix volumina conventions
                n = np.asarray([0, 255], dtype=np.float32)
            else:
                n = np.asarray(self._normalize, dtype=np.float32)
            tImg = time.time()
            img = QImage(a.shape[1], a.shape[0],
                         QImage.Format_ARGB32_Premultiplied)
            if not a.flags["C_CONTIGUOUS"]:
                a = a.copy()
            vigra.colors.gray2qimage_ARGB32Premultiplied(a, byte_view(img), n)
            tImg = 1000.0 * (time.time() - tImg)
        else:
            if has_no_mask:
                self.logger.warning("using slow image creation function")
            tImg = time.time()
            if self._normalize:
                # clipping has been implemented in this commit,
                # but it is not yet available in the packages obtained via easy_install
                # http://www.informatik.uni-hamburg.de/~meine/hg/qimage2ndarray/diff/fcddc70a6dea/qimage2ndarray/__init__.py
                a = np.clip(a, *self._normalize)
            img = gray2qimage(a, self._normalize)
            ret = img.convertToFormat(QImage.Format_ARGB32_Premultiplied)
            tImg = 1000.0 * (time.time() - tImg)

        if self.logger.isEnabledFor(logging.DEBUG):
            tTOT = 1000.0 * (time.time() - t)
            self.logger.debug(
                "toImage (%dx%d, normalize=%r) took %f msec. (array wait: %f, img: %f)"
                % (img.width(), img.height(), normalize, tTOT, tWAIT, tImg))

        return img
示例#33
0
    def toImage( self ):
        t = time.time()
        
        tWAIT = time.time()
        self._arrayreq.wait()
        tWAIT = 1000.0*(time.time()-tWAIT)
        
        tAR = time.time()
        a = self._arrayreq.getResult()
        tAR = 1000.0*(time.time()-tAR)
        
        assert a.ndim == 2

        if self._normalize and self._normalize[0] < self._normalize[1]:
            nmin, nmax = self._normalize
            if nmin:
                a = a - nmin
            scale = (len(self._colorTable)-1) / float(nmax - nmin + 1e-35) #if max==min
            if scale != 1.0:
                a = a * scale
            if len(self._colorTable) <= 2**8:
                a = np.asanyarray( a, dtype=np.uint8 )
            elif len(self._colorTable) <= 2**16:
                a = np.asanyarray( a, dtype=np.uint16 )
            elif len(self._colorTable) <= 2**32:
                a = np.asanyarray( a, dtype=np.uint32 )

        # Use vigra if possible (much faster)
        tImg = None
        if _has_vigra and hasattr(vigra.colors, 'applyColortable'):
            tImg = time.time()
            img = QImage(a.shape[1], a.shape[0], QImage.Format_ARGB32)
            if not issubclass( a.dtype.type, np.integer ):
                raise NotImplementedError()
                #FIXME: maybe this should be done in a better way using an operator before the colortable request which properly handles 
                #this problem 
                warnings.warn("Data for colortable layers cannot be float, casting",RuntimeWarning)
                a = np.asanyarray(a, dtype=np.uint32)

            # If we have a masked array with a non-trivial mask, ensure that mask is made transparent.
            _colorTable = self._colorTable
            if np.ma.is_masked(a):
                # Add transparent color at the beginning of the colortable as needed.
                if (_colorTable[0, 3] != 0):
                    # If label 0 is unused, it can be transparent. Otherwise, the transparent color must be inserted.
                    if (a.min() == 0):
                        # If it will overflow simply promote the type. Unless we have reached the max VIGRA type.
                        if (a.max() == np.iinfo(a.dtype).max):
                            a_new_dtype = np.min_scalar_type(np.iinfo(a.dtype).max + 1)
                            if a_new_dtype <= np.dtype(np.uint32):
                                 a = np.asanyarray(a, dtype=a_new_dtype)
                            else:
                                assert (np.iinfo(a.dtype).max >= len(_colorTable)), \
                                       "This is a very large colortable. If it is indeed needed, add a transparent" + \
                                       " color at the beginning of the colortable for displaying masked arrays."

                                # Try to wrap the max value to a smaller value of the same color.
                                a[a == np.iinfo(a.dtype).max] %= len(_colorTable)

                        # Insert space for transparent color and shift labels up.
                        _colorTable = np.insert(_colorTable, 0, 0, axis=0)
                        a[:] = a+1
                    else:
                        # Make sure the first color is transparent.
                        _colorTable = _colorTable.copy()
                        _colorTable[0] = 0

                # Make masked values transparent.
                a = np.ma.filled(a, 0)

            if a.dtype in (np.uint64, np.int64):
                # FIXME: applyColortable() doesn't support 64-bit, so just truncate
                a = a.astype(np.uint32)

            vigra.colors.applyColortable(a.astype(np.uint32), _colorTable, byte_view(img))
            tImg = 1000.0*(time.time()-tImg)

        # Without vigra, do it the slow way 
        else:
            raise NotImplementedError()
            if _has_vigra:
                # If this warning is annoying you, try this:
                # warnings.filterwarnings("once")
                warnings.warn("Using slow colortable images.  Upgrade to VIGRA > 1.9 to use faster implementation.")

            #make sure that a has values in range [0, colortable_length)
            a = np.remainder(a, len(self._colorTable))
            #apply colortable
            colortable = np.roll(np.fliplr(self._colorTable), -1, 1) # self._colorTable is BGRA, but array2qimage wants RGBA
            img = colortable[a]
            img = array2qimage(img)
            
        if self.logger.isEnabledFor(logging.DEBUG):
            tTOT = 1000.0*(time.time()-t)
            self.logger.debug("toImage (%dx%d) took %f msec. (array req: %f, wait: %f, img: %f)" % (img.width(), img.height(), tTOT, tAR, tWAIT, tImg))

        return img