示例#1
0
    def saveAboveTablePolyData(self):
        aboveTablePolyDataRaw = filterUtils.transformPolyData(
            self.aboveTablePolyData,
            self.firstFrameToWorldTransform.GetLinearInverse())

        ioUtils.writePolyData(aboveTablePolyDataRaw,
                              self.pathDict['aboveTablePointcloud'])
示例#2
0
 def getFilesystemFilename(self, meshId):
     if meshId in self.meshes:
         filename = os.path.join(self.cacheDirectory, '%s.%s' % (meshId, self.cacheDataType))
         if not os.path.isfile(filename):
             ioUtils.writePolyData(self.get(meshId), filename)
         return filename
     return None
示例#3
0
def saveConvexHulls(chulls, outputDir):

    if os.path.isdir(outputDir):
        print 'removing directory:', outputDir
        shutil.rmtree(outputDir)

    print 'making directory:', outputDir
    os.makedirs(outputDir)

    for i, chull in enumerate(chulls):

        chull, plane = chull.convexHull, chull.plane
        origin = plane.GetOrigin()
        normal = plane.GetNormal()
        chullPoints = vnp.getNumpyFromVtk(chull, 'Points')

        assert np.allclose(np.linalg.norm(normal), 1.0)

        output = np.vstack([normal, chullPoints])
        outputFilename = os.path.join(outputDir, 'plane_%04d.txt' % i)

        np.savetxt(outputFilename, output)

    ioUtils.writePolyData(getMergedConvexHullsMesh(chulls),
                          os.path.join(outputDir, 'merged_planes.ply'))
示例#4
0
def saveObjectPolyData(objectName):
    visObj = om.findObjectByName(objectName)
    filename = os.path.join(getLabelFusionDataDir(), 'object-meshes',
                            objectName + '_aligned.vtp')
    polyData = filterUtils.transformPolyData(visObj.polyData,
                                             visObj.actor.GetUserTransform())
    ioUtils.writePolyData(polyData, filename)
示例#5
0
 def getFilesystemFilename(self, meshId):
     if meshId in self.meshes:
         filename = os.path.join(self.cacheDirectory,
                                 '%s.%s' % (meshId, self.cacheDataType))
         if not os.path.isfile(filename):
             ioUtils.writePolyData(self.get(meshId), filename)
         return filename
     return None
示例#6
0
 def save_poly_data(self, filename):
     """
     Save the poly data to a file
     :param filename:
     :type filename:
     :return:
     :rtype:
     """
     ioUtils.writePolyData(self.poly_data, filename)
示例#7
0
    def save_snapshot(self):
        save_dir = os.path.join(spartan_utils.get_sandbox_dir(), "pointclouds")
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        for topic, data in self._subscribers.iteritems():
            filename = os.path.join(save_dir, "%s.ply" % (data['name']))
            filename.replace(" ", "_")
            ioUtils.writePolyData(data['pointcloud'], filename)
示例#8
0
    def saveCurrentScene(self):
        location = str(self.ui.saveLocation.text)
        with open(location + ".json", 'w') as outfile:
            json.dump(self.objects, outfile, cls=MyEncoder)

        obj = om.findObjectByName("data files").children()[0]
        pd = obj.polyData
        ioUtils.writePolyData(pd, location + ".vtk")
        print 'saved:', location + ".vtk"
示例#9
0
    def run(scenePointCloud,
            modelPointCloud,
            overlap=0.9,
            distance=0.02,
            timeout=1000,
            numSamples=200):
        """

        :param scenePointCloud:
        :param modelPointCloud:
        :return: transform from scenePointCloud --> modelPointCloud. It is a vtkTransform
        """
        baseName = GlobalRegistrationUtils.getSandboxDir()
        modelFile = os.path.join(baseName, 'model_data_for_pcs4.ply')
        sceneFile = os.path.join(baseName, 'scene_data_for_pcs4.ply')

        ioUtils.writePolyData(modelPointCloud, modelFile)
        ioUtils.writePolyData(scenePointCloud, sceneFile)

        super4PCSBaseDir = utils.getSuper4PCSBaseDir()
        registrationBin = os.path.join(super4PCSBaseDir, 'build/Super4PCS')
        outputFile = os.path.join(utils.getLabelFusionBaseDir(),
                                  'sandbox/pcs4_mat_output.txt')

        print "number of scene points = ", scenePointCloud.GetNumberOfPoints()
        print "number of model points = ", modelPointCloud.GetNumberOfPoints()

        registrationArgs = [
            registrationBin, '-i', modelFile, sceneFile,
            '-o %f' % overlap,
            '-d %f' % distance,
            '-t %d' % timeout,
            '-n %d' % numSamples, '-r pcs4_transformed_output.ply',
            '-m %s' % outputFile
        ]

        registrationArgs = ' '.join(registrationArgs).split()

        if os.path.isfile(outputFile):
            print 'removing', outputFile
            os.remove(outputFile)

        print 'calling super pcs4...'
        print
        print ' '.join(registrationArgs)

        startTime = time.time()
        subprocess.check_call(registrationArgs)
        elapsedTime = time.time() - startTime
        print "SuperPCS4 took " + str(elapsedTime) + " seconds"

        print 'done.'
        transform = Super4PCS.getTransformFromFile(outputFile)
        return transform
示例#10
0
def onFileSaveData():

    obj = om.getActiveObject()
    if not obj:
        app.showErrorMessage('Please select an object', title='No object selected')
        return
    if isinstance(obj, otdfmodel.OtdfModelItem):
        mainWindow = app.getMainWindow()
        filename = QtGui.QFileDialog.getSaveFileName(mainWindow, "Save Data...", getDefaultDirectory(), 'OTDF (*.otdf)', 'OTDF (*.otdf)')

        if not os.path.splitext(filename)[1]:
            filename += '.otdf'

        storeDefaultDirectory(filename)
        otdfString = obj.parser.getUpdatedOtdf()
        otdfFile = open(filename, 'w')
        otdfFile.write(otdfString)
        otdfFile.close()
    elif hasattr(obj, 'polyData'):
        mainWindow = app.getMainWindow()
        fileFilters = "PLY (*.ply);;STL (*.stl);;VTP (*.vtp)";
        filename = QtGui.QFileDialog.getSaveFileName(mainWindow, "Save Data...", getDefaultDirectory(), fileFilters, 'VTP (*.vtp)')

        if not filename:
            return

        if not os.path.splitext(filename)[1]:
            filename += '.vtp'

        polyData = io.writePolyData(obj.polyData, filename)
    else:
        app.showErrorMessage('Please select an object that contains geometry data or an OTDF object', title='Invalid object selected')
        return

    storeDefaultDirectory(filename)
示例#11
0
    def run(scenePointCloud, modelPointCloud):
        """

        :param scenePointCloud:
        :param modelPointCloud:
        :return: transform from scenePointCloud --> modelPointCloud. It is a vtkTransform
        """
        baseName = os.path.join(CorlUtils.getCorlBaseDir(), 'sandbox')
        modelFile = os.path.join(baseName, 'model_data_for_pcs4.ply')
        sceneFile = os.path.join(baseName, 'scene_data_for_pcs4.ply')

        ioUtils.writePolyData(modelPointCloud, modelFile)
        ioUtils.writePolyData(scenePointCloud, sceneFile)

        super4PCSBaseDir = CorlUtils.getSuper4PCSBaseDir()
        registrationBin = os.path.join(super4PCSBaseDir, 'build/Super4PCS')
        outputFile = os.path.join(CorlUtils.getCorlBaseDir(),
                                  'sandbox/pcs4_mat_output.txt')
        overlap = 0.9
        distance = 0.02
        timeout = 1000
        numSamples = 200

        registrationArgs = [
            registrationBin, '-i', modelFile, sceneFile,
            '-o %f' % overlap,
            '-d %f' % distance,
            '-t %d' % timeout,
            '-n %d' % numSamples, '-r pcs4_transformed_output.ply',
            '-m %s' % outputFile
        ]

        registrationArgs = ' '.join(registrationArgs).split()

        if os.path.isfile(outputFile):
            print 'removing', outputFile
            os.remove(outputFile)

        print 'calling super pcs4...'
        print
        print ' '.join(registrationArgs)

        subprocess.check_call(registrationArgs)

        print 'done.'
        transform = SuperPCS4.getTransformFromFile(outputFile)
        return transform
示例#12
0
def saveObject(visObj, filename=None, overwrite=False, pathToDir='handheld-scanner'):
    if filename is None:
        filename = visObj.getProperty('Name') + '.vtp'

    filename = os.path.join(getLabelFusionDataDir(),'object-meshes', pathToDir, filename)
    polyData = visObj.polyData

    if not overwrite:
        if os.path.exists(filename):
            raise ValueError('file already exists, not overwriting')
            return

    userTransform = visObj.actor.GetUserTransform()
    if userTransform is not None:
        polyData = filterUtils.transformPolyData(polyData, visObj.actor.GetUserTransform())

    ioUtils.writePolyData(polyData, filename)
def saveConvexHulls(chulls, outputDir):

    if os.path.isdir(outputDir):
        print 'removing directory:', outputDir
        shutil.rmtree(outputDir)

    print 'making directory:', outputDir
    os.makedirs(outputDir)

    for i, chull in enumerate(chulls):

        chull, plane = chull.convexHull, chull.plane
        origin = plane.GetOrigin()
        normal = plane.GetNormal()
        chullPoints = vnp.getNumpyFromVtk(chull, 'Points')

        assert np.allclose(np.linalg.norm(normal), 1.0)

        output = np.vstack([normal, chullPoints])
        outputFilename = os.path.join(outputDir, 'plane_%04d.txt' % i)

        np.savetxt(outputFilename, output)

    ioUtils.writePolyData(getMergedConvexHullsMesh(chulls),  os.path.join(outputDir, 'merged_planes.ply'))
示例#14
0
def onFileSaveData():

    obj = om.getActiveObject()
    if not obj:
        app.showErrorMessage('Please select an object',
                             title='No object selected')
        return
    if isinstance(obj, otdfmodel.OtdfModelItem):
        mainWindow = app.getMainWindow()
        filename = QtGui.QFileDialog.getSaveFileName(mainWindow,
                                                     "Save Data...",
                                                     getDefaultDirectory(),
                                                     'OTDF (*.otdf)',
                                                     'OTDF (*.otdf)')

        if not os.path.splitext(filename)[1]:
            filename += '.otdf'

        storeDefaultDirectory(filename)
        otdfString = obj.parser.getUpdatedOtdf()
        otdfFile = open(filename, 'w')
        otdfFile.write(otdfString)
        otdfFile.close()
    elif hasattr(obj, 'polyData'):
        mainWindow = app.getMainWindow()
        fileFilters = "PLY (*.ply);;STL (*.stl);;VTP (*.vtp);;VTK (*.vtk)"
        defaultFilter = 'VTP (*.vtp)'
        filename = QtGui.QFileDialog.getSaveFileName(mainWindow,
                                                     "Save Data...",
                                                     getDefaultDirectory(),
                                                     fileFilters,
                                                     defaultFilter)

        if not filename:
            return

        if not os.path.splitext(filename)[1]:
            filename += '.vtp'

        polyData = io.writePolyData(obj.polyData, filename)
    else:
        app.showErrorMessage(
            'Please select an object that contains geometry data or an OTDF object',
            title='Invalid object selected')
        return

    storeDefaultDirectory(filename)
        vis.showPolyData(polyData, baseName + ' merged', parent=folder, visible=False)

        print '  total points:', polyData.GetNumberOfPoints()

        # compute centroid and subtract from points to move the mesh to the origin
        origin = np.array(filterUtils.computeCentroid(polyData))
        t = transformUtils.frameFromPositionAndRPY(-origin, [0.0, 0.0, 0.0])
        for obj in folder.children():
            obj.setPolyData(filterUtils.transformPolyData(obj.polyData, t))

        return folder.children()[-1].polyData



    app = mainwindowapp.construct(globals())

    outDir = args.output_dir
    if not os.path.isdir(outDir):
        os.makedirs(outDir)

    for filename in args.filename:
        print 'reading:', filename
        polyData = loadObjFile(filename)
        outFile = os.path.splitext(os.path.basename(filename))[0] + '.vtp'
        outFile = os.path.join(outDir, outFile)
        print 'writing:', outFile
        ioUtils.writePolyData(polyData, outFile)

    if not args.no_window:
        app.app.start()
示例#16
0
 def savePointCloud(self):
     objectPointCloud = om.findObjectByName('cropped pointcloud').polyData
     ioUtils.writePolyData(objectPointCloud,
                           self.pathDict['objectPointcloud'])
file and re-save it as an ascii ply file.
'''


import os
from director import ioUtils
from director import vtkNumpy as vnp


if __name__ == '__main__':

    filename = sys.argv[1]
    outputFilename = os.path.splitext(filename)[0] + '.vtp'


    print "reading poly data"
    polyData = ioUtils.readPolyData(filename)
    print "finished reading poly data"

    # TODO:
    # This should just be fixed in ioUtils.readPolyData, but for now
    # there is a workaround for an issue with the ply reader.
    # The output of the ply reader has points but not vertex cells,
    # so create a new polydata with vertex cells and copy the cells over.
    points = vnp.getNumpyFromVtk(polyData, 'Points')
    newPolyData = vnp.numpyToPolyData(points, createVertexCells=True)
    polyData.SetVerts(newPolyData.GetVerts())

    print 'writing:', outputFilename
    ioUtils.writePolyData(polyData, outputFilename)
示例#18
0
Note, the ply file needs to be in ascii format and not
binary.  The vtk ply reader seems to crash on binary
ply files.  You can use meshlab to open a binary ply
file and re-save it as an ascii ply file.
'''

import os
from director import ioUtils
from director import vtkNumpy as vnp

if __name__ == '__main__':

    filename = sys.argv[1]
    outputFilename = os.path.splitext(filename)[0] + '.vtp'

    print("reading poly data")
    polyData = ioUtils.readPolyData(filename)
    print("finished reading poly data")

    # TODO:
    # This should just be fixed in ioUtils.readPolyData, but for now
    # there is a workaround for an issue with the ply reader.
    # The output of the ply reader has points but not vertex cells,
    # so create a new polydata with vertex cells and copy the cells over.
    points = vnp.getNumpyFromVtk(polyData, 'Points')
    newPolyData = vnp.numpyToPolyData(points, createVertexCells=True)
    polyData.SetVerts(newPolyData.GetVerts())

    print('writing:', outputFilename)
    ioUtils.writePolyData(polyData, outputFilename)