예제 #1
0
def startApplication(enableQuitTimer=False):
    appInstance = QtGui.QApplication.instance()
    if enableQuitTimer:
        quitTimer = TimerCallback()
        quitTimer.callback = appInstance.quit
        quitTimer.singleShot(0.1)
    appInstance.exec_()
예제 #2
0
    def start(enableAutomaticQuit=True):
        """
        In testing mode, the application will quit automatically after starting
        unless enableAutomaticQuit is set to False.  Tests that need to perform
        work after the QApplication has started can set this flag to False and
        call quit or exit themselves.

        In testing mode, this function will register an exception hook so that
        tests will return on error code if an unhandled exception is raised.
        """
        if enableAutomaticQuit:
            ConsoleApp.startTestingModeQuitTimer()

        if (ConsoleApp.getTestingEnabled()
                and not ConsoleApp.getTestingInteractiveEnabled()):
            sys.excepthook = _consoleAppExceptionHook

        def onStartup():
            for func in ConsoleApp._startupCallbacks:
                try:
                    func()
                except:
                    print traceback.format_exc()

        startTimer = TimerCallback(callback=onStartup)
        startTimer.singleShot(0)

        result = ConsoleApp.applicationInstance().exec_()

        if (ConsoleApp.getTestingEnabled()
                and not ConsoleApp.getTestingInteractiveEnabled()):
            print "TESTING PROGRAM RETURNING EXIT CODE:", result
            sys.exit(result)

        return result
예제 #3
0
def startApplication(enableQuitTimer=False):
    appInstance = QtGui.QApplication.instance()
    if enableQuitTimer:
        quitTimer = TimerCallback()
        quitTimer.callback = appInstance.quit
        quitTimer.singleShot(0.1)
    appInstance.exec_()
예제 #4
0
    def start(enableAutomaticQuit=True):
        '''
        In testing mode, the application will quit automatically after starting
        unless enableAutomaticQuit is set to False.  Tests that need to perform
        work after the QApplication has started can set this flag to False and
        call quit or exit themselves.

        In testing mode, this function will register an exception hook so that
        tests will return on error code if an unhandled exception is raised.
        '''
        if enableAutomaticQuit:
            ConsoleApp.startTestingModeQuitTimer()

        if ConsoleApp.getTestingEnabled() and not ConsoleApp.getTestingInteractiveEnabled():
            sys.excepthook = _consoleAppExceptionHook

        def onStartup():
            for func in ConsoleApp._startupCallbacks:
                try:
                    func()
                except:
                    print traceback.format_exc()

        startTimer = TimerCallback(callback=onStartup)
        startTimer.singleShot(0)

        result = ConsoleApp.applicationInstance().exec_()

        if ConsoleApp.getTestingEnabled() and not ConsoleApp.getTestingInteractiveEnabled():
            print 'TESTING PROGRAM RETURNING EXIT CODE:', result
            sys.exit(result)

        return result
예제 #5
0
class PropertyPanelConnector(object):
    def __init__(self, propertySet, propertiesPanel, propertyNamesToAdd=None):
        self.propertySet = propertySet
        self.propertyNamesToAdd = propertyNamesToAdd
        self.propertiesPanel = propertiesPanel
        self.propertySet.connectPropertyAdded(self._onPropertyAdded)
        self.propertySet.connectPropertyChanged(self._onPropertyChanged)
        self.propertySet.connectPropertyAttributeChanged(
            self._onPropertyAttributeChanged)
        self.propertiesPanel.connect(
            'propertyValueChanged(QtVariantProperty*)',
            self._onPanelPropertyChanged)

        self.timer = TimerCallback()
        self.timer.callback = self._rebuildNow

        self._blockSignals = True
        PropertyPanelHelper.addPropertiesToPanel(self.propertySet,
                                                 self.propertiesPanel,
                                                 self.propertyNamesToAdd)
        self._blockSignals = False

    def cleanup(self):
        self.propertiesPanel.disconnect(
            'propertyValueChanged(QtVariantProperty*)',
            self._onPanelPropertyChanged)

    def _rebuild(self):
        if not self.timer.singleShotTimer.isActive():
            self.timer.singleShot(0)

    def _rebuildNow(self):
        self._blockSignals = True
        self.propertiesPanel.clear()
        PropertyPanelHelper.addPropertiesToPanel(self.propertySet,
                                                 self.propertiesPanel)
        self._blockSignals = False

    def _onPropertyAdded(self, propertySet, propertyName):
        self._rebuild()

    def _onPropertyAttributeChanged(self, propertySet, propertyName,
                                    propertyAttribute):
        self._rebuild()

    def _onPropertyChanged(self, propertySet, propertyName):
        self._blockSignals = True
        PropertyPanelHelper.onPropertyValueChanged(self.propertiesPanel,
                                                   propertySet, propertyName)
        self._blockSignals = False

    def _onPanelPropertyChanged(self, panelProperty):
        if not self._blockSignals:
            PropertyPanelHelper.setPropertyFromPanel(panelProperty,
                                                     self.propertiesPanel,
                                                     self.propertySet)
예제 #6
0
class PropertyPanelConnector(object):

    def __init__(self, propertySet, propertiesPanel, propertyNamesToAdd=None):
        self.propertySet = propertySet
        self.propertyNamesToAdd = propertyNamesToAdd
        self.propertiesPanel = propertiesPanel
        self.connections = []
        self.connections.append(self.propertySet.connectPropertyAdded(self._onPropertyAdded))
        self.connections.append(self.propertySet.connectPropertyChanged(self._onPropertyChanged))
        self.connections.append(self.propertySet.connectPropertyAttributeChanged(self._onPropertyAttributeChanged))
        self.propertiesPanel.connect('propertyValueChanged(QtVariantProperty*)', self._onPanelPropertyChanged)

        self.timer = TimerCallback()
        self.timer.callback = self._rebuildNow

        self._blockSignals = True
        PropertyPanelHelper.addPropertiesToPanel(self.propertySet, self.propertiesPanel, self.propertyNamesToAdd)
        self._blockSignals = False

    def cleanup(self):
        self.timer.callback = None
        self.propertiesPanel.disconnect('propertyValueChanged(QtVariantProperty*)', self._onPanelPropertyChanged)
        for connection in self.connections:
            self.propertySet.callbacks.disconnect(connection)

    def _rebuild(self):
        if not self.timer.singleShotTimer.isActive():
            self.timer.singleShot(0)

    def _rebuildNow(self):
        self._blockSignals = True
        self.propertiesPanel.clear()
        PropertyPanelHelper.addPropertiesToPanel(self.propertySet, self.propertiesPanel)
        self._blockSignals = False

    def _onPropertyAdded(self, propertySet, propertyName):
        self._rebuild()

    def _onPropertyAttributeChanged(self, propertySet, propertyName, propertyAttribute):
        self._rebuild()

    def _onPropertyChanged(self, propertySet, propertyName):
        self._blockSignals = True
        PropertyPanelHelper.onPropertyValueChanged(self.propertiesPanel, propertySet, propertyName)
        self._blockSignals = False

    def _onPanelPropertyChanged(self, panelProperty):
        if not self._blockSignals:
            PropertyPanelHelper.setPropertyFromPanel(panelProperty, self.propertiesPanel, self.propertySet)
예제 #7
0
class AffordanceObjectModelManager(object):

    def __init__(self, view):
        self.collection = lcmobjectcollection.LCMObjectCollection(channel='AFFORDANCE_COLLECTION_COMMAND')
        self.collection.connectDescriptionUpdated(self._onDescriptionUpdated)
        self.collection.connectDescriptionRemoved(self._onDescriptionRemoved)
        self.view = view
        self.notifyFrequency = 30 # throttle lcm messages per second sent for affordance updates
        self._ignoreChanges = False

        self._pendingUpdates = set()
        self.timer = TimerCallback()
        self.timer.callback = self._notifyPendingUpdates

        self.affordanceUpdater = None

    def setAffordanceUpdater(self, affordanceUpdater):
        self.affordanceUpdater = affordanceUpdater

    def getAffordances(self):
        return [obj for obj in om.getObjects() if isinstance(obj, affordanceitems.AffordanceItem)]


    def getCollisionAffordances(self):
        affs = []
        for aff in self.getAffordances():
            if aff.getProperty('Collision Enabled'):
                affs.append(aff)
        return affs

    def getAffordanceId(self, aff):
        return aff.getProperty('uuid')

    def newAffordanceFromDescription(self, desc):
        if 'uuid' not in desc:
            desc['uuid'] = newUUID()
        self.collection.updateDescription(desc)
        return self.getAffordanceById(desc['uuid'])

    def getAffordanceById(self, affordanceId):
        for aff in self.getAffordances():
            if self.getAffordanceId(aff) == affordanceId:
                return aff

    def getAffordanceDescription(self, aff):
        return aff.getDescription()

    def registerAffordance(self, aff, notify=True):
        aff.connectRemovedFromObjectModel(self._onAffordanceRemovedFromObjectModel)
        aff.properties.connectPropertyChanged(self._onAffordancePropertyChanged)
        aff.getChildFrame().connectFrameModified(self._onAffordanceFrameChanged)
        if notify:
            self.notifyAffordanceUpdate(aff)

    def removeAffordance(self, aff):
        self.collection.removeDescription(aff.getProperty('uuid'), notify=False)

    def notifyAffordanceUpdate(self, aff):

        if not isinstance(aff, affordanceitems.AffordanceItem):
            return

        shouldNotify = not self._pendingUpdates and not self.timer.singleShotTimer.isActive()
        self._pendingUpdates.add(aff)
        if shouldNotify:
            self._notifyPendingUpdates()

    def _notifyPendingUpdates(self):

        if self._pendingUpdates:
            self.timer.singleShot(1.0/self.notifyFrequency)

        for aff in self._pendingUpdates:
            try:
                self.collection.updateDescription(self.getAffordanceDescription(aff), notify=False)
            except:
                print(traceback.format_exc())

        self._pendingUpdates.clear()

    def _onAffordancePropertyChanged(self, propertySet, propertyName):
        if self._ignoreChanges:
            return
        self.notifyAffordanceUpdate(self.getAffordanceById(propertySet.getProperty('uuid')))

    def _onAffordanceFrameChanged(self, frameObj):
        if self._ignoreChanges:
            return
        aff = frameObj.parent()
        self.notifyAffordanceUpdate(aff)

    def _onAffordanceRemovedFromObjectModel(self, objectModel, aff):
        if self._ignoreChanges:
            return
        self.removeAffordance(aff)

    def _loadAffordanceFromDescription(self, desc):
        className = desc['classname']
        cls = getattr(affordanceitems, className)
        aff = cls(desc['Name'], self.view)
        om.addToObjectModel(aff, parentObj=om.getOrCreateContainer('affordances'))
        frame = vis.addChildFrame(aff)
        frame.setProperty('Deletable', False)
        aff.loadDescription(desc, copyMode=aff.COPY_MODE_ALL)
        self.registerAffordance(aff, notify=False)

    def _onDescriptionUpdated(self, collection, descriptionId):
        aff = self.getAffordanceById(descriptionId)
        desc = collection.getDescription(descriptionId)

        if aff:
            self._ignoreChanges = True
            aff.loadDescription(desc, copyMode=aff.COPY_MODE_SKIP_LOCAL)
            self._ignoreChanges = False

        else:
            aff = self._loadAffordanceFromDescription(desc)

    def _onDescriptionRemoved(self, collection, descriptionId):
        self._ignoreChanges = True
        om.removeFromObjectModel(self.getAffordanceById(descriptionId))
        self._ignoreChanges = False
예제 #8
0
파일: consoleapp.py 프로젝트: rxdu/director
 def startQuitTimer(timeoutInSeconds):
     quitTimer = TimerCallback()
     quitTimer.callback = ConsoleApp.quit
     quitTimer.singleShot(timeoutInSeconds)
예제 #9
0
class DepthScanner(object):
    def __init__(self, view):
        self.view = view

        self.depthImage = None
        self.pointCloudObj = None
        self.renderObserver = None

        self.windowToDepthBuffer = vtk.vtkWindowToImageFilter()
        self.windowToDepthBuffer.SetInput(self.view.renderWindow())
        self.windowToDepthBuffer.SetInputBufferTypeToZBuffer()
        self.windowToDepthBuffer.ShouldRerenderOff()

        self.windowToColorBuffer = vtk.vtkWindowToImageFilter()
        self.windowToColorBuffer.SetInput(self.view.renderWindow())
        self.windowToColorBuffer.SetInputBufferTypeToRGB()
        self.windowToColorBuffer.ShouldRerenderOff()

        useBackBuffer = False
        if useBackBuffer:
            self.windowToDepthBuffer.ReadFrontBufferOff()
            self.windowToColorBuffer.ReadFrontBufferOff()

        self.initDepthImageView()
        self.initPointCloudView()

        self._block = False
        self.singleShotTimer = TimerCallback()
        self.singleShotTimer.callback = self.update

    def getDepthBufferImage(self):
        return self.windowToDepthBuffer.GetOutput()

    def getDepthImage(self):
        return self.depthScaleFilter.GetOutput()

    def getDepthImageAsNumpyArray(self):
        vtk_image = self.getDepthImage()
        return vtk_image_to_numpy_array(vtk_image)

    def getColorBufferImage(self):
        return self.windowToColorBuffer.GetOutput()

    def updateBufferImages(self):
        for f in [self.windowToDepthBuffer, self.windowToColorBuffer]:
            f.Modified()
            f.Update()

    def initDepthImageView(self):

        self.depthImageColorByRange = [0.0, 4.0]

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0, 0.667)  # red to blue
        lut.SetRange(
            self.depthImageColorByRange)  # map red (near) to blue (far)
        lut.SetRampToLinear()
        lut.Build()

        self.depthScaleFilter = vtk.vtkImageShiftScale()
        self.depthScaleFilter.SetScale(1000)
        self.depthScaleFilter.SetOutputScalarTypeToUnsignedShort()

        self.depthImageLookupTable = lut
        self.imageMapToColors = vtk.vtkImageMapToColors()
        self.imageMapToColors.SetLookupTable(self.depthImageLookupTable)
        self.imageMapToColors.SetInputConnection(
            self.depthScaleFilter.GetOutputPort())

        self.imageView = imageview.ImageView()
        self.imageView.view.setWindowTitle('Depth image')
        self.imageView.setImage(self.imageMapToColors.GetOutput())

    def initPointCloudView(self):
        self.pointCloudView = PythonQt.dd.ddQVTKWidgetView()
        self.pointCloudView.setWindowTitle('Pointcloud')
        self.pointCloudViewBehaviors = viewbehaviors.ViewBehaviors(
            self.pointCloudView)

    def update(self):

        if not self.renderObserver:

            def onEndRender(obj, event):
                if self._block:
                    return
                if not self.singleShotTimer.singleShotTimer.isActive():
                    self.singleShotTimer.singleShot(0)

            self.renderObserver = self.view.renderWindow().AddObserver(
                'EndEvent', onEndRender)

        self._block = True
        self.view.forceRender()
        self.updateBufferImages()
        self._block = False

        depthImage, polyData, _ = computeDepthImageAndPointCloud(
            self.getDepthBufferImage(), self.getColorBufferImage(),
            self.view.camera())

        self.depthScaleFilter.SetInputData(depthImage)
        self.depthScaleFilter.Update()

        self.depthImageLookupTable.SetRange(
            self.depthScaleFilter.GetOutput().GetScalarRange())
        self.imageMapToColors.Update()
        self.imageView.resetCamera()
        #self.imageView.view.render()

        if not self.pointCloudObj:
            self.pointCloudObj = vis.showPolyData(polyData,
                                                  'point cloud',
                                                  colorByName='rgb',
                                                  view=self.pointCloudView)
        else:
            self.pointCloudObj.setPolyData(polyData)
        self.pointCloudView.render()

    def getDepthImageAndPointCloud(self):
        return computeDepthImageAndPointCloud(self.getDepthBufferImage(),
                                              self.getColorBufferImage(),
                                              self.view.camera())
예제 #10
0
 def startQuitTimer(timeoutInSeconds):
     quitTimer = TimerCallback()
     quitTimer.callback = ConsoleApp.quit
     quitTimer.singleShot(timeoutInSeconds)
class DepthScanner(object):

    def __init__(self, view):
        self.view = view

        self.depthImage = None
        self.pointCloudObj = None
        self.renderObserver = None

        self.windowToDepthBuffer = vtk.vtkWindowToImageFilter()
        self.windowToDepthBuffer.SetInput(self.view.renderWindow())
        self.windowToDepthBuffer.SetInputBufferTypeToZBuffer()
        self.windowToDepthBuffer.ShouldRerenderOff()

        self.windowToColorBuffer = vtk.vtkWindowToImageFilter()
        self.windowToColorBuffer.SetInput(self.view.renderWindow())
        self.windowToColorBuffer.SetInputBufferTypeToRGB()
        self.windowToColorBuffer.ShouldRerenderOff()

        useBackBuffer = False
        if useBackBuffer:
            self.windowToDepthBuffer.ReadFrontBufferOff()
            self.windowToColorBuffer.ReadFrontBufferOff()

        self.initDepthImageView()
        self.initPointCloudView()

        self._block = False
        self.singleShotTimer = TimerCallback()
        self.singleShotTimer.callback = self.update

    def getDepthBufferImage(self):
        return self.windowToDepthBuffer.GetOutput()

    def getDepthImage(self):
        return self.depthScaleFilter.GetOutput()

    def getDepthImageAsNumpyArray(self):
        vtk_image = self.getDepthImage()
        return vtk_image_to_numpy_array(vtk_image)

    def getColorBufferImage(self):
        return self.windowToColorBuffer.GetOutput()

    def updateBufferImages(self):
        for f in [self.windowToDepthBuffer, self.windowToColorBuffer]:
            f.Modified()
            f.Update()

    def initDepthImageView(self):

        self.depthImageColorByRange = [0.0, 4.0]

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0, 0.667) # red to blue
        lut.SetRange(self.depthImageColorByRange) # map red (near) to blue (far)
        lut.SetRampToLinear()
        lut.Build()

        self.depthScaleFilter = vtk.vtkImageShiftScale()
        self.depthScaleFilter.SetScale(1000)
        self.depthScaleFilter.SetOutputScalarTypeToUnsignedShort()

        self.depthImageLookupTable = lut
        self.imageMapToColors = vtk.vtkImageMapToColors()
        self.imageMapToColors.SetLookupTable(self.depthImageLookupTable)
        self.imageMapToColors.SetInputConnection(self.depthScaleFilter.GetOutputPort())

        self.imageView = imageview.ImageView()
        self.imageView.view.setWindowTitle('Depth image')
        self.imageView.setImage(self.imageMapToColors.GetOutput())

    def initPointCloudView(self):
        self.pointCloudView = PythonQt.dd.ddQVTKWidgetView()
        self.pointCloudView.setWindowTitle('Pointcloud')
        self.pointCloudViewBehaviors = viewbehaviors.ViewBehaviors(self.pointCloudView)

    def update(self):

        if not self.renderObserver:
            def onEndRender(obj, event):
                if self._block:
                    return
                if not self.singleShotTimer.singleShotTimer.isActive():
                    self.singleShotTimer.singleShot(0)
            self.renderObserver = self.view.renderWindow().AddObserver('EndEvent', onEndRender)

        self._block = True
        self.view.forceRender()
        self.updateBufferImages()
        self._block = False

        depthImage, polyData, _ = computeDepthImageAndPointCloud(self.getDepthBufferImage(), self.getColorBufferImage(), self.view.camera())

        self.depthScaleFilter.SetInputData(depthImage)
        self.depthScaleFilter.Update()

        self.depthImageLookupTable.SetRange(self.depthScaleFilter.GetOutput().GetScalarRange())
        self.imageMapToColors.Update()
        self.imageView.resetCamera()
        #self.imageView.view.render()

        if not self.pointCloudObj:
            self.pointCloudObj = vis.showPolyData(polyData, 'point cloud', colorByName='rgb', view=self.pointCloudView)
        else:
            self.pointCloudObj.setPolyData(polyData)
        self.pointCloudView.render()

    def getDepthImageAndPointCloud(self):
        return computeDepthImageAndPointCloud(self.getDepthBufferImage(), self.getColorBufferImage(), self.view.camera())
예제 #12
0
class AffordanceObjectModelManager(object):

    def __init__(self, view):
        self.collection = lcmobjectcollection.LCMObjectCollection(channel='AFFORDANCE_COLLECTION_COMMAND')
        self.collection.connectDescriptionUpdated(self._onDescriptionUpdated)
        self.collection.connectDescriptionRemoved(self._onDescriptionRemoved)
        self.view = view
        self.notifyFrequency = 30 # throttle lcm messages per second sent for affordance updates
        self._ignoreChanges = False

        self._pendingUpdates = set()
        self.timer = TimerCallback()
        self.timer.callback = self._notifyPendingUpdates

        self.affordanceUpdater = None

    def setAffordanceUpdater(self, affordanceUpdater):
        self.affordanceUpdater = affordanceUpdater

    def getAffordances(self):
        return [obj for obj in om.getObjects() if isinstance(obj, affordanceitems.AffordanceItem)]


    def getCollisionAffordances(self):
        affs = []
        for aff in self.getAffordances():
            if aff.getProperty('Collision Enabled'):
                affs.append(aff)
        return affs

    def getAffordanceId(self, aff):
        return aff.getProperty('uuid')

    def newAffordanceFromDescription(self, desc):
        if 'uuid' not in desc:
            desc['uuid'] = newUUID()
        self.collection.updateDescription(desc)
        return self.getAffordanceById(desc['uuid'])

    def getAffordanceById(self, affordanceId):
        for aff in self.getAffordances():
            if self.getAffordanceId(aff) == affordanceId:
                return aff

    def getAffordanceDescription(self, aff):
        return aff.getDescription()

    def registerAffordance(self, aff, notify=True):
        aff.connectRemovedFromObjectModel(self._onAffordanceRemovedFromObjectModel)
        aff.properties.connectPropertyChanged(self._onAffordancePropertyChanged)
        aff.getChildFrame().connectFrameModified(self._onAffordanceFrameChanged)
        if notify:
            self.notifyAffordanceUpdate(aff)

    def removeAffordance(self, aff):
        self.collection.removeDescription(aff.getProperty('uuid'), notify=False)

    def notifyAffordanceUpdate(self, aff):

        if not isinstance(aff, affordanceitems.AffordanceItem):
            return

        shouldNotify = not self._pendingUpdates and not self.timer.singleShotTimer.isActive()
        self._pendingUpdates.add(aff)
        if shouldNotify:
            self._notifyPendingUpdates()

    def _notifyPendingUpdates(self):

        if self._pendingUpdates:
            self.timer.singleShot(1.0/self.notifyFrequency)

        for aff in self._pendingUpdates:
            try:
                self.collection.updateDescription(self.getAffordanceDescription(aff), notify=False)
            except:
                print traceback.format_exc()

        self._pendingUpdates.clear()

    def _onAffordancePropertyChanged(self, propertySet, propertyName):
        if self._ignoreChanges:
            return
        self.notifyAffordanceUpdate(self.getAffordanceById(propertySet.getProperty('uuid')))

    def _onAffordanceFrameChanged(self, frameObj):
        if self._ignoreChanges:
            return
        aff = frameObj.parent()
        self.notifyAffordanceUpdate(aff)

    def _onAffordanceRemovedFromObjectModel(self, objectModel, aff):
        if self._ignoreChanges:
            return
        self.removeAffordance(aff)

    def _loadAffordanceFromDescription(self, desc):
        className = desc['classname']
        cls = getattr(affordanceitems, className)
        aff = cls(desc['Name'], self.view)
        om.addToObjectModel(aff, parentObj=om.getOrCreateContainer('affordances'))
        vis.addChildFrame(aff)
        aff.loadDescription(desc, copyMode=aff.COPY_MODE_ALL)
        self.registerAffordance(aff, notify=False)

    def _onDescriptionUpdated(self, collection, descriptionId):
        aff = self.getAffordanceById(descriptionId)
        desc = collection.getDescription(descriptionId)

        if aff:
            self._ignoreChanges = True
            aff.loadDescription(desc, copyMode=aff.COPY_MODE_SKIP_LOCAL)
            self._ignoreChanges = False

        else:
            aff = self._loadAffordanceFromDescription(desc)

    def _onDescriptionRemoved(self, collection, descriptionId):
        self._ignoreChanges = True
        om.removeFromObjectModel(self.getAffordanceById(descriptionId))
        self._ignoreChanges = False
예제 #13
0
class DepthScanner(object):
    def __init__(self, view):
        self.view = view

        self.depthImage = None
        self.pointCloudObj = None
        self.renderObserver = None
        self.parentFolder = 'depth scanner'

        self.windowToDepthBuffer = vtk.vtkWindowToImageFilter()
        self.windowToDepthBuffer.SetInput(self.view.renderWindow())
        self.windowToDepthBuffer.SetInputBufferTypeToZBuffer()
        self.windowToDepthBuffer.ShouldRerenderOff()

        self.windowToColorBuffer = vtk.vtkWindowToImageFilter()
        self.windowToColorBuffer.SetInput(self.view.renderWindow())
        self.windowToColorBuffer.SetInputBufferTypeToRGB()
        self.windowToColorBuffer.ShouldRerenderOff()

        useBackBuffer = False
        if useBackBuffer:
            self.windowToDepthBuffer.ReadFrontBufferOff()
            self.windowToColorBuffer.ReadFrontBufferOff()

        self.initDepthImageView()
        self.initPointCloudView()

        self._block = False
        self.singleShotTimer = TimerCallback()
        self.singleShotTimer.callback = self.update
        self._updateFunc = None

    def getDepthBufferImage(self):
        return self.windowToDepthBuffer.GetOutput()

    def getDepthImage(self):
        return self.depthScaleFilter.GetOutput()

    def getColorBufferImage(self):
        return self.windowToColorBuffer.GetOutput()

    def updateBufferImages(self):
        for f in [self.windowToDepthBuffer, self.windowToColorBuffer]:
            f.Modified()
            f.Update()

    def initDepthImageView(self):

        self.depthImageColorByRange = [0.0, 4.0]

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0, 0.667)  # red to blue
        lut.SetRange(
            self.depthImageColorByRange)  # map red (near) to blue (far)
        lut.SetRampToLinear()
        lut.Build()

        self.depthScaleFilter = vtk.vtkImageShiftScale()
        self.depthScaleFilter.SetScale(1.0)
        self.depthScaleFilter.SetOutputScalarTypeToDouble()

        self.depthImageLookupTable = lut
        self.imageMapToColors = vtk.vtkImageMapToColors()
        self.imageMapToColors.SetLookupTable(self.depthImageLookupTable)
        self.imageMapToColors.SetInputConnection(
            self.depthScaleFilter.GetOutputPort())

        self.imageView = imageview.ImageView()
        self.imageView.view.setWindowTitle('Depth image')
        self.imageView.setImage(self.imageMapToColors.GetOutput())

    def initPointCloudView(self):
        self.pointCloudView = PythonQt.dd.ddQVTKWidgetView()
        self.pointCloudView.setWindowTitle('Pointcloud')
        self.pointCloudViewBehaviors = viewbehaviors.ViewBehaviors(
            self.pointCloudView)

    def update(self):

        if not self.renderObserver:

            def onEndRender(obj, event):
                if self._block:
                    return
                if not self.singleShotTimer.singleShotTimer.isActive():
                    self.singleShotTimer.singleShot(0)

            self.renderObserver = self.view.renderWindow().AddObserver(
                'EndEvent', onEndRender)

        if not self.pointCloudView.visible and not self.imageView.view.visible:
            return

        self._block = True
        self.view.forceRender()
        self.updateBufferImages()
        self._block = False

        depthImage, polyData = computeDepthImageAndPointCloud(
            self.getDepthBufferImage(), self.getColorBufferImage(),
            self.view.camera())

        self.depthScaleFilter.SetInputData(depthImage)
        self.depthScaleFilter.Update()

        self.depthImageLookupTable.SetRange(
            self.depthScaleFilter.GetOutput().GetScalarRange())
        self.imageMapToColors.Update()
        self.imageView.resetCamera()
        #self.imageView.view.render()

        if not self.pointCloudObj:
            self.pointCloudObj = vis.showPolyData(polyData,
                                                  'point cloud',
                                                  colorByName='rgb',
                                                  view=self.pointCloudView,
                                                  parent=self.parentFolder)
        else:
            self.pointCloudObj.setPolyData(polyData)
        self.pointCloudView.render()
        if self._updateFunc:
            self._updateFunc()

    def addViewsToDock(self, app):
        for view in [self.imageView.view, self.pointCloudView]:
            dock = app.addWidgetToDock(view, QtCore.Qt.RightDockWidgetArea)
            dock.setMinimumWidth(300)
            dock.setMinimumHeight(300)
예제 #14
0
class DepthScanner(object):

    def __init__(self, view):
        self.view = view

        self.depthImage = None
        self.pointCloudObj = None
        self.renderObserver = None
        self.parentFolder = 'depth scanner'

        self.windowToDepthBuffer = vtk.vtkWindowToImageFilter()
        self.windowToDepthBuffer.SetInput(self.view.renderWindow())
        self.windowToDepthBuffer.SetInputBufferTypeToZBuffer()
        self.windowToDepthBuffer.ShouldRerenderOff()

        self.windowToColorBuffer = vtk.vtkWindowToImageFilter()
        self.windowToColorBuffer.SetInput(self.view.renderWindow())
        self.windowToColorBuffer.SetInputBufferTypeToRGB()
        self.windowToColorBuffer.ShouldRerenderOff()

        useBackBuffer = False
        if useBackBuffer:
            self.windowToDepthBuffer.ReadFrontBufferOff()
            self.windowToColorBuffer.ReadFrontBufferOff()

        self.initDepthImageView()
        self.initPointCloudView()

        self._block = False
        self.singleShotTimer = TimerCallback()
        self.singleShotTimer.callback = self.update
        self._updateFunc = None

    def getDepthBufferImage(self):
        return self.windowToDepthBuffer.GetOutput()

    def getDepthImage(self):
        return self.depthScaleFilter.GetOutput()

    def getColorBufferImage(self):
        return self.windowToColorBuffer.GetOutput()

    def updateBufferImages(self):
        for f in [self.windowToDepthBuffer, self.windowToColorBuffer]:
            f.Modified()
            f.Update()

    def initDepthImageView(self):

        self.depthImageColorByRange = [0.0, 4.0]

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0, 0.667) # red to blue
        lut.SetRange(self.depthImageColorByRange) # map red (near) to blue (far)
        lut.SetRampToLinear()
        lut.Build()

        self.depthScaleFilter = vtk.vtkImageShiftScale()
        self.depthScaleFilter.SetScale(1.0)
        self.depthScaleFilter.SetOutputScalarTypeToDouble()

        self.depthImageLookupTable = lut
        self.imageMapToColors = vtk.vtkImageMapToColors()
        self.imageMapToColors.SetLookupTable(self.depthImageLookupTable)
        self.imageMapToColors.SetInputConnection(self.depthScaleFilter.GetOutputPort())

        self.imageView = imageview.ImageView()
        self.imageView.view.setWindowTitle('Depth image')
        self.imageView.setImage(self.imageMapToColors.GetOutput())

    def initPointCloudView(self):
        self.pointCloudView = PythonQt.dd.ddQVTKWidgetView()
        self.pointCloudView.setWindowTitle('Pointcloud')
        self.pointCloudViewBehaviors = viewbehaviors.ViewBehaviors(self.pointCloudView)

    def update(self):

        if not self.renderObserver:
            def onEndRender(obj, event):
                if self._block:
                    return
                if not self.singleShotTimer.singleShotTimer.isActive():
                    self.singleShotTimer.singleShot(0)
            self.renderObserver = self.view.renderWindow().AddObserver('EndEvent', onEndRender)

        if not self.pointCloudView.visible and not self.imageView.view.visible:
            return

        self._block = True
        self.view.forceRender()
        self.updateBufferImages()
        self._block = False

        depthImage, polyData = computeDepthImageAndPointCloud(self.getDepthBufferImage(), self.getColorBufferImage(), self.view.camera())

        self.depthScaleFilter.SetInputData(depthImage)
        self.depthScaleFilter.Update()

        self.depthImageLookupTable.SetRange(self.depthScaleFilter.GetOutput().GetScalarRange())
        self.imageMapToColors.Update()
        self.imageView.resetCamera()
        #self.imageView.view.render()

        if not self.pointCloudObj:
            self.pointCloudObj = vis.showPolyData(polyData, 'point cloud', colorByName='rgb', view=self.pointCloudView, parent=self.parentFolder)
        else:
            self.pointCloudObj.setPolyData(polyData)
        self.pointCloudView.render()
        if self._updateFunc:
            self._updateFunc()

    def addViewsToDock(self, app):
        for view in [self.imageView.view, self.pointCloudView]:
            dock = app.addWidgetToDock(view, QtCore.Qt.RightDockWidgetArea)
            dock.setMinimumWidth(300)
            dock.setMinimumHeight(300)