Grasp Detection from Depth and Point Clouds
Module: Computer Vision | Difficulty: Premium
Prerequisites
- !Depth cameras and point cloud basics
- !Convolutional backbones and heatmap outputs
- !Rotations and coordinate frames in 3D
What You'll Learn
- 1Represent a candidate grasp as a compact parameter vector
- 2Score grasp quality using force closure intuition
- 3Post-process raw detector scores into an executable pose
- 4Transfer a simulated grasp policy to a real arm
- 5Pick a grasp pipeline that fits your cycle-time budget
Why grasping is harder than detection
An object detector answers a question about an image. A grasp detector has to answer a question about physics: if two fingers close here, will the object stay put when the arm accelerates? Geometry that looks trivial on screen often fails in the cell. A mug handled by its rim is stable while stationary and rotates out of the gripper the moment the wrist tilts. A stack of thin cards cannot be pinched from above because the fingers collide with the table before reaching a force-closing configuration. Transparent and reflective objects break the depth sensor itself, returning holes exactly where the fingers need to go.
The engineering consequence is that a grasp pipeline is never just a network. It is a detector, a set of geometric constraints, a collision check, and a temporal filter working together. Understanding where each stage contributes accuracy is what separates a demo that works on a video from a cell that runs a thousand cycles a shift.
Representing a candidate grasp
For a parallel-jaw gripper on a tabletop, most systems use a planar parameterization: a contact point in the image, a jaw rotation around the camera axis, and an opening width, plus a quality score. This reduces the search to a per-pixel prediction, which is cheap and fits convolutional architectures naturally.
A full six-degree-of-freedom formulation adds an approach direction and a roll about it, which is necessary for picking objects out of a bin where a top-down approach is blocked. Six-degree systems usually predict a set of contact points instead of a single vector, then pair them into antipodal candidates.
| Parameter | Planar grasp | Six-degree grasp | Why it matters |
|---|---|---|---|
| Contact location | One image point | Two opposing points | Antipodal pairing guarantees opposing normals |
| Orientation | Angle in image plane | Approach and roll angles | Determines collision with bin walls |
| Width | Scalar | Scalar or per-pair | Must exceed object extent by a margin |
| Quality | Scalar heatmap value | Force-closure score | Rank before committing hardware |
| Output size | Small, dense | Large, sparse | Drives inference latency |
Quality itself comes from classical mechanics. The epsilon metric asks how large a wrench the contact set can resist in the worst direction, which is force closure expressed as a scalar. Learned systems regress a proxy of that number rather than computing it, because numerical force closure needs friction coefficients you rarely have for real clutter.
Turning a depth frame into ranked grasps
Modern detectors follow the GQ-CNN recipe: stack a depth image with derived channels, run a small encoder-decoder, and emit a quality heatmap plus regression heads for angle and width. Contact-based variants instead output per-point contact probabilities on the point cloud and assemble poses from high-scoring pairs, which recovers grasps that are impossible to express in a single top-down frame.
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraspDetector(nn.Module):
"""Dense planar grasp prediction from depth plus geometry channels."""
def __init__(self, in_channels=4):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(in_channels, 32, 3, stride=2, padding=1),
nn.BatchNorm2d(32), nn.ReLU(inplace=True),
nn.Conv2d(32, 64, 3, stride=2, padding=1),
nn.BatchNorm2d(64), nn.ReLU(inplace=True),
nn.Conv2d(64, 128, 3, stride=2, padding=1),
nn.BatchNorm2d(128), nn.ReLU(inplace=True),
)
self.quality = nn.Conv2d(128, 1, 1)
self.angle = nn.Conv2d(128, 1, 1)
self.width = nn.Conv2d(128, 1, 1)
def forward(self, x):
f = self.encoder(x)
return {
"quality": torch.sigmoid(self.quality(f)),
"angle": torch.sigmoid(self.angle(f)) * torch.pi,
"width": self.width(f).clamp(0.02, 0.12),
}
def top_k_grasps(pred, k=256, nms_radius=24):
"""Greedy spatial suppression so candidates are not duplicates."""
q = pred["quality"][0, 0]
scores = q.flatten()
order = scores.argsort(descending=True)
picked = []
taken = torch.zeros_like(q, dtype=torch.bool)
for idx in order:
y, x = divmod(idx.item(), q.shape[1])
if taken[y, x]:
continue
picked.append((scores[idx].item(), y, x))
r = nms_radius
taken[max(0, y - r):y + r, max(0, x - r):x + r] = True
if len(picked) >= k:
break
return picked
model = GraspDetector()
with torch.no_grad():
pred = model(depth_stack) # (1, 4, 320, 320)
candidates = top_k_grasps(pred, k=256)
Non-maximum suppression is not optional. Without it the heatmap yields thousands of neighbouring pixels at nearly identical poses, and downstream collision checking wastes its entire budget evaluating duplicates centimetres apart.
From scores to an executable pose
The detector works in camera coordinates; the robot works in its base frame. Depth at the candidate pixel, converted through the camera intrinsics, gives a 3D point, and a fixed hand-eye calibration transforms it into base coordinates. The jaw angle from the image plane must likewise be rotated into the wrist frame, taking care that angle wrap-around near zero does not cause a large commanded motion.
Before execution, three checks run. The width must exceed the measured object extent plus a closing margin, otherwise the fingers arrive already touching and stall. The approach path must be swept against the table and any known obstacles, because a perfectly valid grasp pose can still be unreachable along a straight line. And the gripper's own body must clear neighbouring clutter, which is the check that most often eliminates the highest-scoring candidate and forces the pipeline to walk down the ranked list.
import numpy as np
import tf_transformations as tft
class GraspExecutor:
def __init__(self, detector, camera_intrinsics, tcp_from_cam):
self.detector = detector
self.K = camera_intrinsics
self.T = tcp_from_cam # 4x4 hand-eye transform
def pick_best(self, depth, forbidden_boxes):
pred = self.detector(depth)
for score, y, x in top_k_grasps(pred, k=64):
z = depth[0, y, x]
if not np.isfinite(z) or z <= 0.05:
continue
u = (x - self.K[0, 2]) * z / self.K[0, 0]
v = (y - self.K[1, 2]) * z / self.K[1, 1]
pose_cam = np.array([u, v, z, 1.0])
pose_base = self.T @ pose_cam
yaw = pred["angle"][0, 0, y, x].item()
width = pred["width"][0, 0, y, x].item()
if width < 0.03:
continue
if any(self._collides(pose_base[:3], box) for box in forbidden_boxes):
continue
quat = tft.quaternion_from_euler(0, 0, yaw)
return {"xyz": pose_base[:3], "quat": quat, "width": width,
"score": score}
return None
@staticmethod
def _collides(point, box):
lo, hi = box
return np.all(point >= lo) and np.all(point <= hi)
Walking the ranked list rather than committing to argmax is the single cheapest reliability win available in this stack.
Closing the simulation gap
Simulated grasping is where data comes from, because generating a million clutter scenes with perfect labels costs nothing. It is also where policies go to die: textures are flat, friction is uniform, depth sensors are noiseless, and objects never deform. The remedy is domain randomization, varying texture, lighting, friction, object pose, and camera noise so the network can no longer tell which domain it is in.
The adversarial term pushes simulated and real features together, but randomization alone usually accounts for most of the transfer. After pretraining, a few dozen real grasps with human or scripted correction are enough to fine-tune the last layers, which is far cheaper than annotating a full real dataset.
| Approach | Simulation data | Real data needed | Reported real success |
|---|---|---|---|
| Train on Cornell only | None | 885 labeled images | Around 90 percent |
| Train in sim without randomization | One million | None | Collapses under clutter |
| Train in sim with randomization | One million | None | Roughly 85 percent |
| Randomized sim plus short fine-tune | One million | 10 to 100 corrections | Mid to high 90s |
Choosing a pipeline for your cell
For structured pick-and-place with known parts, skip learning entirely: fit a primitive, compute an antipodal axis analytically, and execute. For unstructured bins, a dense planar detector with temporal filtering is the pragmatic default, and it runs comfortably inside a 200 millisecond budget on embedded hardware. For entangled or overlapping objects, contact-point prediction on the full point cloud recovers grasps that top-down approaches miss, at roughly double the latency.
Hardware choices interact with these decisions more than people expect. A gripper with compliant fingertips forgives a pose error of several millimetres and lets you relax the approach constraint, while a rigid parallel jaw demands sub-millimetre accuracy and therefore a slower final approach. Suction collapses the problem to finding a locally flat patch, which is far easier to detect, but it trades away the ability to lift heavy objects by the edge or to orient a part precisely in the gripper.
Temporal filtering deserves emphasis. Rather than trusting one frame, accumulate the quality map across the last few captures in the base frame and pick the candidate that is consistently high scoring. Objects that are barely graspable in a single noisy depth frame are usually stable over five, and the average also suppresses the transient holes that stereo and time-of-flight sensors produce on glossy surfaces.
Common Mistakes
Executing the argmax grasp without checking the closing width or table clearance
Fix: Rank candidates, then validate width, approach sweep and gripper clearance, walking down the list on failure
Calibrating hand-eye once and never verifying it after a collision or a camera remount
Fix: Run a periodic calibration check against a fixed fiducial and alert when error exceeds a millimetre
Training only on clean synthetic depth with no sensor noise model
Fix: Inject realistic holes, edge dropout and quantization into simulated depth before training
Judging a method on detection accuracy instead of end-to-end pick success
Fix: Report both, and time the full sense-to-motion cycle including filtering and collision checks
Best Practices
- Normalize depth relative to the working surface rather than in absolute camera coordinates
- Apply non-maximum suppression before any geometric validation to avoid duplicate work
- Accumulate grasp scores across several frames in the robot base frame for temporal stability
- Measure friction of your actual parts and carry it into simulation rather than assuming the default
- Keep a scripted fallback behaviour for when the detector returns nothing above threshold
Interview Questions
Q1: What is an antipodal grasp and why do detectors favor it?
The two contact points face each other along opposing surface normals, so the squeezing force cancels out instead of translating the object. It is the configuration most parallel-jaw hardware can execute reliably.
Q2: Why does domain randomization usually beat an adversarial domain loss for sim-to-real transfer?
Randomization prevents the network from exploiting any single simulated regularity in the first place, so there is no domain gap left to align. Adversarial alignment can only remove feature differences that remain systematic after training.
Q3: How do you handle objects that the depth camera cannot see?
Fall back to RGB-based completion or a monocular depth estimator to fill holes, or switch strategy to a top-down suction cup that tolerates partial geometry.
Q4: Why filter grasps temporally instead of per frame?
Single depth frames contain transient noise and occlusion, so a marginal grasp can spike to the top score. Averaging in the base frame suppresses those spikes and keeps the commanded pose stable across retries.
Key Takeaways
- A grasp is a ranked pose plus a quality score, not a bounding box
- Force closure explains what the quality score is approximating, and why width and approach constraints matter
- Non-maximum suppression and ranked fallback keep downstream collision checks affordable
- Hand-eye calibration error and table clearance reject more good candidates than the network does
- Domain randomization with a short real fine-tune is the cheapest path from simulation to a working cell
- Temporal accumulation across frames is a near-free reliability improvement
- Report end-to-end pick success and cycle time, not just detector accuracy