I ran this code and got a KeyError at line 183. Can you diagnose with me? You can tell me what to do next and I will give you the results. #!/usr/bin/env python3
"""
This script computes the point-pair features of a given
model and tries to find the model in a given scene.
Note: Currently, trimesh doesn't support pointcloud with normals. To combat this, you need to
reconstruct some surface between the points (e.g. ball pivoting)
"""
import random
import time
import argparse
import itertools
from collections import defaultdict
import trimesh
import trimesh.transformations as tf
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import KDTree
from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import linkage, fcluster
def main():
parser = argparse.ArgumentParser(
description=doc, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("model", default='/Users/mac/Documents/model-globally-match-locally-python/example_models/model_small.ply', help="Path to the model pointcloud")
parser.add_argument("scene", default='/Users/mac/Documents/model-globally-match-locally-python/example_models/scene_larger.ply', help="Path to the scene pointcloud")
parser.add_argument(
"--fast", action="store_true", help="Use the c++ extension for speeeeeed"
)
parser.add_argument(
"--scene-pts-fraction",
default=0.2,
type=float,
help="Fraction of scene points to use as reference",
)
parser.add_argument(
"--ppf-num-angles",
default=30,
type=int,
help="Number of angle steps used to discretize feature angles.",
)
parser.add_argument(
"--ppf-rel-dist-step",
default=0.05,
type=float,
help="Discretization step of feature distances, relative to model diameter.",
)
parser.add_argument(
"--alpha-num-angles",
default=30,
type=int,
help="Number of angle steps used to discretize the rotation angle alpha.",
)
parser.add_argument(
"--cluster-max-angle",
type=float,
default=30,
help="Maximal angle between poses after which they don't belong to same cluster anymore. [degrees]",
)
args = parser.parse_args()
if args.fast:
import ppf_fast
_compute_ppf = ppf_fast.compute_ppf
_pdist_rot = ppf_fast.pdist_rot
print("Using fast c++ mode")
else:
_compute_ppf = compute_ppf
_pdist_rot = pdist_rot
print("Using slow python mode")
model = trimesh.load(args.model)
scene = trimesh.load(args.scene)
if hasattr(model, "vertex_normals") and hasattr(scene, "vertex_normals"):
_model_vis = model.copy()
_scene_vis = scene.copy()
else:
try:
print(
"Your trimesh version still can't load pointclouds with normals. Trying open3d..."
)
import open3d as o3d
model = o3d.io.read_point_cloud(args.model)
scene = o3d.io.read_point_cloud(args.scene)
model = trimesh.Trimesh(
np.asarray(model.points), vertex_normals=np.asarray(model.normals)
)
scene = trimesh.Trimesh(
np.asarray(scene.points), vertex_normals=np.asarray(scene.normals)
)
_model_vis = trimesh.PointCloud(vertices=model.vertices)
_scene_vis = trimesh.PointCloud(vertices=scene.vertices)
except ImportError as e:
print("Fallback to open3d failed", e)
quit()
print("Model has", len(model.vertices), "vertices. scale=", model.scale)
print("Scene has", len(scene.vertices), "vertices. scale=", scene.scale)
# trimesh doesn't support .scale for point clouds
modelscale = np.linalg.norm(np.max(model.vertices, axis=0) - np.min(model.vertices, axis=0))
print("modelscale", modelscale)
_model_vis.visual.vertex_colors = [[255, 0, 0, 255] for _ in _model_vis.vertices]
_scene_vis.visual.vertex_colors = [
[150, 200, 150, 240] for _ in _scene_vis.vertices
]
#plt.figure()
#plt.show()
vis = trimesh.Scene([_model_vis, _scene_vis])
#vis.show()
## 1. compute ppfs of all vertex pairs in model, store in hash table
angle_step = float(np.radians(360 / args.ppf_num_angles))
dist_step = args.ppf_rel_dist_step * modelscale
print("Computing model ppfs features")
t_start = time.perf_counter()
ppfs_model, _, model_alphas = _compute_ppf(
to_nanobind(model.vertices),
to_nanobind(model.vertex_normals),
angle_step,
dist_step,
)
t_end = time.perf_counter()
print(f"Computing ppfs for {len(model.vertices)} verts took {t_end - t_start:.2f}s")
## 2. choose reference points in scene, compute their ppfs
t_start = time.perf_counter()
_, pairs_scene, scene_alphas = _compute_ppf(
to_nanobind(scene.vertices),
to_nanobind(scene.vertex_normals),
angle_step,
dist_step,
max_dist=modelscale,
ref_fraction=args.scene_pts_fraction,
)
t_end = time.perf_counter()
print(f"Computing all scene ppfs took {t_end - t_start:.1f}s")
## 3. go through scene ppfs, look up in table if we find model ppf
skipped_features = 0
# discretization for the alpha rotation
alpha_step = np.radians(360 / args.alpha_num_angles)
poses = []
# accumulator we're going to reuse for each reference vert
accumulator = np.zeros((len(model.vertices), args.alpha_num_angles))
print("Num reference verts", len(pairs_scene))
for idx_ref, sA in enumerate(pairs_scene):
print(
f"{idx_ref+1}/{len(pairs_scene)}: {len(pairs_scene[sA])} paired verts for ref {sA}",
" " * 20,
end="\r",
)
# one accumulator per reference vert, we set it to zero instead of re-initializing
accumulator[...] = 0
for sB in pairs_scene[sA]:
if sA == sB:
continue
s_feature = pairs_scene[sA][sB]
if s_feature not in ppfs_model:
skipped_features += 1
continue
alpha_s = scene_alphas[(sA, sB)]
for m_pair in ppfs_model[s_feature]:
mA, mB = m_pair
alpha_m = model_alphas[m_pair]
alpha = alpha_m - alpha_s
alpha_disc = int(alpha // alpha_step)
accumulator[mA, alpha_disc] += 1
# accumulator[mA, (alpha_disc - 1) % args.alpha_num_angles] += 1
# accumulator[mA, (alpha_disc + 1) % args.alpha_num_angles] += 1
peak_cutoff = np.max(accumulator) * 0.9
idxs_peaks = np.argwhere(accumulator > peak_cutoff)
s_r = scene.vertices[sA]
s_normal = scene.vertex_normals[sA]
R_scene2glob = np.eye(4)
R_scene2glob[:3, :3] = align_vectors(s_normal, [1, 0, 0])
T_scene2glob = R_scene2glob @ tf.translation_matrix(-s_r)
for best_mr, best_alpha in idxs_peaks:
R_model2glob = np.eye(4)
R_model2glob[:3, :3] = align_vectors(
model.vertex_normals[best_mr], [1, 0, 0]
)
T_model2glob = R_model2glob @ tf.translation_matrix(
-model.vertices[best_mr]
)
R_alpha = tf.rotation_matrix(alpha_step * best_alpha, [1, 0, 0], [0, 0, 0])
# TODO: invert homog
T_model2scene = np.linalg.inv(T_scene2glob) @ R_alpha @ T_model2glob
poses.append((T_model2scene, best_mr, accumulator[best_mr, best_alpha]))
print(f"Got {len(poses)} poses after matching", " " * 20)
print("Skipped", skipped_features, "scene pairs, not found in model")
t_cluster_start = time.perf_counter()
pose_clusters = cluster_poses(
poses,
dist_max=modelscale * 0.5,
rot_max_deg=args.cluster_max_angle,
pdist_rot=_pdist_rot,
)
poses = pose_clusters
t_cluster_end = time.perf_counter()
print(f"Clustering took {t_cluster_end - t_cluster_start:.1f}s")
## Visualize result
scene_refs = trimesh.PointCloud(
[scene.vertices[idx] for idx in list(pairs_scene.keys())]
)
vis = trimesh.Scene([_scene_vis, scene_refs])
for T_model2scene, m_r, score in poses:
model_vis = _model_vis.copy()
color = (*np.random.randint(0, 255, size=3), 255)
model_vis.visual.vertex_colors = [color for _ in model_vis.vertices]
model_vis.apply_transform(T_model2scene)
vis.add_geometry(model_vis)
print("Score", score)
print(np.around(T_model2scene, decimals=2))
print()
vis.show()
Assistant
def to_nanobind(arr):
"""
Workaround for current bug in nanobind: arrays need to be writable to be recognized
https://github.com/wjakob/nanobind/issues/42
"""
F_arr = np.asfortranarray(arr)
F_arr.setflags(write=True)
return F_arr
def align_vectors(a, b):
"""
Computes rotation matrix that rotates a into b
"""
v = np.cross(a, b)
c = np.dot(a, b)
v1, v2, v3 = v
h = 1 / (1 + c)
Vmat = np.array([[0, -v3, v2], [v3, 0, -v1], [-v2, v1, 0]])
R = np.eye(3) + Vmat + (Vmat.dot(Vmat) * h)
return R
def pdist_rot(rot_mats):
"""Returns the condensed distance matrix like pdist, but in rotation space"""
m = len(rot_mats)
idx = lambda i, j: m * i + j - ((i + 2) * (i + 1)) // 2
print("Index for last pair", idx(m, m) + 1)
# we save distance in degrees and use uint8 for smaller memory footprint
dists = np.zeros(idx(m, m) + 1, dtype=np.uint8)
print("dists shape", dists.shape)
mat_idxs = np.arange(m)
# Note: combinations() doesn't give (i,i) pairs
# Note: combinations() keeps original ascending index order
for idxA, idxB in itertools.combinations(mat_idxs, 2):
dist = np.degrees(rotation_between(rot_mats[idxA], rot_mats[idxB])).astype(
np.uint8
)
dists[idx(idxA, idxB)] = dist
return dists.astype(float)
def cluster_poses(poses, dist_max=0.5, rot_max_deg=10, pdist_rot=None):
rots = np.array([T_m2s[:3, :3] for T_m2s, _, _ in poses])
locs = np.array([T_m2s[:3, 3] for T_m2s, _, _ in poses])
scores = np.array([score for _, _, score in poses])
method = "centroid"
# 1) cluster by location
dist_dists = pdist(locs)
dist_dendro = linkage(dist_dists, method)
dist_clusters = fcluster(dist_dendro, dist_max, criterion="distance")
# 2) cluster by rotations
# XXX optimize, we can make more smaller cluster problems, since
# a cluster across distant poses doesn't make sense
rot_dists = pdist_rot(rots)
rot_dendor = linkage(rot_dists, method)
rot_clusters = fcluster(rot_dendor, rot_max_deg, criterion="distance")
# Combine the two clusterings, by creating new clusters
# if two poses are in same cluster in loc and rot, they will be in new
# common cluster (hash of both cluster ids)
pose_clusters = bernstein(dist_clusters, rot_clusters)
# remap the ludicrous hash values to range 0..num
_, pose_clusters = np.unique(pose_clusters, return_inverse=True)
cluster_scores = np.zeros(np.max(pose_clusters) + 1)
for pose_score, pose_cluster in zip(scores, pose_clusters):
cluster_scores[pose_cluster] += pose_score
best_cluster_idx = np.argmax(cluster_scores)
print(
"Best cluster",
best_cluster_idx,
cluster_scores[best_cluster_idx],
np.count_nonzero(pose_clusters == best_cluster_idx),
)
plt.hist(cluster_scores, histtype="stepfilled", bins=100)
plt.title("Cluster Scores Histogram")
plt.show()
out_ts = defaultdict(list)
out_Rs = defaultdict(list)
for pose_idx, cluster_idx in enumerate(pose_clusters):
out_ts[cluster_idx].append(locs[pose_idx])
out_Rs[cluster_idx].append(rots[pose_idx])
sorted_clusters = np.argsort(cluster_scores)[::-1]
for idx_cluster, top_cluster in enumerate(sorted_clusters[:10]):
print(f"cluster {idx_cluster} contains {len(out_ts[top_cluster])} poses")
geo = lambda x, y: np.sqrt(x * y)
best_cluster_idx = np.argmax(cluster_scores)
best_score = cluster_scores[best_cluster_idx]
best_geo_score = geo(best_score, len(out_ts[best_cluster_idx]))
best_rel_thresh = 0.5
out_poses = []
for cluster_idx in sorted_clusters:
geo_score = geo(len(out_ts[cluster_idx]), cluster_scores[cluster_idx])
if geo_score < best_rel_thresh * best_geo_score:
continue
print("cluster idx", cluster_idx, cluster_scores[cluster_idx], "geoscore", geo_score)
ts = out_ts[cluster_idx]
Rs = out_Rs[cluster_idx]
avg_t = np.mean(ts, axis=0)
avg_R = average_rotations(Rs)
out_T = np.eye(4)
out_T[:3, :3] = avg_R[:3, :3]
out_T[:3, 3] = avg_t
out_poses.append((out_T, 0, geo_score))
print("Returning", len(out_poses), "clustered and averaged poses")
return out_poses
Certainly! Let's work together to diagnose and resolve the KeyError you're encountering at line 183 in your script. Here's a step-by-step approach to identify and fix the issue.
1. Understanding the Error Location
Given the error occurs at line 183, let's pinpoint where this is in your script. Here's a snippet around that area:
for idx_ref, sA in enumerate(pairs_scene):
...
for sB in pairs_scene[sA]:
s_feature = pairs_scene[sA][sB]
if s_feature not in ppfs_model:
skipped_features += 1
continue
alpha_s = scene_alphas[(sA, sB)] # <-- Line 183: Potential KeyError
for m_pair in ppfs_model[s_feature]:
...
Potential Cause:
The KeyError is likely occurring when accessing scene_alphas[(sA, sB)]. This suggests that the key (sA, sB) does not exist in the scene_alphas dictionary at the time of access.
2. Hypothesize the Root Cause
Analyzing the script, the scene_alphas dictionary is populated in the compute_ppf function. Let's examine how compute_ppf is invoked for the scene:
Re-run the Script: Ensure that scene_alphas now contains the expected number of entries.
Check for KeyError: The error should no longer occur since scene_alphas is properly populated.
4. Implement the Fix
Here's the specific modification you need to make in your main() function:
...
## 2. choose reference points in scene, compute their ppfs
t_start = time.perf_counter()
_, pairs_scene, scene_alphas = _compute_ppf(
to_nanobind(scene.vertices),
to_nanobind(scene.vertex_normals),
angle_step,
dist_step,
max_dist=modelscale,
ref_fraction=args.scene_pts_fraction,
alphas=True, # <-- Enable alpha computation here
)
t_end = time.perf_counter()
print(f"Computing all scene ppfs took {t_end - t_start:.1f}s")
...
Explanation:
alphas=True: This flag ensures that the compute_ppf function calculates and stores the alpha values in the scene_alphas dictionary.
Result: With scene_alphas properly populated, accessing keys like (sA, sB) should no longer raise a KeyError.
5. Validate the Solution
After implementing the fix:
Run the Script: Execute your script with the provided arguments.
Monitor Output:
Verify that the KeyError at line 183 no longer appears.
Ensure that scene_alphas now contains a substantial number of entries (non-zero).
Further Testing:
If issues persist, consider adding additional debug statements to inspect specific keys and their presence in the dictionaries.
6. Additional Recommendations
Error Handling: To make your script more robust, consider adding error handling when accessing dictionary keys. For example:
try:
alpha_s = scene_alphas[(sA, sB)]
except KeyError:
print(f"Warning: Key {(sA, sB)} not found in scene_alphas.")
skipped_features += 1
continue
Logging: Implement a logging mechanism instead of using print statements. This allows better control over debug information and can be toggled based on verbosity levels.
Unit Tests: Consider writing unit tests for functions like compute_ppf to ensure they behave as expected under various scenarios.
Conclusion
The KeyError at line 183 was caused by the scene_alphas dictionary not being populated due to the alphas parameter being set to its default value False when computing PPFs for the scene. By setting alphas=True during this computation, the dictionary is correctly populated, resolving the error.
If you encounter further issues or need additional assistance, feel free to ask!