File size: 13,711 Bytes
b24c748
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
sys.path.append("/home/kyber/charles/project/grasp_box")
from submodules.SAM6D.pose_estimator import SAM6DPoseEstimator
import numpy as np
import argparse
import json
import yaml
import cv2
import matplotlib.pyplot as plt
import copy
from tqdm import tqdm
import glob
import pickle
import open3d as o3d
import time
import trimesh
import os
from pathlib import Path
from utilis import render_cad_mask, find_matched_points,count_lines_passing_points, get_connected_vertices, intersection_in_xyz_axis
 



class Perception:
    def __init__(self,config):   
        self.config_path = config
        self.config = self.load_config(config)
        self.intrinsic_matrix = np.array(
            [
                [
                    self.config["camera"]["intrinsic_matrix"]["f_x"],
                    0.0,
                    self.config["camera"]["intrinsic_matrix"]["c_x"],
                ],
                [
                    0.0,
                    self.config["camera"]["intrinsic_matrix"]["f_y"],
                    self.config["camera"]["intrinsic_matrix"]["c_y"],
                ],
                [0.0, 0.0, 1.0],
            ]
        )
        self.pose_estimator = SAM6DPoseEstimator(
                config,
                self.intrinsic_matrix,
                "/home/kyber/charles/project/grasp_box/submodules/SAM6D/config/base.yaml",
                True
            )
    def load_config(self, config_path):
        with open(config_path, "r") as file:
            return yaml.safe_load(file)
        
    def binary_search_scale(self, rgb,depth, mask, K, cad_name,debug=False,scale_min=[0.1, 0.15,0.15], scale_max=[0.3,0.18,0.5], threshold=15):
    
        h, w, _ = rgb.shape

        [low_x, low_y, low_z]=scale_min
        [high_x, high_y, high_z]=scale_max
        
        if set(np.unique(mask) ).issubset({0, 255}):
            mask =  (mask // 255).astype(np.uint8)
        
        while low_x<=high_x and low_y <= high_y  and low_z <= high_z:
            
            mid_x = (low_x+high_x)/2
            mid_y = (low_y+high_y)/2
            mid_z = (low_z+high_z)/2
            self.pose_estimator.K = self.intrinsic_matrix
            pose_scores, pred_rot, pred_trans,color_vis,_ = self.pose_estimator.inference(rgb.copy(), mask.copy(), depth.copy(), cad_name, scale= [mid_x, mid_y,mid_z])
        
            pose = np.eye(4)
            pose[:3,3] = pred_trans
            pose[:3,:3] = pred_rot

            mesh_c = self.pose_estimator.cad_cache['tmp']['mesh']
            
            mask_r= render_cad_mask(pose, mesh_c, K, w, h)
            if debug:
                self.vis_3d(rgb, depth, [pose],K,mesh_c)
                breakpoint()
            # find nearset vertices, and project get length between vertices
            half_extents = mesh_c.extents / 2.0
            signs = np.array([[x, y, z] for x in [-1, 1]
                                        for y in [-1, 1]
                                        for z in [-1, 1]])

            vertices = signs * half_extents   
            transformed_points = (pose @ np.hstack((vertices, np.ones((vertices.shape[0], 1)))).T).T[:, :3]
            projected_points = (K @ transformed_points.T).T
            projected_points[:, :2] /= projected_points[:, 2:3]
            
            condition = (projected_points[:, 0] < w) & (projected_points[:, 1] < h)
            filtered_points = projected_points[condition]
            filtered_indices = np.where(condition)[0]

            min_idx_in_filtered = np.argmin(np.linalg.norm(filtered_points)) 
            original_index = filtered_indices[min_idx_in_filtered]
            nearest_index = original_index
            projected_points = projected_points[...,:2].astype(int) 
        
            
            # if two vertices are matched, use this vertex as starting point and find intersection value, then get box extents directly
            gt_contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            gt_cnt = max(gt_contours, key=cv2.contourArea)
            gt_vertex = cv2.approxPolyDP(gt_cnt, epsilon=5, closed=True).reshape(-1,2)
            
            obs_contours, _ = cv2.findContours(mask_r.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            obs_cnt = max(obs_contours, key=cv2.contourArea)
            obs_vertex = cv2.approxPolyDP(obs_cnt, epsilon=5, closed=True).reshape(-1,2)
            vis = rgb.copy()
            for u, v in gt_vertex:
                cv2.circle(vis, tuple([u,v]), 5, (255, 0, 0), -1)
            # cv2.imwrite('a.png', vis)
            pair_match = find_matched_points(projected_points, gt_vertex, threshold=50)
       
            # early stopping, if key point matched, stop searching and return scale based on similarity
            for start_pt_index in range(8):
                start_pt =  projected_points[start_pt_index] 
            
                connected = get_connected_vertices(start_pt_index)
                norm_vectors = (projected_points[connected] - start_pt)/ np.linalg.norm(projected_points[connected] - start_pt)
                count = count_lines_passing_points(start_pt, norm_vectors, gt_vertex, threshold=threshold/2, rgb=rgb,vis = False)
                if  count == 3:
                    # lines start from start pt and project to xyz axis, all hits the vertex of gt mask, return the scale
                    arr_gt, arr_obs =  intersection_in_xyz_axis(norm_vectors, start_pt, mask_r, mask, threshold = threshold//2,vis = False, save = False)
                    output_scale = [None] * 3 
                    for axis_index,norm_vector in enumerate(norm_vectors):
                        axis = np.nonzero(signs[connected[axis_index]] - signs[start_pt_index])[0][0]
                        length_gt = arr_gt[axis_index]
                        end_pt_obs = projected_points[connected[axis_index]]

                        if end_pt_obs[0] not in range(0,rgb.shape[1]) or  end_pt_obs[1] not in range(0,rgb.shape[0]):
                            # out of boundary. get pixel distance directly from start and end point. add threshold for tolerance
                            length_obs = np.linalg.norm(end_pt_obs - start_pt).astype(np.uint32) + threshold
                        else:
                            length_obs = arr_obs[axis_index]
                        
                        output_scale[axis] = round(length_gt * mesh_c.extents[axis]/length_obs,2)
                 
                    return output_scale
                
            if len(pair_match) == 0:
                start_pt_index = nearest_index
                
            else:
                pair_match = pair_match[0]
                start_pt_index = pair_match[0]
                
            start_pt = projected_points[start_pt_index]  
            connected = get_connected_vertices(start_pt_index)
            norm_vectors = (projected_points[connected] - start_pt)/ np.linalg.norm(projected_points[connected] - start_pt)
            arr_gt, arr_obs =  intersection_in_xyz_axis(norm_vectors, start_pt, mask_r, mask,threshold,vis = False, save = False)
            
            if abs(arr_gt-arr_obs)[0] <= 20 and abs(arr_gt-arr_obs)[1] <= 20 and abs(arr_gt-arr_obs)[2] <= 20:
                break

            if  abs(high_x-low_x) < 0.1 and abs(high_y-low_y) < 1 and abs(high_z-low_z) < 0.1:
                break

            if (arr_obs[0] - arr_gt[0]) > 0:
                high_x = mid_x
            elif (arr_obs[0] - arr_gt[0]) < 0:
                low_x = mid_x
                
            if (arr_obs[1] - arr_gt[1]) > 0:
                high_y = mid_y
            elif (arr_obs[1] - arr_gt[1]) < 0:
                low_y = mid_y
                
            if (arr_obs[2] - arr_gt[2]) > 0:
                high_z = mid_z
            elif (arr_obs[2] - arr_gt[2]) < 0:
                low_z = mid_z
                
        final_scale = self.pose_estimator.cad_cache['tmp']['mesh'].extents
        return  final_scale
    
    def vis_3d(self, rgb_img, depth_img, pose_list,intrinsic,mesh, mask = None):
        
        vis = o3d.visualization.Visualizer()
        vis.create_window()
  
        if mask is not None:
            rgb_img = rgb_img * mask[:,:,None]
            depth_img = depth_img * mask
        rgb = o3d.geometry.Image(rgb_img) # for uinit16 use
        depth = o3d.geometry.Image((depth_img).astype(np.uint16))
        # mask = (mask > 0).astype(np.uint8) 
        
        rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(rgb, depth, depth_scale=1000.0)
       
        width = rgb_img.shape[1]
        height = rgb_img.shape[0]
        cx =  int(intrinsic[0,2])
        cy =  int(intrinsic[1,2])
        fx = int(intrinsic[0,0])
        fy = int(intrinsic[1,1])
        
        intri = o3d.camera.PinholeCameraIntrinsic(width=width, height=height, fx=fx, fy=fy, cx=cx, cy=cy) 
        o3d_points = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd, intrinsic=intri)
     
    
        vis.add_geometry(o3d_points)
        # vis.add_geometry(o3d.geometry.TriangleMesh.create_coordinate_frame(1))
        vis.update_geometry(o3d_points)
        
        

        
        
        for i,pose in enumerate(pose_list):

            # mesh = trimesh.load(self.config['cad_database'][f'{box_name[i]}'], force='mesh')
            # mesh_o3d = o3d.io.read_triangle_mesh(f"/media/kyber/Data1/SAM-6D/SAM-6D/Data/Storage_hq_test/model/{box_name}/model.obj",enable_post_processing=True)
            mesh_o3d = o3d.geometry.TriangleMesh()
            mesh_o3d.vertices = o3d.utility.Vector3dVector(mesh.vertices)
            mesh_o3d.triangles = o3d.utility.Vector3iVector(mesh.faces)
            aabb = mesh_o3d.get_axis_aligned_bounding_box()
            extents = aabb.get_extent()
            
            mesh_o3d.transform(pose)
            # print('----------------------------->',extents)
            mesh_o3d.paint_uniform_color([1.0, 0.0, 0.0]) 
            mesh_o3d = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(mesh.vertices),  o3d.utility.Vector3iVector(mesh.faces))
            pcd_obj = mesh_o3d.sample_points_uniformly(number_of_points=5000)

           
            pcd_obj_trans = copy.deepcopy(pcd_obj).transform(pose)
            pcd_obj_trans.paint_uniform_color([1.0, 0.0, 0.0]) 
            vis.add_geometry(pcd_obj_trans)
            vis.update_geometry(pcd_obj_trans)
        
        vis.run() 

    def run(self, depth_img, color_img, mask_img, K = None,debug = False, gt = False):
          
        if K is not None:
            self.intrinsic_matrix = K
       
        color_vis = copy.deepcopy(color_img)

      
        assert len(mask_img.shape) == 2
           
        # vis the GT
        # box = trimesh.load(f'/workspace/PACE/models/obj_{str(obj_id).zfill(6)}.ply', force='mesh')
        # box_rescale = box.copy()
        # box_rescale.vertices = box_rescale.vertices/1000
        # self.vis_3d(color_img, depth_img, [gt_pose],self.intrinsic_matrix,box_rescale)
            
        # use box infer module to infer the scale & pose
        tmp_scores = -1
        output_pose = None
        output_scores = None
        output_scale = None
        
        self.pose_estimator.K = self.intrinsic_matrix
    
    
        assert np.isin(mask_img, [0,1]).all()
        
        for run_idx in range(2):

            scale =  self.binary_search_scale(color_img,depth_img, mask_img*255, self.intrinsic_matrix, 'R306',debug=False,scale_min=[0.1, 0.15,0.15], scale_max=[0.3,0.18,0.5],threshold=10)
            box_ori_scale = self.pose_estimator.cad_cache['R306']['mesh'].extents
            new_scale = np.round(scale/box_ori_scale,2)
            pose_scores, pred_rot, pred_trans,color_vis, _ = self.pose_estimator.inference(color_img.copy(), mask_img*255, depth_img.copy(), 'R306', new_scale)
            pose6d = np.eye(4)
            pose6d[:3,:3] = pred_rot
            pose6d[:3,3] = pred_trans             
            mesh = copy.deepcopy(self.pose_estimator.cad_cache['tmp']['mesh'])
            print('scores:', pose_scores)
            
            if pose_scores is None: 
                continue
            if pose_scores > tmp_scores:
                output_pose = pose6d
                output_scores = pose_scores
                output_scale = mesh.extents
                tmp_scores = pose_scores
            
            self.vis_3d(color_img, depth_img, [pose6d],self.intrinsic_matrix,mesh)

        # IoU = iou_3d_boxes(box.extents/1000, gt_pose, mesh.extents, pose6d, grid_n=100)
        # IoU = compute_3d_iou_new(gt_pose, pose6d, box.extents/1000, mesh.extents,0,'box','box')
        # vis example from cpff++
        # box_ori_scale = self.pose_estimator.cad_cache['R306']['mesh'].extents
        # new_scale = np.round(cpf_scale/box_ori_scale,2)
        # mesh = copy.deepcopy(self.pose_estimator.cad_cache['tmp']['mesh'])
        # self.vis_3d(color_img, depth_img, [cpf_pose],self.intrinsic_matrix,mesh)
        return output_pose, output_scores, output_scale

    
if __name__ == '__main__':

    config = '/home/kyber/charles/project/grasp_box/config/config_perception.yaml'
    perception = Perception(config)
    color_img = cv2.imread('/home/kyber/charles/project/grasp_box/data/000000_rgb.png', cv2.IMREAD_COLOR)
    depth_img = cv2.imread('/home/kyber/charles/project/grasp_box/data/000000_depth.png', -1)  # unit mm    
    mask = ~cv2.imread('/home/kyber/charles/project/grasp_box/data/000000_box-colgate.png', -1)
    mask = mask.astype(bool)
    mask = mask.astype(np.uint8)  
    pose,scores, extents = perception.run(depth_img = depth_img, color_img = color_img,  mask_img=mask)