예제 #1
0
 def getEdges(self, scale, thresholdFactor):
     laplacianOfGaussian = ndimage.gaussian_laplace(self._image, scale)  # ish 0.57 seconds
     zeroCrossings = _findZeroCrossings(laplacianOfGaussian, thresholdFactor)  # ish 0.25 sec
     result = PointCloud()
     for x, y in zip(zeroCrossings[0], zeroCrossings[1]):
         result.addXY(float(x), float(y))
     return result
예제 #2
0
def produce_normal_file(data_dir):
    filelist = glob2.glob(data_dir + '/**/*_rgb.png')
    print('Total {} images'.format(len(filelist)))

    for curidx in range(len(filelist)):
        if curidx % 100 == 0:
            print('Processing image number', curidx)
        name = filelist[curidx]
        frameindex = name[-12:-8]
        # name = '/home/sicong/detail_data/data/3/0235_rgb.png'
        try:
            img_full = io.imread(name)
        except:
            continue
        depth_full = io.imread(name[0:-8] + '_depth.png')
        depthcount = np.sum(depth_full > 100)
        if depthcount < 100 * 100:
            continue
        rot = 0
        scale = util.getScale_detail(depth_full)
        center = util.getCenter_detail(depth_full)
        if (center[0] < 1 or center[1] < 1 or center[1] > img_full.shape[0]
                or center[0] > img_full.shape[1]):
            continue

        ori_mask = depth_full > 100
        pcd = PointCloud(np.expand_dims(depth_full, 0),
                         np.expand_dims(ori_mask, 0))
        ori_normal = pcd.get_normal().squeeze(0)
        gt_normal = util_detail.cropfor3d(ori_normal, center, scale, rot, 256,
                                          'nearest')
        gt_normal = normal_util.normalize(gt_normal)
        normal_file_name = name[0:-8] + '_normal.npy'
        np.save(normal_file_name, gt_normal)
예제 #3
0
class MostPopulatedCircleStage:
    def __init__(self, radius):
        self._radius = radius
        self._executionResult = None

    def execute(self, pointCloud):
        mostPopulatedCircleFinder = MostPopulatedCircleFinder(
            pointCloud.asNumpyArray())
        center = mostPopulatedCircleFinder.get(self._radius)
        squareRadius = self._radius**2
        self._executionResult = PointCloud()
        for point in pointCloud:
            diff = point - center
            normSquare = diff[0]**2 + diff[1]**2
            if normSquare <= squareRadius:
                self._executionResult.addPoint(point)
        return self._executionResult

    def getImageRepresentation(self):
        return PointCloudToRgbImage(self._executionResult, 0)

    def __ne__(self, other):
        if type(self) != type(other):
            return True
        return self._radius != other._radius
예제 #4
0
 def test_simple(self):
     encoder = PointCloudJsonEncoder()
     cloud = PointCloud()
     cloud.addXY(0.0, 1.0)
     cloud.addXY(2.0, 3.0)
     jsonDict = encoder.default(cloud)
     self.assertEqual(jsonDict, {'__type__': 'PointCloud',
                                 'points': [{'x': 0.0, 'y': 1.0}, {'x': 2.0, 'y': 3.0}]})
예제 #5
0
 def execute(self, pointCloud):
     mean = pointCloud.mean()
     self._executionResult = PointCloud()
     radiusSquare = self._radius**2
     for x, y in pointCloud:
         squareDistanceFromMean = float((x - mean[0])**2 + (y - mean[1])**2)
         if squareDistanceFromMean <= radiusSquare:
             self._executionResult.addXY(float(x), float(y))
     return self._executionResult
예제 #6
0
    def dict_to_object(self, d):
        if "__type__" not in d:
            return d

        if d["__type__"] == "PointCloud":
            result = PointCloud()
            for point in d["points"]:
                result.addXY(point["x"], point["y"])
            return result

        return d
예제 #7
0
 def __init__(self):
     super().__init__()
     self._images = []
     self._filenames = []
     self._noPointClouds = {}
     self._yesPointClouds = {}
     self._activeFilename = ""
     self._activeYesPointCloud = PointCloud()
     self._activeNoPointCloud = PointCloud()
     self._pipeline = None
     self._lastPipelineStage = None
예제 #8
0
 def execute(self, pointCloud):
     mostPopulatedCircleFinder = MostPopulatedCircleFinder(
         pointCloud.asNumpyArray())
     center = mostPopulatedCircleFinder.get(self._radius)
     squareRadius = self._radius**2
     self._executionResult = PointCloud()
     for point in pointCloud:
         diff = point - center
         normSquare = diff[0]**2 + diff[1]**2
         if normSquare <= squareRadius:
             self._executionResult.addPoint(point)
     return self._executionResult
예제 #9
0
파일: APTPosData.py 프로젝트: pnnl/apt
    def __init__(self):
        """
        Initialize APTPosData class need APT pos data (format [[x0,y0,z0,Da0],...])
        """
        PointCloud.__init__(self)
        APTMassSpec.__init__(self)

        self.pos = None
        self.identity = None
        self.rand_mass_label = None
        self._data_size = 0

        self._files = {'Data filename': None, 'RRNG filename': None}
예제 #10
0
def UnitTest():
    from PointCloud import PointCloud
    points = PointCloud()
    mean = [0, 0, 0]
    cov = [[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]] * np.array([0.01])
    p = np.random.multivariate_normal(mean, cov, 20000)
    points.AddPoints(np.array(p))
    tree = Octree(points)
    print "Printing tree directly:"
    print tree
    print "Printing tree by iterating through cells:"
    for cell in tree:
        print cell
예제 #11
0
    def generateGcode(self):

        if not "Nails" in self.parameters:
            return

        filename = QtGui.QFileDialog.getSaveFileName(self, "Generate Gcode",
                                                     "./", "gcode (*.tap)")[0]
        if not filename:
            return

        js = self.parameters["Nails"]
        nails = js["3:nails"]
        path = js["4:thread"]
        w = js["2:parameters:"]["proc_width"]
        h = js["2:parameters:"]["proc_height"]
        sf = Point2(1, 1) * self.scaleFactor * 1000.0 * js["2:parameters:"][
            "ppi"]  # pixels to millimeters

        origin = Point2(0, 0)
        pc = PointCloud(1, 1)
        pc.addFromList(nails)
        cp = pc.closestPoint(origin.x, origin.y)
        print "origin", nails[cp[0]]

        engine = Gc(nails,
                    path[:self.cutoffSlider.value()],
                    scaleFactor=sf,
                    origin=pc.p[cp[0]])
        code = engine.generateStringPath(
            os.path.basename(self.parameters["filename"]),
            startPosition=Point2(w * sf.x * .5, -5),
            minNailDistance=self.minNailDist)
        #code = engine.generateStringPath(os.path.basename(self.parameters["filename"]), nails, path[:400], self.minNailDist, scaleFactor=sf, origin=Point2(0,0), startPosition=Point2(0.5, -0.1)*w)
        spl = os.path.splitext(filename)
        filename = spl[0] + "_string" + spl[1]
        with open(filename, "w") as f:
            f.write(code)
            f.close()
            print "written gcode to", filename

        img = self.drawGcode(self.parameters["image"], code,
                             Point2(1.0 / sf.x, 1.0 / sf.y), Point2(0, 0))
        self.showImage(img)

        code = engine.generateDrillPattern(
            os.path.basename(self.parameters["filename"]), -6.0)
        filename = spl[0] + "_drills" + spl[1]
        with open(filename, "w") as f:
            f.write(code)
            f.close()
            print "written gcode to", filename
예제 #12
0
    def __init__(self, cloudState, parent=None):
        super().__init__(parent)
        '''
        list of images, click one and it shows
        save button
        pixels in left image exluded
        pixels in right image included
        mouse drag for include/exclude

        +--------------------------+
        |      |      | list       |
        | img1 | img2 | ...        |
        |      |      | button     |
        +--------------------------+
        horizontal layout
          img1 = label
          img2 = label
          vertical layout
            list = listwidget
            button
        '''
        mainWidget = QWidget(self)
        mainLayout = QHBoxLayout()
        listLayout = QVBoxLayout()
        self._noLabel = SelectableQLabel()
        self._yesLabel = SelectableQLabel()
        self._noLabel.rectangleSelected.connect(cloudState.noRectangle)
        self._yesLabel.rectangleSelected.connect(cloudState.yesRectangle)

        noPixmap = cloudToPixmap(PointCloud())
        yesPixmap = cloudToPixmap(PointCloud())

        self._noLabel.setBackgroundPixmap(noPixmap)
        self._yesLabel.setBackgroundPixmap(yesPixmap)

        self._noLabel.resize(PIXMAP_SIZE, PIXMAP_SIZE)
        self._yesLabel.resize(PIXMAP_SIZE, PIXMAP_SIZE)

        self._filenameList = QListWidget()
        self._filenameList.itemClicked.connect(cloudState.filenameClicked)
        self.setListItems(cloudState.getFilenames())
        self._saveButton = QPushButton("Save")
        self._saveButton.clicked.connect(cloudState.saveActiveCloud)
        mainLayout.addWidget(self._noLabel)
        mainLayout.addWidget(self._yesLabel)
        listLayout.addWidget(self._filenameList)
        listLayout.addWidget(self._saveButton)
        mainLayout.addLayout(listLayout)
        mainWidget.setLayout(mainLayout)

        self.setCentralWidget(mainWidget)
예제 #13
0
    def _trimEdges(self, cloud):
        newCloud = PointCloud()

        keepThreshold = self._edgeDetectionConfig.keepFactor
        accumulatedKeep = 0.0
        accumulatedKeepCorrection = 0.0
        for point in cloud:
            if accumulatedKeep - accumulatedKeepCorrection < keepThreshold:
                newCloud.addPoint(point)
        accumulatedKeep += keepThreshold

        if accumulatedKeep - accumulatedKeepCorrection >= 1.0:
            accumulatedKeepCorrection += 1.0

        return newCloud
예제 #14
0
    def calculateCOG(self):
        nailWeight = 9.9 / 100  #grams per nail
        threadWeightPerMeter = 40.0 / 1000  # g / m
        canvas_weight = 838  # grams

        if "Nails" in self.parameters:

            js = self.parameters["Nails"]
            w = js["2:parameters:"]["proc_width"]
            h = js["2:parameters:"]["proc_height"]
            sf = Point2(1,
                        1) * self.scaleFactor * 1000.0 * js["2:parameters:"][
                            "ppi"]  # pixels to millimeters
            origin = Point2(0, 0)
            pc = PointCloud(1, 1)
            pc.addFromList(js["3:nails"])
            #cp = pc.closestPoint(origin.x, origin.y)
            #origin = pc.p[cp[0]]
            pc.translate(-origin.x, -origin.y)
            pc.scale(sf.x, sf.y)

            # cog nails
            nails_cog = Point2(0, 0)
            nails_mass = nailWeight * len(pc.p)
            for p in pc.p:
                nails_cog += p
            nails_cog = nails_cog / len(pc.p)

            # cog thread
            path = js["4:thread"]
            cp = pc.p[path[0]]
            totalThreadLen = 0
            thread_cog = Point2(0, 0)
            for pid in path[1:]:
                nxt = pc.p[pid]
                l = cp.dist(nxt)
                totalThreadLen += l
                thread_cog += (cp + nxt) * 0.5 * l
                cp = nxt
            thread_cog /= totalThreadLen
            thread_mass = totalThreadLen / 1000 * threadWeightPerMeter

            # canvas cog
            canvas_cog = Point2(
                float(js["2:parameters:"]["proc_width"]) * sf.x,
                float(js["2:parameters:"]["proc_height"]) * sf.y) * 0.5

            print "canvas:", canvas_weight, "g"
            print "nails:", nails_mass, "g"
            print "thread:", thread_mass, "g"
            print "canvas cog:", canvas_cog
            print "nails cog:", nails_cog
            print "thread cog:", thread_cog

            combined_cog = (canvas_cog * canvas_weight +
                            nails_cog * nails_mass + thread_cog * thread_mass)
            combined_cog /= canvas_weight + nails_mass + thread_mass
            print "overall COG", combined_cog
예제 #15
0
 def measure_depth(self):
     self.rgb, self.depth = self.depth_camera.capture_images()
     self.point_cloud = PointCloud.from_depth(self.depth).\
         select_roi(self.shift,
                    self.rotation,
                    self.borders)
     return self.point_cloud
예제 #16
0
    def test_AddPoints(self):
        c = PointCloud()
        c.addPoint([1.0, 2.0])
        c.addXY(3.0, 4.0)

        points = [p for p in c]
        self.assertEquals(points[0][0], 1.0)
        self.assertEquals(points[0][1], 2.0)
        self.assertEquals(points[1][0], 3.0)
        self.assertEquals(points[1][1], 4.0)
        self.assertEquals(c.max(), (3.0, 4.0))
        self.assertEquals(c.min(), (1.0, 2.0))
        self.assertEquals(c.mean(), (2.0, 3.0))
예제 #17
0
 def test_wuerfel_normalize(self):
     #for file in ['data/line_points.raw']:
     for file in ['data/wuerfel5_points.raw', 'data/wuerfel5-allpos_points.raw', 'data/wuerfel5-allneg_points.raw', 'data/wuerfel10_points.raw']:
         pc = PointCloud()
         pc.readRaw(file)
         pcn = pc.normalized()
     
         bb = pcn.getBoundingBox()
         self.assertEqual(1.0, bb['x'])
         self.assertEqual(1.0, bb['y'])
         self.assertEqual(1.0, bb['z'])
         self.assertEqual(-1.0, bb['-x'])
         self.assertEqual(-1.0, bb['-y'])
         self.assertEqual(-1.0, bb['-z'])
         
         self.assertEqual(2.0, pcn.getXSize())
         self.assertEqual(2.0, pcn.getYSize())
         self.assertEqual(2.0, pcn.getZSize())
def get_pc_image(pc: PointCloud):
    ax = plt.axes(projection="3d")
    pc = pc.filter()
    ax.scatter3D(pc[:, 0],
                 pc[:, 1],
                 pc[:, 2],
                 c=pc[:, 2], cmap='hsv')
    ax.set_title("3D plot")
    ax.view_init(55, 45)
    plt.savefig("plot.png")
    rgb = cv2.cvtColor(cv2.imread("plot.png"), cv2.COLOR_BGR2RGB)
    return rgb
예제 #19
0
파일: Clustering.py 프로젝트: pnnl/apt
    def ion_selection(self, selected_ion_types):
        """
        Select ion types in the rng file for clustering. 

        select_ion_types:
            a list/array of ion types to be selected. \
            To select specific ions, use format ['A1B1', 'C2', ...];
            To select all ions, regardless of ranged or not ranged, use 'all';
            To select all ranged ions, use 'Ranged';
            To select all unranged ions, use 'Noise';

        """
        self._paras['selected ions for clustering'] = selected_ion_types
        selection = self.APTPosData.select_ions(selected_ion_types)

        selected_pos = self.APTPosData.pos[selection]
        self.current_PointCloud_ion_identity = self.APTPosData.identity[
            selection]

        self.current_PointCloud = PointCloud()
        self.current_PointCloud.init_point_cloud(selected_pos)
        self.cluster_id = -np.ones(len(selected_pos), dtype=int)
예제 #20
0
    def execute(self, pointCloud):
        print("Executing fraction point remover stage")
        '''
        I really don't know why this method works so well, except for threshold 0.8 or 0.2,
        but I'm keeping it since it seems to work very well for everything else,
        and 0.8 and 0.2 are off by 2 at most.
        '''
        newCloud = PointCloud()

        keepThreshold = self._keepFraction
        accumulatedKeep = 0.0
        accumulatedKeepCorrection = 0.0
        for point in pointCloud:
            if accumulatedKeep - accumulatedKeepCorrection < keepThreshold:
                newCloud.addPoint(point)
            accumulatedKeep += keepThreshold

            if accumulatedKeep - accumulatedKeepCorrection >= 1.0:
                accumulatedKeepCorrection += 1.0

        self._executionResult = newCloud
        return self._executionResult
예제 #21
0
    def checkNails(self):

        if "Nails" in self.parameters:
            nails = self.parameters["Nails"]["3:nails"]
            pc = PointCloud(10, 10)
            print "list", nails
            pc.addFromList(nails)
            print pc.p
            img = self.parameters["image"]

            draw = ImageDraw.Draw(img)
            min_dist = 1000
            for i, p in enumerate(pc.p):
                np, d = pc.closestPoint(p.x, p.y, i)
                min_dist = min(min_dist, d)
                if d < self.minNailDist:
                    draw.rectangle((p.x - 3, p.y - 3, p.x + 3, p.y + 3),
                                   outline=(255, 0, 0))

            print "minDist:", min_dist * 1000.0 * self.parameters["Nails"][
                "2:parameters:"]["ppi"], "mm"
            self.showImage(img)
예제 #22
0
class KeepInsideRadiusStage:
    def __init__(self, radius):
        self._radius = radius
        self._executionResult = None

    def execute(self, pointCloud):
        mean = pointCloud.mean()
        self._executionResult = PointCloud()
        radiusSquare = self._radius**2
        for x, y in pointCloud:
            squareDistanceFromMean = float((x - mean[0])**2 + (y - mean[1])**2)
            if squareDistanceFromMean <= radiusSquare:
                self._executionResult.addXY(float(x), float(y))
        return self._executionResult

    def getImageRepresentation(self):
        return PointCloudToRgbImage(self._executionResult, 0)

    def __ne__(self, other):
        if type(self) != type(other):
            return True
        return self._radius != other._radius
예제 #23
0
    def test_SimpleWrite(self):
        cloud = PointCloud()
        cloud.addXY(0.0, 0.0)
        cloud.addXY(1.0, 2.0)

        writeable = self.StringStorer()
        PointCloudHandler.savePointCloudToWriteable(cloud, writeable)

        oneString = "".join(writeable.strings)
        expectedString = '{\n'\
                         '  "__type__": "PointCloud",\n'\
                         '  "points": [\n'\
                         '    {\n'\
                         '      "x": 0.0,\n'\
                         '      "y": 0.0\n'\
                         '    },\n'\
                         '    {\n'\
                         '      "x": 1.0,\n'\
                         '      "y": 2.0\n'\
                         '    }\n'\
                         '  ]\n'\
                         '}'
        self.assertEquals(oneString, expectedString)
예제 #24
0
def exchangePoints(fromCloud, toCloud, coordinates):
    xBox = sorted([coordinates[1], coordinates[3]])
    yBox = sorted([coordinates[0], coordinates[2]])
    retFromCloud = PointCloud()

    # TODO: Break out duplicated code.
    xMin, yMin = fromCloud.min()
    xMax, yMax = fromCloud.max()
    xCenter = (xMin + xMax) / 2
    yCenter = (yMin + yMax) / 2
    width = xMax - xMin
    height = yMax - yMin
    size = max(width, height)

    for point in fromCloud:
        x = (point[0] - xCenter) / size * PIXMAP_SIZE + PIXMAP_SIZE / 2
        y = (point[1] - yCenter) / size * PIXMAP_SIZE + PIXMAP_SIZE / 2

        if (x >= xBox[0] and x <= xBox[1] and y >= yBox[0] and y <= yBox[1]):
            toCloud.addPoint(point)
        else:
            retFromCloud.addPoint(point)
    return retFromCloud, toCloud
def plot_point_cloud(point_cloud: PointCloud, figure=None):
    if not figure:
        figure = plt.figure()
        plt.ion()
    ax = plt.axes(projection="3d")
    pc = point_cloud.filter()
    ax.scatter3D(pc[:, 0],
                 pc[:, 1],
                 pc[:, 2],
                 c=pc[:, 2], cmap='hsv')
    ax.set_title("3D plot")
    plt.show()
    plt.draw()
    plt.pause(0.001)
    return figure
예제 #26
0
def get_train_valid_loader(semantic_dir,
                           random_seed=42,
                           batch_size=1,
                           valid_size=0.34,
                           shuffle=True,
                           semi=True,
                           pc_size=500000,
                           binary=True,
                           cat=0,
                           num_workers=4,
                           pin_memory=False):
    error_msg = "[!] valid_size should be in the range [0, 1]."
    assert ((valid_size >= 0) and (valid_size <= 1)), error_msg

    # load dataset
    dataset = PointCloud(semantic_dir, semi, pc_size, binary, cat)

    num_train = len(dataset)
    indices = list(range(num_train))
    split = int(np.floor(valid_size * num_train))

    if shuffle:
        np.random.seed(random_seed)
        np.random.shuffle(indices)

    train_idx, valid_idx = indices[split:], indices[:split]

    train_sampler = SubsetRandomSampler(train_idx)
    valid_sampler = SubsetRandomSampler(valid_idx)

    train_loader = torch.utils.data.DataLoader(
        dataset,
        batch_size=batch_size,
        sampler=train_sampler,
        num_workers=num_workers,
        pin_memory=pin_memory,
    )

    valid_loader = torch.utils.data.DataLoader(
        dataset,
        batch_size=batch_size,
        sampler=valid_sampler,
        num_workers=num_workers,
        pin_memory=pin_memory,
    )

    return (train_loader, valid_loader)
예제 #27
0
def main(input, class_id, alpha=.1, output=None, show_plots=False):
    pc = PointCloud(infile=input)
    pc.classifier = 'rf_classifier.sav'
    pc.run_classifier()
    pc.group_class(class_id)
    if output is None:
        output = input.split('/')[-1].split('.')[0]
    w = shapefile.Writer('output/{0}/{0}_{1}'.format(output, class_decode[class_id]), shapeType=15)
    w.autoBalance = 1
    w.field("CLASS")
    for i in range(max(pc.class_groups)):
        z = pc.group_height(i)
        points = pc.group_geom(i)
        if show_plots==True:
            x = [p.coords.xy[0] for p in points]
            y = [p.coords.xy[1] for p in points]
        if len(points) < 5:
            continue
        concave_hull, _ = alpha_shape(points, alpha=alpha)
        counter = 0
        al = alpha
        while concave_hull.type == 'MultiPolygon' and counter < 10:
            al = al/2
            concave_hull, _ = alpha_shape(points, al)
            counter += 1
        if concave_hull.type == 'MultiPolygon':
            continue
        if len(concave_hull.bounds) > 0:
            x, y = concave_hull.exterior.coords.xy
            points = []
            for j in range(len(x)):
                points.append((x[j], y[j], z))
            w.record(class_id)
            w.polyz([points])
            if show_plots==True:
                #plot_polygon(concave_hull)
                _ = pl.plot(x, y, 'o', color='#f16824')
                pl.show()
    w.close()
예제 #28
0
 def test_wuerfel5(self):
     pc = PointCloud()
     pc.readRaw('data/wuerfel5_points.raw')
     
     bb = pc.getBoundingBox()
     self.assertEqual(5.0, bb['x'])
     self.assertEqual(5.0, bb['y'])
     self.assertEqual(0.0, bb['z'])
     self.assertEqual(0.0, bb['-x'])
     self.assertEqual(0.0, bb['-y'])
     self.assertEqual(-5.0, bb['-z'])
     
     self.assertEqual(5.0, pc.getXSize())
     self.assertEqual(5.0, pc.getYSize())
     self.assertEqual(5.0, pc.getZSize())
예제 #29
0
 def _resetPointClouds(self):
     print("reset point clouds")
     if (self._pipeline is not None
             and self._lastPipelineStage is not None):
         self._yesPointClouds = {}
         self._noPointClouds = {}
         for filename, img in zip(self._filenames, self._images):
             pointCloud = self._pipeline.executeUntilRaw(
                 self._lastPipelineStage, qImageToMatrix(img))
             if type(pointCloud) is PointCloud:
                 print("Added point cloud with size:", pointCloud.size())
                 self._noPointClouds[filename] = pointCloud
                 self._yesPointClouds[filename] = PointCloud()
         if len(self._filenames) > 0:
             self._activeFilename = self._filenames[0]
             self._activeYesPointCloud = self._yesPointClouds[
                 self._activeFilename]
             self._activeNoPointCloud = self._noPointClouds[
                 self._activeFilename]
             self.activePointCloudsChanged.emit(
                 (self._activeNoPointCloud, self._activeYesPointCloud))
예제 #30
0
    def test_SimpleImage(self):
        simpleImage = np.zeros((12, 12))
        simpleImage[1, 1] = 255

        expectedPointCloud = PointCloud()
        expectedPointCloud.addXY(0.5, 0.0)
        expectedPointCloud.addXY(1.5, 2.0)
        expectedPointCloud.addXY(0.0, 0.5)
        expectedPointCloud.addXY(2.0, 1.5)

        e = EdgeDetector(simpleImage)
        pointCloud = e.getEdges(1.0, 17.0)

        for point, expectedPoint in zip(pointCloud, expectedPointCloud):
            self.assertEqual(point[0], expectedPoint[0])
            self.assertEqual(point[1], expectedPoint[1])
예제 #31
0
    def test_ToRgb(self):
        c = PointCloud()
        image = PointCloudToRgbImage(c, 0)
        rows, cols, channels = image.shape
        self.assertEquals(channels, 3)
        for element in np.nditer(image):
            self.assertEquals(element, 0.0)

        c.addXY(0.0, 0.0)
        c.addXY(10.0, 10.0)
        image = PointCloudToRgbImage(c, 0)
        rows, cols, channels = image.shape
        self.assertEquals(rows, 11)
        self.assertEquals(cols, 11)
        self.assertEquals(image[0, 0, 0], 255)
        self.assertEquals(image[0, 0, 1], 0)
        self.assertEquals(image[0, 0, 2], 0)
        self.assertEquals(image[10, 10, 0], 255)
        self.assertEquals(image[10, 10, 1], 0)
        self.assertEquals(image[10, 10, 2], 0)
        self.assertEquals(np.sum(image), 510)
예제 #32
0
def main(infile, outfile, pipeline=test_pipe):
    pc = PointCloud(infile, json_pipeline=pipeline)
    pc.unassign_classification(8)

    pc.find_elevated_points()

    if pc.elevated_points.size > 0:
        powerline_info = powerlines(pc.elevated_points, ht_min=10)

        poss_lines = pc.elevated_points[powerline_info[:, 2] == 1,
                                        3].astype(int)
        prob_lines = pc.elevated_points[powerline_info[:, 2] == 2,
                                        3].astype(int)
        poss_poles = pc.elevated_points[powerline_info[:, 1] != -1,
                                        3].astype(int)

        # pc.classification = (pc.eps, 7)
        pc.classification = (poss_lines, 60)
        pc.classification = (prob_lines, 60)
        pc.classification = (poss_poles, 30)
        pc.use_adj_points = False
        pc.save_las(filename=outfile)
        del pc
예제 #33
0
파일: Merge.py 프로젝트: nizshee/scannect
#! /usr/bin/python3

from PointCloud import PointCloud

start = 0
stop = 360
step = 10

pc_curr = PointCloud.read_file("../data/box{:03d}.pcd".format(start))
pc_curr = pc_curr.static(mean=50, dev=1e-1)
pc_curr.write("../data/processed/box{:03d}.pcd".format(start))

# pc_next = PointCloud.read_file("../data/box005.pcd")
# pc_next = pc_next.static(mean=50, dev=1e-1)

for angle in range(start + step, stop, step):
    file_fst = "../data/box{:03d}.pcd".format(angle)
    file_snd = "../data/processed/box{:03d}.pcd".format(angle)
    print(file_fst)
    pc_next = PointCloud.read_file(file_fst)
    pc_next = pc_next.static(mean=50, dev=1e-1)
    pc_curr = pc_curr.ndt(pc_next, iterations=100, step=10, resol=5.0, trans=0.08)
    pc_curr.write(file_snd)

# 24 26
# 36 38
# 28 30


# pc_next = pc_curr.ndt(pc_next, iterations=100, step=10, resol=10.0, trans=0.1)
예제 #34
0
파일: Filter.py 프로젝트: nizshee/scannect
#! /usr/bin/python3

from PointCloud import PointCloud

start = 0
stop = 360
step = 40


# pc_next = PointCloud.read_file("../data/box005.pcd")
# pc_next = pc_next.static(mean=50, dev=1e-1)

concat = PointCloud()
for angle in range(start, stop, step):
    filename = "../data/processed/box{:03d}.pcd".format(angle)
    print(filename)
    pc = PointCloud.read_file(filename)
    concat = concat.concat(pc.voxel(leaf_x=5, leaf_y=5, leaf_z=5))
# concat = concat.static(mean=200, dev=0.5)
# concat = concat.voxel(leaf_x=15, leaf_y=15, leaf_z=15)
concat.write("../data/processed/aaa.pcd")

concat.static(mean=30, dev=3).voxel(leaf_x=7, leaf_y=7, leaf_z=7).write_normal("../data/processed/aa.pcd")
예제 #35
0
from HomMatrix3 import HomMatrix3, FrustrumMatrix
from ProgressMeter import Meter

WIDTH  = 800 # width of canvas
HEIGHT = 800 # height of canvas

HPSIZE = 1 # double of point size (must be integer)
COLOR = "#0000FF" # blue

pointList = [] # list of points (used by Canvas.delete(...))
#pc = PointCloud().readRaw('data/elephant_points.raw').normalized()
#pc = PointCloud().readRaw('data/bunny_points.raw').normalized()
#pc = PointCloud().readRaw('data/cow_points.raw').normalized()
#pc = PointCloud().readRaw('data/pyramide_points.raw').normalized()
#pc = PointCloud().readRaw('data/wuerfel5-allneg_points.raw').normalized()
pc = PointCloud().readRaw('data/cube_points.raw').normalized()

xAngle = 0
yAngle = 0
zAngle = 0

## Sichtvolumen Kamera
fm = FrustrumMatrix(-2, 2, -2, 2, -1, 10)
cm = HomMatrix3()
cm.setTranslation(0,0,-3)

def quit(root=None):
    """ quit programm """
    if root==None:
        sys.exit(0)
    root._root().quit()