# Copyright (C) 2024-present Naver Corporation. All rights reserved. # Licensed under CC BY-NC-SA 4.0 (non-commercial use only). # # -------------------------------------------------------- # Visualization utilities using trimesh # -------------------------------------------------------- import PIL.Image import numpy as np from scipy.spatial.transform import Rotation import torch from dust3r.utils.geometry import geotrf, get_med_dist_between_poses, depthmap_to_absolute_camera_coordinates from dust3r.utils.device import to_numpy from dust3r.utils.image import rgb, img_to_arr try: import trimesh except ImportError: print('/!\\ module trimesh is not installed, cannot visualize results /!\\') def cat_3d(vecs): if isinstance(vecs, (np.ndarray, torch.Tensor)): vecs = [vecs] return np.concatenate([p.reshape(-1, 3) for p in to_numpy(vecs)]) def show_raw_pointcloud(pts3d, colors, point_size=2): scene = trimesh.Scene() pct = trimesh.PointCloud(cat_3d(pts3d), colors=cat_3d(colors)) scene.add_geometry(pct) scene.show(line_settings={'point_size': point_size}) def pts3d_to_trimesh(img, pts3d, valid=None): H, W, THREE = img.shape assert THREE == 3 assert img.shape == pts3d.shape vertices = pts3d.reshape(-1, 3) # make squares: each pixel == 2 triangles idx = np.arange(len(vertices)).reshape(H, W) idx1 = idx[:-1, :-1].ravel() # top-left corner idx2 = idx[:-1, +1:].ravel() # right-left corner idx3 = idx[+1:, :-1].ravel() # bottom-left corner idx4 = idx[+1:, +1:].ravel() # bottom-right corner faces = np.concatenate(( np.c_[idx1, idx2, idx3], np.c_[idx3, idx2, idx1], # same triangle, but backward (cheap solution to cancel face culling) np.c_[idx2, idx3, idx4], np.c_[idx4, idx3, idx2], # same triangle, but backward (cheap solution to cancel face culling) ), axis=0) # prepare triangle colors face_colors = np.concatenate(( img[:-1, :-1].reshape(-1, 3), img[:-1, :-1].reshape(-1, 3), img[+1:, +1:].reshape(-1, 3), img[+1:, +1:].reshape(-1, 3) ), axis=0) # remove invalid faces if valid is not None: assert valid.shape == (H, W) valid_idxs = valid.ravel() valid_faces = valid_idxs[faces].all(axis=-1) faces = faces[valid_faces] face_colors = face_colors[valid_faces] assert len(faces) == len(face_colors) return dict(vertices=vertices, face_colors=face_colors, faces=faces) def cat_meshes(meshes): vertices, faces, colors = zip(*[(m['vertices'], m['faces'], m['face_colors']) for m in meshes]) n_vertices = np.cumsum([0]+[len(v) for v in vertices]) for i in range(len(faces)): faces[i][:] += n_vertices[i] vertices = np.concatenate(vertices) colors = np.concatenate(colors) faces = np.concatenate(faces) return dict(vertices=vertices, face_colors=colors, faces=faces) def show_duster_pairs(view1, view2, pred1, pred2): import matplotlib.pyplot as pl pl.ion() for e in range(len(view1['instance'])): i = view1['idx'][e] j = view2['idx'][e] img1 = rgb(view1['img'][e]) img2 = rgb(view2['img'][e]) conf1 = pred1['conf'][e].squeeze() conf2 = pred2['conf'][e].squeeze() score = conf1.mean()*conf2.mean() print(f">> Showing pair #{e} {i}-{j} {score=:g}") pl.clf() pl.subplot(221).imshow(img1) pl.subplot(223).imshow(img2) pl.subplot(222).imshow(conf1, vmin=1, vmax=30) pl.subplot(224).imshow(conf2, vmin=1, vmax=30) pts1 = pred1['pts3d'][e] pts2 = pred2['pts3d_in_other_view'][e] pl.subplots_adjust(0, 0, 1, 1, 0, 0) if input('show pointcloud? (y/n) ') == 'y': show_raw_pointcloud(cat(pts1, pts2), cat(img1, img2), point_size=5) def auto_cam_size(im_poses): return 0.1 * get_med_dist_between_poses(im_poses) class SceneViz: def __init__(self): self.scene = trimesh.Scene() def add_rgbd(self, image, depth, intrinsics=None, cam2world=None, zfar=np.inf, mask=None): image = img_to_arr(image) # make up some intrinsics if intrinsics is None: H, W, THREE = image.shape focal = max(H, W) intrinsics = np.float32([[focal, 0, W/2], [0, focal, H/2], [0, 0, 1]]) # compute 3d points pts3d = depthmap_to_pts3d(depth, intrinsics, cam2world=cam2world) return self.add_pointcloud(pts3d, image, mask=(depth 150) mask |= (hsv[:, :, 1] < 30) & (hsv[:, :, 2] > 180) mask |= (hsv[:, :, 1] < 50) & (hsv[:, :, 2] > 220) # Morphological operations kernel = np.ones((5, 5), np.uint8) mask2 = ndimage.binary_opening(mask, structure=kernel) # keep only largest CC _, labels, stats, _ = cv2.connectedComponentsWithStats(mask2.view(np.uint8), connectivity=8) cc_sizes = stats[1:, cv2.CC_STAT_AREA] order = cc_sizes.argsort()[::-1] # bigger first i = 0 selection = [] while i < len(order) and cc_sizes[order[i]] > cc_sizes[order[0]] / 2: selection.append(1 + order[i]) i += 1 mask3 = np.in1d(labels, selection).reshape(labels.shape) # Apply mask return torch.from_numpy(mask3)