savoji's picture
Add files using upload-large-folder tool
b24c748 verified
import numpy as np
import cv2
from scipy.spatial import ConvexHull
def render_cad_mask(pose, mesh_model, K, w=640, h=480):
# Load the vertices from the mesh model
vertices = np.array(mesh_model.vertices)
size = min(len(vertices), 500)
sample_indices = np.random.choice(len(vertices), size=size, replace=False)
vertices = vertices[sample_indices]
# Transform vertices with the object pose
transformed_vertices = (pose @ np.hstack((vertices, np.ones((vertices.shape[0], 1)))).T).T[:, :3]
# Project vertices to the 2D plane using the intrinsic matrix K
projected_points = (K @ transformed_vertices.T).T
projected_points = projected_points[:, :2] / projected_points[:, 2:3] # Normalize by z
hull = ConvexHull(projected_points)
outline_points = projected_points[hull.vertices]
# Create a polygon from the projected 2D points
polygon = np.int32(outline_points).reshape((-1, 1, 2))
# Initialize a blank mask and draw the polygon
mask = np.zeros((h, w), dtype=np.uint8)
cv2.fillPoly(mask, [polygon], color=1)
return mask
def iou_3d_boxes(extentsA, T1, extentsB, T2, grid_n=60):
"""
Compute IoU between two 3D boxes (different sizes, different poses).
extentsA: (3,) full sizes of box A
T1: (4,4) transform (world-from-boxA)
extentsB: (3,) full sizes of box B
T2: (4,4) transform (world-from-boxB)
grid_n: number of grid subdivisions per axis for sampling inside box A
"""
extentsA = np.asarray(extentsA, float)
extentsB = np.asarray(extentsB, float)
sx, sy, sz = extentsA
volA = sx * sy * sz
volB = np.prod(extentsB)
# grid inside A's local frame
nx = ny = nz = grid_n
hx, hy, hz = sx/2, sy/2, sz/2
xs = np.linspace(-hx, hx, nx, endpoint=False) + (sx/nx)*0.5
ys = np.linspace(-hy, hy, ny, endpoint=False) + (sy/ny)*0.5
zs = np.linspace(-hz, hz, nz, endpoint=False) + (sz/nz)*0.5
X, Y, Z = np.meshgrid(xs, ys, zs, indexing="xy")
ptsA_local = np.stack([X.ravel(), Y.ravel(), Z.ravel()], axis=-1)
# transform these to world
R1, t1 = T1[:3,:3], T1[:3,3]
pts_world = ptsA_local @ R1.T + t1
# test inside B: transform to B-local
R2, t2 = T2[:3,:3], T2[:3,3]
ptsB_local = (pts_world - t2) @ R2
halfB = extentsB/2 + 1e-9
insideB = np.all(np.abs(ptsB_local) <= halfB, axis=1)
interVol = insideB.mean() * volA
if interVol == 0:
return 0.0
return interVol / (volA + volB - interVol)
def get_connected_vertices(start_index: int):
connected = []
vertices_relation = np.array([
[-1, -1, -1], # v0
[ 1, -1, -1], # v1
[-1, 1, -1], # v2
[ 1, 1, -1], # v3
[-1, -1, 1], # v4
[ 1, -1, 1], # v5
[-1, 1, 1], # v6
[ 1, 1, 1], # v7
])
v0 = vertices_relation[start_index]
for i, vi in enumerate(vertices_relation):
if i == start_index:
continue
if np.count_nonzero(np.abs(v0 - vi)) == 1:
connected.append(i)
return connected
def count_lines_passing_points(start_point, directions, points, threshold,rgb, vis = False):
start = np.array(start_point, dtype=float)
directions = np.array(directions, dtype=float)
points = np.array(points, dtype=float)
#delete start pt from points if it is in
# vis the start point and vertex points list
# vis = rgb.copy()
# cv2.circle(vis, tuple(start.astype(np.uint32)), 5, (255, 0, 0), -1)
# cv2.imwrite('a.png', vis)
skip_index = None
if np.min(np.linalg.norm(points-start,axis = 1)) <=15:
#same point
skip_index = np.argmin(np.linalg.norm(points-start,axis = 1))
norms = np.linalg.norm(directions, axis=1, keepdims=True)
directions = directions / norms
vis_img = rgb.copy()
count = 0
for dir_vec in directions:
diff = points - start
proj_len = np.dot(diff, dir_vec)
closest_points = start + np.outer(proj_len, dir_vec)
dists = np.linalg.norm(points - closest_points, axis=1)
if skip_index is not None:
dists[skip_index] = np.inf
if np.min(dists) < threshold:
count += 1
#vis
if vis:
index = np.argmin(dists)
cv2.circle(vis_img, tuple(start_point), 5, (0, 0, 255), -1)
end_point = points[index]
end_u = int(round(start_point[0] + dir_vec[0] * 50))
end_v = int(round(start_point[1] + dir_vec[1] * 50))
cv2.arrowedLine(vis_img, (int(start_point[0]), int(start_point[1])), (end_u, end_v), (0, 255, 0), 2)
cv2.circle(vis_img, tuple(end_point.astype(np.uint32)), 5, (255, 0, 0), -1)
if vis:
for u, v in points:
cv2.circle(vis_img, (int(u), int(v)), 2, (0, 255, 0), -1)
cv2.putText(vis_img, 'matched pt', (5,25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,225), thickness= 2)
cv2.putText(vis_img, 'passed pt', (5,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), thickness= 2)
cv2.putText(vis_img, 'projected gt box pt', (5,75), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), thickness= 2)
cv2.imwrite(f'vertex_matching.png',vis_img)
return count
def find_matched_points(points_a, points_b, threshold=7.0):
"""
Parameters:
points_a: (8, 2) numpy array
points_b: (6, 2) numpy array
threshold: float — max distance for a match
Returns:
matched_pairs: list of tuples (index_b, index_a, distance)
"""
matched_pairs = []
for i_b, pb in enumerate(points_b):
dists = np.linalg.norm(points_a - pb, axis=1)
min_idx = np.argmin(dists)
min_dist = dists[min_idx]
if min_dist < threshold:
matched_pairs.append((min_idx, i_b,min_dist))
matched_pairs.sort(key=lambda x: x[2])
return matched_pairs
def compute_and_visualize_line_mask_intersection(mask, start, direction, threshold, step_size=0.5, vis = False, save = False):
H, W = mask.shape
u0, v0 = start
du, dv = direction / np.linalg.norm(direction)
intersection_pixels = []
t = 0.0
inside = False
entry_t = None
exit_t = None
for _ in range(10000):
u = int(round(u0 + du * t))
v = int(round(v0 + dv * t))
if 0 <= u < W and 0 <= v < H:
if np.any(mask[v-threshold:v+threshold, u-threshold:u+threshold]):
intersection_pixels.append((u, v))
if not inside:
entry_t = t
inside = True
else:
if inside:
exit_t = t
inside = False
break
else:
if inside:
exit_t = t
inside = False
break
t += step_size
if entry_t is not None and exit_t is not None:
length = exit_t - entry_t
elif entry_t is not None:
length = t - entry_t
else:
length = 0.0
if vis or save:
visualization = cv2.cvtColor((mask * 255).astype(np.uint8), cv2.COLOR_GRAY2BGR)
# Draw intersection segment
for (u, v) in intersection_pixels:
visualization[v-5:v+5, u-5:u+5] = [0, 0, 255] # red pixels = intersection
# Draw entire ray
end_u = int(round(u0 + du * t))
end_v = int(round(v0 + dv * t))
cv2.arrowedLine(visualization, (int(u0), int(v0)), (end_u, end_v), (0, 255, 0), 2)
plt.figure(figsize=(6, 6))
plt.imshow(visualization[..., ::-1])
plt.title(f"Intersection length: {length:.2f} pixels")
plt.axis('off')
if save:
t = time.time()
plt.savefig(f"vis_{t}.png", dpi=300)
plt.close()
elif vis:
plt.show()
return length
def intersection_in_xyz_axis(norm_vectors, start_pt, mask_r,mask,threshold,vis = False, save = False):
intersection_gt_list = []
intersection_obs_list = []
for axis_index,norm_vector in enumerate(norm_vectors):
extended_start = start_pt
length_obs = compute_and_visualize_line_mask_intersection(mask_r, extended_start, norm_vector, threshold,step_size = 20, vis = vis, save = save)
length_gt = compute_and_visualize_line_mask_intersection(mask, extended_start, norm_vector, threshold,step_size = 20, vis=vis, save = save)
intersection_obs_list.append(length_obs)
intersection_gt_list.append(length_gt)
arr_gt = np.array(intersection_gt_list, dtype=np.float32)
arr_obs = np.array(intersection_obs_list, dtype=np.float32)
return arr_gt, arr_obs