ScanNet 数据集平面拟合和平面匹配

代码主要参考:PlaneNet

3D数据平面拟合

思路: 为3D数据中每一个已标注和未标注(代码中把未标注的顶点当做一类)的实例拟合平面,然后合并符合指定要求的平面。

阅读代码前注意的一些概念:

  1. group

代码里面的 group 指的是一个物体实例,如上图中用不同颜色区分开的点云集合。

  1. segment

标签相同的点云集合,一个group 里面可能含有多个segment ,一个segment 里可能含有多个平面。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
import xml.etree.ElementTree as ET
import numpy as np
import cv2
import sys
import os
from plyfile import PlyData, PlyElement
import json
import zipfile
import glob

#ROOT_FOLDER = '/mnt/vision/ScanNet/data/'
ROOT_FOLDER = '/home/jiajie/planar_match/PlaneNet/data_preparation/ScanNet/data/'

class ColorPalette:
    def __init__(self, numColors):
        np.random.seed(2)
        #self.colorMap = np.random.randint(255, size = (numColors, 3))
        #self.colorMap[0] = 0


        self.colorMap = np.array([[255, 0, 0],
                                  [0, 255, 0],
                                  [0, 0, 255],
                                  [80, 128, 255],
                                  [255, 230, 180],
                                  [255, 0, 255],
                                  [0, 255, 255],
                                  [100, 0, 0],
                                  [0, 100, 0],
                                  [255, 255, 0],
                                  [50, 150, 0],
                                  [200, 255, 255],
                                  [255, 200, 255],
                                  [128, 128, 80],
                                  [0, 50, 128],
                                  [0, 100, 100],
                                  [0, 255, 128],
                                  [0, 128, 255],
                                  [255, 0, 128],
                                  [128, 0, 255],
                                  [255, 128, 0],
                                  [128, 255, 0],
        ])

        if numColors > self.colorMap.shape[0]:
            self.colorMap = np.concatenate([self.colorMap, np.random.randint(255, size = (numColors - self.colorMap.shape[0], 3))], axis=0)
            pass

        return

    def getColorMap(self):
        return self.colorMap

    def getColor(self, index):
        if index >= colorMap.shape[0]:
            print("index out of range...")
            return np.random.randint(255, size = (3))
        else:
            print("get color in colormap")
            return self.colorMap[index]
            pass

def writePointCloudFace(filename, points, faces):
    with open(filename, 'w') as f:
        header = """ply
format ascii 1.0
element vertex """
        header += str(len(points))
        header += """
property float x
property float y
property float z
property uchar red                                     { start of vertex color }
property uchar green
property uchar blue
property uchar alpha
element face """
        header += str(len(faces))
        header += """
property list uchar int vertex_index
end_header
"""
        f.write(header)
        for point in points:
            for value in point[:3]:
                f.write(str(value) + ' ')
                continue
            for value in point[3:]:
                f.write(str(int(value)) + ' ')
                continue
            f.write(str(int(255)) + ' ')
            f.write('\n')
            continue
        for face in faces:
            f.write('3 ' + str(face[0]) + ' ' + str(face[1]) + ' ' + str(face[2]) + '\n')
            continue        
        f.close()
        pass
    return

def loadClassMap():
    classMap = {}
    classLabelMap = {}
    with open(ROOT_FOLDER + 'class_label/scannetv2-labels.combined.tsv') as info_file:
        line_index = 0
        for line in info_file:
            if line_index > 0:
                line = line.split('\t')
                
                key = line[1].strip()                
                classMap[key] = line[7].strip()
                classMap[key + 's'] = line[7].strip()

                if line[4].strip() != '':
                    label = int(line[4].strip())
                else:
                    label = -1
                    pass
                classLabelMap[key] = label
                classLabelMap[key + 's'] = label                    
                pass
            line_index += 1
            continue
        pass
    return classMap, classLabelMap

def fitPlane(points):
    if points.shape[0] == points.shape[1]:
        return np.linalg.solve(points, np.ones(points.shape[0]))
    else:
        return np.linalg.lstsq(points, np.ones(points.shape[0]), rcond=None)[0]
    
def mergePlanesNew(points, planes, planePointIndices, planeSegments, segmentNeighbors, numPlanes, planeDiffThreshold = 0.05, planeAngleThreshold = 30, inlierThreshold = 0.9, planeAreaThreshold = 10, orthogonalThreshold = np.cos(np.deg2rad(60)), parallelThreshold = np.cos(np.deg2rad(30)), debug=False):


    fittingErrorThreshold = planeDiffThreshold
    
    planeFittingErrors = []
    for plane, pointIndices in zip(planes, planePointIndices):
        XYZ = points[pointIndices]
        planeNorm = np.linalg.norm(plane)
        if planeNorm == 0:
            planeFittingErrors.append(fittingErrorThreshold)
            continue
        diff = np.abs(np.matmul(XYZ, plane) - np.ones(XYZ.shape[0])) / planeNorm
        planeFittingErrors.append(diff.mean())
        continue
    
    planeList = zip(planes, planePointIndices, planeSegments, planeFittingErrors)
    planeList = sorted(planeList, key=lambda x:x[3])

    ## Merge two planes if they are neighbors and the merged plane has small fitting error
    while len(planeList) > 0:
        hasChange = False
        planeIndex = 0

        if debug:
            for index, planeInfo in enumerate(sorted(planeList, key=lambda x:-len(x[1]))):
                print(index, planeInfo[0] / np.linalg.norm(planeInfo[0]), planeInfo[2], planeInfo[3])
                continue
            pass
        
        while planeIndex < len(planeList):
            plane, pointIndices, segments, fittingError = planeList[planeIndex]
            if fittingError > fittingErrorThreshold:
                break
            neighborSegments = []
            for segment in segments:
                if segment in segmentNeighbors:
                    neighborSegments += segmentNeighbors[segment]
                    pass
                continue
            neighborSegments += list(segments)
            neighborSegments = set(neighborSegments)
            bestNeighborPlane = (fittingErrorThreshold, -1, None)
            for neighborPlaneIndex, neighborPlane in enumerate(planeList):
                if neighborPlaneIndex <= planeIndex:
                    continue
                if not bool(neighborSegments & neighborPlane[2]):
                    continue
                dotProduct = np.abs(np.dot(neighborPlane[0], plane) / np.maximum(np.linalg.norm(neighborPlane[0]) * np.linalg.norm(plane), 1e-4))
                newPointIndices = np.concatenate([neighborPlane[1], pointIndices], axis=0)
                XYZ = points[newPointIndices]
                if dotProduct > parallelThreshold and len(neighborPlane[1]) > len(pointIndices) * 0.5:
                    newPlane = fitPlane(XYZ)                    
                else:
                    newPlane = plane
                    pass
                #newPlane = plane
                diff = np.abs(np.matmul(XYZ, newPlane) - np.ones(XYZ.shape[0])) / np.linalg.norm(newPlane)
                newFittingError = diff.mean()
                if debug:
                    print(len(planeList), planeIndex, neighborPlaneIndex, newFittingError, plane / np.linalg.norm(plane), neighborPlane[0] / np.linalg.norm(neighborPlane[0]), dotProduct, orthogonalThreshold)
                    pass
                if dotProduct < orthogonalThreshold:
                    continue                
                if newFittingError < bestNeighborPlane[0]:
                    newPlaneInfo = [newPlane, newPointIndices, segments.union(neighborPlane[2]), newFittingError]
                    bestNeighborPlane = (newFittingError, neighborPlaneIndex, newPlaneInfo)
                    pass
                continue
            if bestNeighborPlane[1] != -1:
                newPlaneList = planeList[:planeIndex] + planeList[planeIndex + 1:bestNeighborPlane[1]] + planeList[bestNeighborPlane[1] + 1:]
                newFittingError, newPlaneIndex, newPlane = bestNeighborPlane
                for newPlaneIndex in range(len(newPlaneList)):
                    if (newPlaneIndex == 0 and newPlaneList[newPlaneIndex][3] > newFittingError) \
                       or newPlaneIndex == len(newPlaneList) - 1 \
                       or (newPlaneList[newPlaneIndex][3] < newFittingError and newPlaneList[newPlaneIndex + 1][3] > newFittingError):
                        newPlaneList.insert(newPlaneIndex, newPlane)
                        break                    
                    continue
                if len(newPlaneList) == 0:
                    newPlaneList = [newPlane]
                    pass
                planeList = newPlaneList
                hasChange = True
            else:
                planeIndex += 1
                pass
            continue
        if not hasChange:
            break
        continue

    planeList = sorted(planeList, key=lambda x:-len(x[1]))

    
    minNumPlanes, maxNumPlanes = numPlanes
    if minNumPlanes == 1 and len(planeList) == 0:
        if debug:
            print('at least one plane')
            pass
    elif len(planeList) > maxNumPlanes:
        if debug:
            print('too many planes', len(planeList), maxNumPlanes)
            pass
        planeList = planeList[:maxNumPlanes]
        pass
    
    groupedPlanes, groupedPlanePointIndices, groupedPlaneSegments, groupedPlaneFittingErrors = zip(*planeList)
    groupNeighbors = []
    for planeIndex, planeSegments in enumerate(groupedPlaneSegments):
        neighborSegments = []
        for segment in planeSegments:
            if segment in segmentNeighbors:            
                neighborSegments += segmentNeighbors[segment]
                pass
            continue
        neighborSegments += list(planeSegments)        
        neighborSegments = set(neighborSegments)
        neighborPlaneIndices = []
        for neighborPlaneIndex, neighborPlaneSegments in enumerate(groupedPlaneSegments):
            if neighborPlaneIndex == planeIndex:
                continue
            if bool(neighborSegments & neighborPlaneSegments):
                plane = groupedPlanes[planeIndex]
                neighborPlane = groupedPlanes[neighborPlaneIndex]
                if np.linalg.norm(plane) * np.linalg.norm(neighborPlane) < 1e-4:
                    continue
                dotProduct = np.abs(np.dot(plane, neighborPlane) / np.maximum(np.linalg.norm(plane) * np.linalg.norm(neighborPlane), 1e-4))
                if dotProduct < orthogonalThreshold:
                    neighborPlaneIndices.append(neighborPlaneIndex)
                    pass
                pass
            continue
        groupNeighbors.append(neighborPlaneIndices)
        continue

    if debug and len(groupedPlanes) > 1:
        print('merging result', [len(pointIndices) for pointIndices in groupedPlanePointIndices], groupedPlaneFittingErrors, groupNeighbors)
        pass
    
    planeList = zip(groupedPlanes, groupedPlanePointIndices, groupNeighbors)
    return planeList


def readMesh(scene_id):

    filename = ROOT_FOLDER + scene_id + '/' + scene_id + '.aggregation.json'
    data = json.load(open(filename, 'r'))
    aggregation = np.array(data['segGroups'])

    high_res = False

    if high_res:
        filename = ROOT_FOLDER + scene_id + '/' + scene_id + '_vh_clean.labels.ply'
    else:
        filename = ROOT_FOLDER + scene_id + '/' + scene_id + '_vh_clean_2.labels.ply'
        pass

    plydata = PlyData.read(filename)
    vertices = plydata['vertex']
    points = np.stack([vertices['x'], vertices['y'], vertices['z']], axis=1)
    faces = np.array(plydata['face']['vertex_indices'])
    
    semanticSegmentation = vertices['label']


    if high_res:
        filename = ROOT_FOLDER + scene_id + '/' + scene_id + '_vh_clean.segs.json'
    else:
        filename = ROOT_FOLDER + scene_id + '/' + scene_id + '_vh_clean_2.0.010000.segs.json'
        pass

    data = json.load(open(filename, 'r'))
    segmentation = np.array(data['segIndices'])

    groupSegments = []
    groupLabels = []
    for segmentIndex in range(len(aggregation)):
        groupSegments.append(aggregation[segmentIndex]['segments'])
        groupLabels.append(aggregation[segmentIndex]['label'])
        continue

    segmentation = segmentation.astype(np.int32)

    uniqueSegments = np.unique(segmentation).tolist()
    numSegments = 0
    for segments in groupSegments:
        for segmentIndex in segments:
            if segmentIndex in uniqueSegments:
                uniqueSegments.remove(segmentIndex)
                pass
            continue
        numSegments += len(segments)
        continue

    for segment in uniqueSegments:
        groupSegments.append([segment, ])
        groupLabels.append('unannotated')
        continue

    numGroups = len(groupSegments)
    numPoints = segmentation.shape[0]    
    numPlanes = 1000

    ## Segment connections for plane merging later
    segmentEdges = []
    for faceIndex in range(faces.shape[0]):
        face = faces[faceIndex]
        segment_1 = segmentation[face[0]]
        segment_2 = segmentation[face[1]]
        segment_3 = segmentation[face[2]]
        if segment_1 != segment_2 or segment_1 != segment_3:
            if segment_1 != segment_2 and segment_1 != -1 and segment_2 != -1:
                segmentEdges.append((min(segment_1, segment_2), max(segment_1, segment_2)))
                pass
            if segment_1 != segment_3 and segment_1 != -1 and segment_3 != -1:
                segmentEdges.append((min(segment_1, segment_3), max(segment_1, segment_3)))
                pass
            if segment_2 != segment_3 and segment_2 != -1 and segment_3 != -1:
                segmentEdges.append((min(segment_2, segment_3), max(segment_2, segment_3)))                
                pass
            pass
        continue
    segmentEdges = list(set(segmentEdges))


    numPlanes = 1000
    numPlanesPerSegment = 2
    segmentRatio = 0.1
    planeAreaThreshold = 10
    numIterations = 100
    numIterationsPair = 1000
    planeDiffThreshold = 0.05
    fittingErrorThreshold = planeDiffThreshold

    ## Specify the minimum and maximum number of planes for each object
    labelNumPlanes = {'wall': [1, 3], 
                      'floor': [1, 1],
                      'cabinet': [1, 5],
                      'bed': [1, 5],
                      'chair': [1, 2],
                      'sofa': [1, 10],
                      'table': [1, 5],
                      'door': [1, 2],
                      'window': [1, 2],
                      'bookshelf': [1, 5],
                      'picture': [1, 1],
                      'counter': [1, 10],
                      'blinds': [0, 0],
                      'desk': [1, 10],
                      'shelf': [1, 5],
                      'shelves': [1, 5],                      
                      'curtain': [0, 0],
                      'dresser': [1, 5],
                      'pillow': [0, 0],
                      'mirror': [0, 0],
                      'entrance': [1, 1],
                      'floor mat': [1, 1],                      
                      'clothes': [0, 0],
                      'ceiling': [1, 5],
                      'book': [0, 1],
                      'books': [0, 1],                      
                      'refridgerator': [1, 5],
                      'television': [1, 1], 
                      'paper': [0, 1],
                      'towel': [0, 1],
                      'shower curtain': [0, 1],
                      'box': [1, 5],
                      'whiteboard': [1, 5],
                      'person': [0, 0],
                      'night stand': [1, 5],
                      'toilet': [0, 5],
                      'sink': [0, 5],
                      'lamp': [0, 1],
                      'bathtub': [0, 5],
                      'bag': [0, 1],
                      'otherprop': [0, 5],
                      'otherstructure': [0, 5],
                      'otherfurniture': [0, 5],                      
                      'unannotated': [0, 5],
                      '': [0, 0],
    }
    nonPlanarGroupLabels = ['bicycle', 'bottle', 'water bottle']
    nonPlanarGroupLabels = {label: True for label in nonPlanarGroupLabels}
    
    verticalLabels = ['wall', 'door', 'cabinet']
    classMap, classLabelMap = loadClassMap()
    allXYZ = points.reshape(-1, 3)

    segmentNeighbors = {}
    for segmentEdge in segmentEdges:
        if segmentEdge[0] not in segmentNeighbors:
            segmentNeighbors[segmentEdge[0]] = []
            pass
        segmentNeighbors[segmentEdge[0]].append(segmentEdge[1])
        
        if segmentEdge[1] not in segmentNeighbors:
            segmentNeighbors[segmentEdge[1]] = []
            pass
        segmentNeighbors[segmentEdge[1]].append(segmentEdge[0])
        continue

    planeGroups = []
    print('num groups', len(groupSegments))

    debug = False    
    debugIndex = -1

    ## A group corresponds to an instance in the ScanNet annotation
    for groupIndex, group in enumerate(groupSegments):
        if debugIndex != -1 and groupIndex != debugIndex:
            continue
        if groupLabels[groupIndex] in nonPlanarGroupLabels:
            groupLabel = groupLabels[groupIndex]
            minNumPlanes, maxNumPlanes = 0, 0
        elif groupLabels[groupIndex] == 'unannotated':
            groupLabel = 'unannotated'
            minNumPlanes, maxNumPlanes = labelNumPlanes[groupLabel]
        elif groupLabels[groupIndex] in classMap:
            groupLabel = classMap[groupLabels[groupIndex]]
            minNumPlanes, maxNumPlanes = labelNumPlanes[groupLabel]            
        else:
            minNumPlanes, maxNumPlanes = 0, 0
            groupLabel = ''
            pass

        if maxNumPlanes == 0:
            pointMasks = []
            for segmentIndex in group:
                pointMasks.append(segmentation == segmentIndex)
                continue
            pointIndices = np.any(np.stack(pointMasks, 0), 0).nonzero()[0]
            groupPlanes = [[np.zeros(3), pointIndices, []]]
            planeGroups.append(groupPlanes)
            continue
        groupPlanes = []
        groupPlanePointIndices = []
        groupPlaneSegments = []


        ## A group contains multiple segments and we run RANSAC for each segment
        for segmentIndex in group:
            segmentMask = segmentation == segmentIndex
            segmentIndices = segmentMask.nonzero()[0]

            XYZ = allXYZ[segmentMask.reshape(-1)]
            numPoints = XYZ.shape[0]

            segmentPlanes = []
            segmentPlanePointIndices = []

            for c in range(2):
                if c == 0:
                    ## First try to fit one plane to see if the entire segment is one plane
                    plane = fitPlane(XYZ)
                    diff = np.abs(np.matmul(XYZ, plane) - np.ones(XYZ.shape[0])) / np.linalg.norm(plane)
                    if diff.mean() < fittingErrorThreshold:
                        segmentPlanes.append(plane)
                        segmentPlanePointIndices.append(segmentIndices)
                        break
                else:
                    ## Run ransac                    
                    for planeIndex in range(numPlanesPerSegment):
                        if len(XYZ) < planeAreaThreshold:
                            continue
                        bestPlaneInfo = [None, 0, None]
                        for iteration in range(min(XYZ.shape[0], numIterations)):
                            sampledPoints = XYZ[np.random.choice(np.arange(XYZ.shape[0]), size=(3), replace=False)]
                            try:
                                plane = fitPlane(sampledPoints)
                                pass
                            except:
                                continue
                            diff = np.abs(np.matmul(XYZ, plane) - np.ones(XYZ.shape[0])) / np.linalg.norm(plane)
                            inlierMask = diff < planeDiffThreshold
                            numInliers = inlierMask.sum()
                            if numInliers > bestPlaneInfo[1]:
                                bestPlaneInfo = [plane, numInliers, inlierMask]
                                pass
                            continue

                        if bestPlaneInfo[1] < planeAreaThreshold:
                            break

                        
                        pointIndices = segmentIndices[bestPlaneInfo[2]]
                        #bestPlane = bestPlaneInfo[0]
                        bestPlane = fitPlane(XYZ[bestPlaneInfo[2]])
                        
                        segmentPlanes.append(bestPlane)                
                        segmentPlanePointIndices.append(pointIndices)

                        outlierMask = np.logical_not(bestPlaneInfo[2])
                        segmentIndices = segmentIndices[outlierMask]
                        XYZ = XYZ[outlierMask]
                        continue
                    pass
                continue
            
            if sum([len(indices) for indices in segmentPlanePointIndices]) < numPoints * 0.5:
                print('not enough fitted points')
                if len(segmentIndices) >= planeAreaThreshold:
                    groupPlanes.append(np.zeros(3))
                    groupPlanePointIndices.append(segmentIndices)
                    groupPlaneSegments.append(set([segmentIndex]))
                    pass
            else:
                groupPlanes += segmentPlanes
                groupPlanePointIndices += segmentPlanePointIndices
                for _ in range(len(segmentPlanes)):
                    groupPlaneSegments.append(set([segmentIndex]))
                    continue
                pass
            continue
            
        if len(groupPlanes) > 0:
            ## Merge planes of each instance
            groupPlanes = mergePlanesNew(points, groupPlanes, groupPlanePointIndices, groupPlaneSegments, segmentNeighbors, numPlanes=(minNumPlanes, maxNumPlanes), planeDiffThreshold=planeDiffThreshold, planeAreaThreshold=planeAreaThreshold, debug=debugIndex != -1)
            pass

        if debug:
            print('group', groupIndex, groupLabels[groupIndex], groupLabel, len(groupPlanes))
            pass
        
        planeGroups.append(groupPlanes)
        continue
    
    
    if debug:
        #colorMap = np.random.randint(255, size=(segmentation.max() + 2, 3))
        colorMap = ColorPalette(segmentation.max() + 2).getColorMap()
        colorMap[-1] = 0
        colorMap[-2] = 255
        annotationFolder = 'test/'
        #colorMap = np.tile(np.expand_dims(np.arange(256), -1), [1, 3])
    else:
        #colorMap = ColorPalette(segmentation.max() + 2).getColorMap()
        # numPlanes = sum([len(group) for group in planeGroups])
        #print('num planes', numPlanes)
        #exit(1)
        # segmentationColor = (np.arange(numPlanes) + 1) * 100
        # colorMap = np.stack([segmentationColor / (256 * 256), segmentationColor / 256 % 256, segmentationColor % 256], axis=1)
        colorMap = ColorPalette(numPlanes).getColorMap()
        # print('colorMap: ',colorMap)
        # colorMap[-1] = 255
        annotationFolder = ROOT_FOLDER + scene_id + '/annotation/'
        pass


    if debug:
        colors = colorMap[segmentation]
        writePointCloudFace(annotationFolder + '/segments.ply', np.concatenate([points, colors], axis=-1), faces)

        groupedSegmentation = np.full(segmentation.shape, fill_value=-1)
        for segmentIndex in range(len(aggregation)):
            indices = aggregation[segmentIndex]['segments']
            for index in indices:
                groupedSegmentation[segmentation == index] = segmentIndex
                continue
            continue
        groupedSegmentation = groupedSegmentation.astype(np.int32)
        colors = colorMap[groupedSegmentation]
        writePointCloudFace(annotationFolder + '/groups.ply', np.concatenate([points, colors], axis=-1), faces)
        pass

    
    planes = []
    planePointIndices = []
    for index, group in enumerate(planeGroups):
        groupPlanes, groupPlanePointIndices, groupNeighbors = zip(*group)

        planes += groupPlanes
        planePointIndices += groupPlanePointIndices
        continue
    

    planeSegmentation = np.full(segmentation.shape, fill_value=-1, dtype=np.int32)
    for planeIndex, planePoints in enumerate(planePointIndices):
        if np.linalg.norm(planes[planeIndex]) < 1e-4:
            planeSegmentation[planePoints] = -2
        else:
            planeSegmentation[planePoints] = planeIndex
            pass
        continue


    if debug:
        groupSegmentation = np.full(segmentation.shape, fill_value=-1, dtype=np.int32)        
        structureSegmentation = np.full(segmentation.shape, fill_value=-1, dtype=np.int32)
        typeSegmentation = np.full(segmentation.shape, fill_value=-1, dtype=np.int32)
        for planeIndex, planePoints in enumerate(planePointIndices):
            if len(planeInfo[planeIndex]) > 1:
                structureSegmentation[planePoints] = planeInfo[planeIndex][1][0]
                typeSegmentation[planePoints] = np.maximum(typeSegmentation[planePoints], planeInfo[planeIndex][1][1] - 2)
                pass
            groupSegmentation[planePoints] = planeInfo[planeIndex][0][0]
            continue

        colors = colorMap[groupSegmentation]    
        writePointCloudFace(annotationFolder + '/group.ply', np.concatenate([points, colors], axis=-1), faces)

        colors = colorMap[structureSegmentation]    
        writePointCloudFace(annotationFolder + '/structure.ply', np.concatenate([points, colors], axis=-1), faces)

        colors = colorMap[typeSegmentation]    
        writePointCloudFace(annotationFolder + '/type.ply', np.concatenate([points, colors], axis=-1), faces)
        pass


    planes = np.array(planes)
    print('number of planes: ', planes.shape[0])    
    planesD = 1.0 / np.maximum(np.linalg.norm(planes, axis=-1, keepdims=True), 1e-4)
    planes *= pow(planesD, 2)

    ## Remove boundary faces for rendering purpose
    removeIndices = []
    for faceIndex in range(faces.shape[0]):
        face = faces[faceIndex]
        segment_1 = planeSegmentation[face[0]]
        segment_2 = planeSegmentation[face[1]]
        segment_3 = planeSegmentation[face[2]]
        if segment_1 != segment_2 or segment_1 != segment_3:
            removeIndices.append(faceIndex)
            pass
        continue
    faces = np.delete(faces, removeIndices)
    colors = colorMap[planeSegmentation]  
    writePointCloudFace(annotationFolder + '/planes.ply', np.concatenate([points, colors], axis=-1), faces)

    if debug:
        exit(1)
        pass
    
    np.save(annotationFolder + '/planes.npy', planes)
        
    return


if __name__=='__main__':

    scene_ids = os.listdir(ROOT_FOLDER)
    scene_ids = scene_ids

    for scene_id in scene_ids:
        if scene_id[:5] != 'scene':
            continue
        if not os.path.exists(ROOT_FOLDER + '/' + scene_id + '/annotation'):
            os.system('mkdir -p ' + ROOT_FOLDER + '/' + scene_id + '/annotation')
            pass
        if not os.path.exists(ROOT_FOLDER + '/' + scene_id + '/annotation/segmentation'):
            os.system('mkdir -p ' + ROOT_FOLDER + '/' + scene_id + '/annotation/segmentation')
            pass
        print(scene_id)
        ## Download if not exists
        if not os.path.exists(ROOT_FOLDER + '/' + scene_id + '/' + scene_id + '.aggregation.json'):
            print('file not download')          
            pass
        print('plane fitting', scene_id)
        if not os.path.exists(ROOT_FOLDER + '/' + scene_id + '/annotation/planes.ply'):
            readMesh(scene_id)
            pass

        # ## Use a C++ program built upon OpenGL to render the 3D plane fitting results to each view
        # if len(glob.glob(ROOT_FOLDER + '/' + scene_id + '/annotation/segmentation/*.png')) < len(glob.glob(ROOT_FOLDER + '/' + scene_id + '/pose/*.txt')):
        #     cmd = '/home/jiajie/planar_match/PlaneNet/data_preparation/Renderer/build/Renderer --scene_id=' + scene_id + ' --root_folder=' + ROOT_FOLDER
        #     os.system(cmd)
        #     pass
        # continue

二维平面分割以及平面匹配

  1. 首先用opengl渲染网格到RGB图
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import os
import sys
import cv2
import argparse
import numpy as np
import trimesh
import pyrender
import matplotlib.pyplot as plt
from tqdm import tqdm,trange

sys.path.append('../')
from utils.functions import get_filelist,get_suffix

def parse_args():
    parser = argparse.ArgumentParser(description='Render mesh to images in different poses')
    
    parser.add_argument('--root_folder',
                        help='Working Folder',
                        default= "/home/jiajie/planar_match/PlaneNet/data_preparation/ScanNet/data",
                        type=str)
    parser.add_argument('--seg_imgs_folder',
                        help='Working Folder',
                        default= "/home/jiajie/planar_match/graph_plane_matching/data_process/seg_images",
                        type=str)
    # parser.add_argument('--seg_masks_folder',
    # help='Working Folder',
    # default= "/home/jiajie/planar_match/graph_plane_matching/data_process/seg_masks",
    # type=str)
    args = parser.parse_args()  
    return args

def get_pose_gl(opencv_camera_pose_inv):
    """
    input:
        the inverse of camera pose(you can use cv2.solvePnPRansac to produce the input):
        _,rvec,tvec,inliners = cv2.solvePnPRansac(pt13, pt2, K, None)
        R = cv2.Rodrigues(rvec)[0]
        T = tvec
        #inverse
        R = R.transpose()
        T = -R.dot(T)

        # the pose offered by ScanNet datasets is opencv_camera_pose_inv, not the opencv_camera_pose(solvePnPRansac)

    return:
        camera_pose: camera_pose
    """
    #matx solve the different coordinate between opencv and opengl
    matx = np.array([[1, 0, 0,0 ],[0, -1, 0, 0],[0, 0, -1, 0],[0, 0, 0, 1]]) 
    R = opencv_camera_pose_inv[0:3,0:3]
    T = opencv_camera_pose_inv[0:3,3:4]
    camera_pose = np.eye(4)
    camera_pose[0:3,0:3] = R
    camera_pose[0:3,3:4] = T
    camera_pose = camera_pose.dot(matx)
    return camera_pose

def read_pose_in_txt(pose_dir):    
    opencv_camera_pose_inv=np.loadtxt(pose_dir,dtype=np.float64)
    return opencv_camera_pose_inv

def gl_renderer(mesh_path, camera_pose_path, save_dir, is_visualize = False):
    """
    input: 
        path of model, camera_pose(opencv_camera_pose_inv)

    output: 
        .png file rendered by the mesh model and different camera views(gl)
    """
    fuze_trimesh = trimesh.load(mesh_path)
    # print('raw color: ',fuze_trimesh.visual.vertex_colors)  
    # fuze_trimesh.visual.vertex_colors = np.random.uniform(size=fuze_trimesh.vertices.shape)
    # fuze_trimesh.visual.face_colors = np.random.uniform(size=fuze_trimesh.faces.shape)
    mesh = pyrender.Mesh.from_trimesh(fuze_trimesh)
      
    pose_path_lists = []
    get_filelist(camera_pose_path,pose_path_lists)
    
    for i in trange(len(pose_path_lists)):
        pose_path = pose_path_lists[i]
        scene = pyrender.Scene()
        #add mesh
        room_node = scene.add(mesh,pose=np.eye(4))
        #add camera
        camera = pyrender.IntrinsicsCamera(fx=1169.62,fy=1167.11,cx=646.295,cy=489.927,znear=0.05, zfar=100.0)

        light = pyrender.DirectionalLight(color=np.ones(3), intensity=1)
        # light = pyrender.SpotLight(color=np.ones(3), intensity=10.0,
        #                 innerConeAngle=np.pi/16, outerConeAngle=np.pi/6)
        # light = pyrender.PointLight(color=np.ones(3), intensity=10.0)

        scene.add(light, pose=np.eye(4))

        # pyrender.Viewer(scene, use_raymond_lighting=True)
        camera_pose_inv = read_pose_in_txt(pose_path)
        camera_pose = get_pose_gl(camera_pose_inv)
        scene.add(camera, pose=camera_pose)
        # scene.set_pose(room_node,pose=camera_pose)     
      
        r = pyrender.OffscreenRenderer(viewport_width=1296, viewport_height=968, point_size=1.0)
        """Render the color buffer flat, with no lighting computations."""
        flags = pyrender.RenderFlags.FLAT
        color, _ = r.render(scene,flags)  
                
        suffix = get_suffix(pose_path)
        color_name = pose_path.split("/")[-1].replace(f'{suffix}',"")
        cv2.imwrite(f'{save_dir}/{color_name}.jpg',color)
        
        # print('render color: ',color)
        r.delete()
        if(is_visualize):
            plt.figure(figsize=(8,8))
            plt.imshow(color)
            plt.show()
      
def main():
    args = parse_args()
    ROOT_FOLDER = args.root_folder
    scene_ids = os.listdir(ROOT_FOLDER)

    for i in trange(len(scene_ids)):
        scene_id = scene_ids[i]
        if scene_id[:5] != 'scene':
            continue
        if not os.path.exists(ROOT_FOLDER + '/' + scene_id + '/annotation'):
            # os.system('mkdir -p ' + ROOT_FOLDER + '/' + scene_id + '/annotation')
            os.makedirs(f'{ROOT_FOLDER}/{scene_id}/annotation')
        
        mesh_path = f'{ROOT_FOLDER}/{scene_id}/annotation/planes.ply'
        mesh_mask_path = f'{ROOT_FOLDER}/{scene_id}/annotation/planes_mask.ply'
        pose_path = f'{ROOT_FOLDER}/{scene_id}/pose'
        seg_path = f'{args.seg_imgs_folder}/{scene_id}'
        # seg_mask_path = f'{args.seg_masks_folder}/{scene_id}'
        if not os.path.exists(seg_path):
            # os.system('mkdir -p ' + seg_path)
            os.makedirs(seg_path)
        # if not os.path.exists(seg_mask_path):
        #     # os.system('mkdir -p ' + seg_path)
        #     os.makedirs(seg_mask_path)

        gl_renderer(mesh_path, pose_path, seg_path, False)
        # gl_renderer(mesh_mask_path, pose_path, seg_mask_path, False)
   
if __name__=='__main__':
    main()
  1. 为每张图像保存对应的数据
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import os
import sys
import cv2
import math
import argparse
import numpy as np
from tqdm import tqdm,trange

sys.path.append('../')
from utils.functions import get_filelist,get_suffix,plot_cv_image

def parse_args():
    parser = argparse.ArgumentParser(description='Render mesh to images in different poses')
    
    parser.add_argument('--seg_imgs_folder',
                        help='segmentation images folder',
                        default= "/home/jiajie/planar_match/graph_plane_matching/data_process/seg_images",
                        type=str)
    parser.add_argument('--raw_imgs_folder',
                        help='ScanNet raw images folder',
                        default= "/home/jiajie/planar_match/PlaneNet/data_preparation/ScanNet/data",
                        type=str)
    parser.add_argument('--npz_save_folder',
                        help='npz files save folder',
                        default= "/home/jiajie/planar_match/graph_plane_matching/data_process/npz_datas",
                        type=str)
    parser.add_argument(
                        '--resize', type=int, nargs='+', default=[640, 480],
                        help='resize the input image')
    parser.add_argument(
                        '--min_nums_in_plane', type=int, default=400,
                        help='min num of pixel in one plane')
    args = parser.parse_args()  
    return args

def save_npz_file(raw_img_path, seg_img_path, camera_pose_path, npz_save_path):
    #read img
    raw_img = cv2.imread(raw_img_path, flags = 1)
    seg_img = cv2.imread(seg_img_path, flags = 2)  
   
    #resize
    size = args.resize
    resized_raw = cv2.resize(raw_img, tuple(size), interpolation = cv2.INTER_AREA)
    resized_seg = cv2.resize(seg_img, tuple(size), interpolation = cv2.INTER_AREA)
    
    #bgr 2 rgb
    rgb_array = resized_raw[..., ::-1]
    # seg_array = resized_seg[..., ::-1]
    # plot_image(resized_seg)
    rgb_array = np.asarray(rgb_array).astype(np.uint8)
    seg_array = np.asarray(resized_seg).astype(np.uint8)
    planar_nonplanar_array = np.asarray(resized_seg).astype(np.uint8)
    unique_seg = np.unique(seg_array).tolist()

    min_nums = args.min_nums_in_plane
    for us in unique_seg:          
        if(seg_array[np.where(seg_array == us)].shape[0]<min_nums):
            seg_array[np.where(seg_array == us)] = 0
    seg_array[np.where(seg_array == 255)] = 0
    #plane area or not in plane area
    planar_nonplanar_array[np.where(seg_array == 0)] = 0
    planar_nonplanar_array[np.where(seg_array != 0)] = 255
    kernel = np.ones((4,4),np.uint8)  
    #开运算,则先腐蚀再膨胀,用于去噪以及物体边缘二值化
    seg_array = cv2.morphologyEx(seg_array, cv2.MORPH_OPEN, kernel)
    planar_nonplanar_array = cv2.morphologyEx(planar_nonplanar_array, cv2.MORPH_OPEN, kernel)
    # plot_cv_image(planar_nonplanar_array)
    # plot_cv_image(seg_array)
    seg_mask_value = np.unique(seg_array)
    segmentation = []
    for smv in seg_mask_value.tolist():       
        segmentation.append(np.where(seg_array == smv))
    seg_array = np.array(segmentation)

    data_info_dict = {}
    data_info_dict['num_planes'] = seg_mask_value.shape[0]
    data_info_dict['image_name'] = raw_img_path.split("/")[-1]
    camera_pose = np.loadtxt(camera_pose_path)
    data_info_dict['camera_pose'] = camera_pose

    #save npz file
    # image:rgb format data
    # seg_mask_value: values of different seg_mask
    # segmentation: pixel index of differnet seg_mask
    np.savez(npz_save_path,
                 image=rgb_array, seg_mask_value=seg_mask_value,
                 segmentation=seg_array,planar_non_planar_mask = planar_nonplanar_array, data_info=data_info_dict)
       
    
def main():
    seg_folder = args.seg_imgs_folder
    scene_ids = os.listdir(seg_folder)

    for n in trange(len(scene_ids)):
        scene_id = scene_ids[n]
        if scene_id[:5] != 'scene':          
            continue
        seg_imgs_path = f'{seg_folder}/{scene_id}'
        seg_imgs_lists = []      
        get_filelist(seg_imgs_path,seg_imgs_lists)
        raw_imgs_path = f'{args.raw_imgs_folder}/{scene_id}/color'
        camera_pose_path = f'{args.raw_imgs_folder}/{scene_id}/pose'
        npz_save_folder = f'{args.npz_save_folder}/{scene_id}'
        print(npz_save_folder)
        if not os.path.exists(npz_save_folder):           
            os.makedirs(npz_save_folder)
        print(npz_save_folder)

        for i in trange(len(seg_imgs_lists)):
            seg_img = seg_imgs_lists[i]
            raw_img = f'{raw_imgs_path}/{seg_img.split("/")[-1]}'
            suffix = get_suffix(raw_img)
            camera_pose_name = seg_img.split('/')[-1].replace(suffix,'.txt')
            camera_pose = f"{camera_pose_path}/{camera_pose_name}" 
            npz_save_path = f'{npz_save_folder}/'+ seg_img.split('/')[-1].replace(suffix,'.npz')
            save_npz_file(raw_img, seg_img, camera_pose, npz_save_path)
    

if __name__ == "__main__":
    args = parse_args()
    main()
  1. 根据分割的具体像素值以及相机位姿寻找匹配平面
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import sys
import cv2
import os
import math
import numpy as np
import argparse
from tqdm import tqdm,trange
from matplotlib import pyplot as plt

sys.path.append('../')
from utils.functions import get_filelist,get_suffix,plot_image

def parse_args():
    parser = argparse.ArgumentParser(description='Render mesh to images in different poses')
    parser.add_argument('--npz_files_folder',
                        help='npz files folder',
                        default= "/home/jiajie/planar_match/graph_plane_matching/data_process/npz_datas",
                        type=str)
    parser.add_argument('--min_value', type=float, nargs='+', default=[0.98, 1],
                        help='min cos angle value threshold of two cameras')
    parser.add_argument('--match_planes_folder',
                        help='files folder store which images have neighbor relationsive',
                        default= "/home/jiajie/planar_match/graph_plane_matching/data_process/match_planes",
                        type=str)
    
    args = parser.parse_args()  
    return args

def find_match_plane(npz_files_floder, match_planes_folder):
    npz_files_list = []
    get_filelist(npz_files_floder,npz_files_list)
    for i in trange(len(npz_files_list)):
        data_s = np.load(npz_files_list[i],allow_pickle=True) 
        camera_pose_s = data_s['data_info'].item()['camera_pose']
        img_id_s = data_s['data_info'].item()['image_name']
        suffix = get_suffix(img_id_s)
        img_id_s = img_id_s.replace(f"{suffix}","")
        nunm_palnes_s = data_s['data_info'].item()['num_planes']    
        # rotation vector
        R_matrix_s = camera_pose_s[0:3,0:3]
        r_vec_s = cv2.Rodrigues(R_matrix_s)[0]    
        r_vec_s = np.swapaxes(r_vec_s,0,1)
        t_vec_s = camera_pose_s[0:3,3:4]
        # translation vector
        for j in range(i,len(npz_files_list)):
            if npz_files_list[i].split("/")[-1] == npz_files_list[j].split("/")[-1]:
                continue
            data_t = np.load(npz_files_list[j],allow_pickle=True)
            camera_pose_t = data_t['data_info'].item()['camera_pose']
            # rotation vector
            R_matrix_t = camera_pose_t[0:3,0:3]
            r_vec_t = cv2.Rodrigues(R_matrix_t)[0] 
            t_vec_t = camera_pose_t[0:3,3:4]
            #caculate cos angle: cos=ab/|a|*|b|
            cos_value = np.dot(r_vec_s, r_vec_t)/(np.linalg.norm(r_vec_s) * np.linalg.norm(r_vec_t))
            t_vec_diff = np.linalg.norm(t_vec_t-t_vec_s)
            if cos_value > args.min_value[0] and t_vec_diff < args.min_value[1]:          
                img_id_t = data_t['data_info'].item()['image_name']
                # plot_image(name=img_id_t,img=data_t['image'])      
                img_id_t = data_t['data_info'].item()['image_name']
                suffix = get_suffix(img_id_t)
                img_id_t = img_id_t.replace(f"{suffix}","")
                #generate plane match relationsive
                nunm_palnes_t = data_t['data_info'].item()['num_planes']  
                Max_num_planes = nunm_palnes_s if nunm_palnes_s > nunm_palnes_t else nunm_palnes_t
                match_plane_list = []
                for k in range(nunm_palnes_s):
                    #get seg mask value
                    seg_mask_value_s = data_s['seg_mask_value'][k]
                    target_index = np.where(data_t['seg_mask_value']==seg_mask_value_s)
                                
                    if target_index[0].shape[0] != 0:                      
                        match_plane_list.append([k,target_index[0][0]])
                    else:
                        match_plane_list.append([k,-1])
                #save txt file
                match_name = f'{img_id_s}_{img_id_t}.txt'
                np.set_printoptions(suppress=True)              
                np.savetxt(f'{match_planes_folder}/{match_name}',np.array(match_plane_list))

                #save visualize imgs
                source_img = np.asarray(data_s['planar_non_planar_mask']).astype(np.uint8)
                for num in range(data_s['segmentation'].shape[0]):
                    seg = tuple(data_s['segmentation'][num])                           
                    source_img[seg] = data_s['seg_mask_value'][num]
                target_img = np.asarray(data_t['planar_non_planar_mask']).astype(np.uint8)
                for num in range(data_t['segmentation'].shape[0]):
                    seg = tuple(data_t['segmentation'][num])                           
                    target_img[seg] = data_t['seg_mask_value'][num]

                fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 5), sharex=False, sharey=False)
                
                ax[0].set_title('image_s') 
                ax[0].imshow(source_img,cmap="bone")

                ax[1].set_title('image_t')                   
                ax[1].imshow(target_img,cmap="bone")

                match_plane_name = f'{img_id_s}_{img_id_t}.jpg'
                # plt.show()
                plt.savefig(f'{match_planes_folder}/{match_plane_name}')

            

def main():
    scene_ids = os.listdir(args.npz_files_folder)
    for scene_id in scene_ids:
        match_planes_folder = f'{args.match_planes_folder}/{scene_id}'
        npz_files_floder = f'{args.npz_files_folder}/{scene_id}'
        if not os.path.exists(match_planes_folder):           
                os.makedirs(match_planes_folder)
        find_match_plane(npz_files_floder, match_planes_folder)
        
if __name__ == "__main__":
    args = parse_args()
    main()
updatedupdated2022-03-232022-03-23