🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Robotic Waste Sorting with Computer Vision & ROS

Sustainable AIWaste Sorting Robotics🟢 Free Lesson

Robotic Waste Sorting with Computer Vision & ROS

AI Robotic Waste Sorting SystemConveyor Belt + VisionRGB-D Camera + HyperspectralWaste Stream InputMixed materials2-3 m/s conveyorMaterial DetectionInstance segmentationMaterial classificationPick Planning6-DOF arm controlGrasp pose optimizationSorting BinsPlastic/Metal/PaperGlass/Organic/OtherVision Pipeline• YOLOv8 instance segmentation• RGB-D depth estimation• Material identification (ML)• Contamination detectionControl System• ROS2 navigation stack• MoveIt motion planning• Force-torque sensing• Collision avoidancePerformance• Pick rate: 70 items/min• Accuracy: 95%+• Purity improvement: 30%• ROI: 18 months

What is Robotic Waste Sorting?

Robotic waste sorting uses AI vision and robotic manipulation to automatically separate recyclable materials from mixed waste streams. Current manual sorting achieves 70-85% accuracy at 30-40 items per minute per worker, with significant health risks from hazardous materials. AI-powered robotic sorting achieves >95% accuracy at 70+ items per minute, operating 24/7 without fatigue or exposure to dangerous waste.

The waste sorting challenge involves three AI tasks: (1) detection—identifying and localizing individual waste items on a moving conveyor belt, (2) classification—determining material type (plastic, metal, paper, glass, organic), and (3) manipulation—planning and executing grasps that successfully pick items without damage. Each task presents unique challenges: detection must handle occlusion, deformation, and varying lighting; classification must distinguish visually similar materials (e.g., different plastic types); and manipulation must handle irregular shapes, fragile materials, and moving targets.

Computer vision for waste sorting uses multi-spectral imaging: RGB cameras capture visual appearance, depth sensors (Intel RealSense, Microsoft Azure Kinect) provide 3D geometry, and hyperspectral cameras identify material composition through spectral signatures. Different plastics (PET, HDPE, PVC) look similar in RGB but have distinct infrared spectra, enabling accurate material identification that determines recycling viability.

The robotic manipulation challenge is particularly difficult because waste items are highly variable—crushed bottles, tangled wires, flat paper, and heavy glass all require different grasp strategies. Reinforcement learning trains grasping policies through simulated and real-world trial-and-error, discovering robust strategies for diverse object geometries. Force-torque sensing provides feedback during grasping, detecting slip and adjusting grip strength in real-time.

Integration with existing waste management infrastructure requires sorting speeds matching conveyor throughput (typically 2-3 m/s) and compatibility with existing material recovery facility (MRF) layouts. The economic case is compelling: a single robotic sorter replaces 3-5 manual sorters, paying for itself in 12-18 months while improving material purity by 20-30%, which increases recycled material market value by $50-100/tonne.

Project Architecture

Robotic Waste Sorting System ArchitectureCamera SensorsVision NodeROS2 ControllerRobot Arm (6-DOF)BinsVision System• RGB: 1280×720 @ 30fps• Depth: 640×480 @ 30fps• Hyperspectral: 250 bands• YOLOv8-seg detection• Material classifier (ResNet)• 3D pose estimation• Belt speed estimation• Latency: <50ms totalROS2 Control Stack• Perception → Planning pipeline• MoveIt2 motion planning• Conveyor tracking (TF2)• Grasp pose optimization• Force-torque control• Collision avoidance (OctoMap)• Real-time scheduling• Safety interlocksSorting Categories• PET plastic (bottles)• HDPE plastic (containers)• Aluminum cans• Steel cans• Cardboard / Paper• Glass (clear/colored)• Organic / Contaminated• Reject / Hazardous

Tools & Setup

ToolVersionPurpose
Python3.11+Core language
ROS2 Humble-Robot middleware
MoveIt22.8+Motion planning
ultralytics8.1+YOLOv8 detection
torch2.1+Deep learning
opencv-python4.8+Image processing
pyrealsense22.54+Depth camera
numpy1.26+Numerical ops

Step 1: Environment Setup

# ROS2 setup (Ubuntu 22.04)
sudo apt install ros-humble-desktop
sudo apt install ros-humble-moveit
sudo apt install ros-humble-navigation2

pip install ultralytics torch opencv-python pyrealsense2 numpy

Step 2: Waste Detection Model

python
# waste_detection.py
import torch
import torch.nn as nn
from ultralytics import YOLO
from typing import List, Dict, Tuple
import numpy as np


WASTE_CLASSES = {
    0: "empty",
    1: "pet_plastic",
    2: "hdpe_plastic",
    3: "other_plastic",
    4: "aluminum",
    5: "steel",
    6: "cardboard",
    7: "paper",
    8: "glass_clear",
    9: "glass_colored",
    10: "organic",
    11: "contaminated",
    12: "hazardous",
}

MATERIAL_PROPERTIES = {
    "pet_plastic": {"recyclable": True, "density": 1.38, "flexible": True},
    "hdpe_plastic": {"recyclable": True, "density": 0.95, "flexible": True},
    "aluminum": {"recyclable": True, "density": 2.70, "flexible": False},
    "steel": {"recyclable": True, "density": 7.85, "flexible": False},
    "cardboard": {"recyclable": True, "density": 0.70, "flexible": True},
    "paper": {"recyclable": True, "density": 0.80, "flexible": True},
    "glass_clear": {"recyclable": True, "density": 2.50, "flexible": False},
    "glass_colored": {"recyclable": True, "density": 2.50, "flexible": False},
    "organic": {"recyclable": False, "density": 1.00, "flexible": True},
    "contaminated": {"recyclable": False, "density": 1.00, "flexible": True},
    "hazardous": {"recyclable": False, "density": 1.50, "flexible": False},
}


class WasteDetector:
    """YOLOv8-based waste object detector."""

    def __init__(self, model_path: str = "yolov8n-waste.pt"):
        self.model = YOLO(model_path)
        self.confidence_threshold = 0.5

    def detect(
        self,
        image: np.ndarray,
        depth_image: np.ndarray = None,
    ) -> List[Dict]:
        """Detect waste objects in image."""
        results = self.model(image, conf=self.confidence_threshold)

        detections = []
        for result in results:
            boxes = result.boxes
            if boxes is not None:
                for i in range(len(boxes)):
                    box = boxes.xyxy[i].cpu().numpy()
                    conf = float(boxes.conf[i])
                    cls = int(boxes.cls[i])

                    detection = {
                        "bbox": box.tolist(),
                        "confidence": conf,
                        "class_id": cls,
                        "class_name": WASTE_CLASSES.get(cls, "unknown"),
                    }

                    if depth_image is not None:
                        x1, y1, x2, y2 = map(int, box)
                        depth_crop = depth_image[y1:y2, x1:x2]
                        detection["depth_mean"] = float(np.mean(depth_crop))
                        detection["depth_std"] = float(np.std(depth_crop))

                    if detection["class_name"] in MATERIAL_PROPERTIES:
                        detection["material"] = MATERIAL_PROPERTIES[detection["class_name"]]

                    detections.append(detection)

        return sorted(detections, key=lambda d: d["confidence"], reverse=True)

    def estimate_3d_position(
        self,
        detection: Dict,
        camera_intrinsics: Dict,
        conveyor_speed: float,
        conveyor_offset: float,
    ) -> Tuple[float, float, float]:
        """Estimate 3D position from detection and depth."""
        bbox = detection["bbox"]
        depth = detection.get("depth_mean", 1.0)

        cx = (bbox[0] + bbox[2]) / 2
        cy = (bbox[1] + bbox[3]) / 2

        fx = camera_intrinsics["fx"]
        fy = camera_intrinsics["fy"]
        cx_int = camera_intrinsics["cx"]
        cy_int = camera_intrinsics["cy"]

        x = (cx - cx_int) * depth / fx
        y = (cy - cy_int) * depth / fy
        z = depth

        return x, y, z

Grasp Planning

python
# grasp_planner.py
import numpy as np
from typing import Tuple, List, Optional
from dataclasses import dataclass
import torch
import torch.nn as nn


@dataclass
class GraspPose:
    """Grasp pose for robotic picking."""
    position: Tuple[float, float, float]
    orientation: Tuple[float, float, float, float]  # quaternion
    width: float
    depth: float
    score: float
    approach_vector: Tuple[float, float, float]


class GraspQualityNet(nn.Module):
    """Neural network for grasp quality prediction."""

    def __init__(self, input_dim: int = 12):
        super().__init__()
        self.network = nn.Sequential(
            nn.Linear(input_dim, 256),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(256, 128),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(128, 64),
            nn.ReLU(),
            nn.Linear(64, 1),
            nn.Sigmoid(),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.network(x)


class GraspPlanner:
    """Plan grasp poses for waste items."""

    def __init__(self):
        self.quality_net = GraspQualityNet()
        self.approach_angles = np.linspace(0, 2 * np.pi, 12)
        self.grip_widths = [0.02, 0.04, 0.06, 0.08, 0.10]

    def plan_grasp(
        self,
        object_bbox: Tuple[float, float, float, float],
        object_depth: float,
        material_type: str,
        camera_intrinsics: Dict,
        conveyor_transform: np.ndarray = None,
    ) -> Optional[GraspPose]:
        """Plan optimal grasp pose for detected object."""
        candidates = self._generate_candidates(
            object_bbox, object_depth, camera_intrinsics
        )

        scored_candidates = []
        for candidate in candidates:
            features = self._extract_features(candidate, material_type)
            features_tensor = torch.tensor(features, dtype=torch.float32).unsqueeze(0)

            with torch.no_grad():
                quality = self.quality_net(features_tensor).item()

            scored_candidates.append((candidate, quality))

        if not scored_candidates:
            return None

        scored_candidates.sort(key=lambda x: x[1], reverse=True)
        best_candidate, best_score = scored_candidates[0]

        return GraspPose(
            position=best_candidate["position"],
            orientation=best_candidate["orientation"],
            width=best_candidate["width"],
            depth=object_depth,
            score=best_score,
            approach_vector=(0, 0, -1),
        )

    def _generate_candidates(
        self,
        bbox: Tuple[float, float, float, float],
        depth: float,
        intrinsics: Dict,
    ) -> List[Dict]:
        """Generate candidate grasp poses."""
        candidates = []
        cx = (bbox[0] + bbox[2]) / 2
        cy = (bbox[1] + bbox[3]) / 2
        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]

        for angle in self.approach_angles:
            for width in self.grip_widths:
                x = (cx - intrinsics["cx"]) * depth / intrinsics["fx"]
                y = (cy - intrinsics["cy"]) * depth / intrinsics["fy"]

                candidates.append({
                    "position": (x, y, depth),
                    "orientation": self._angle_to_quaternion(angle),
                    "width": width,
                    "approach_angle": angle,
                })

        return candidates

    def _extract_features(
        self, candidate: Dict, material_type: str
    ) -> List[float]:
        """Extract features for quality prediction."""
        material_props = MATERIAL_PROPERTIES.get(material_type, {})
        return [
            candidate["position"][0],
            candidate["position"][1],
            candidate["position"][2],
            candidate["width"],
            candidate["approach_angle"],
            1.0 if material_props.get("flexible", False) else 0.0,
            material_props.get("density", 1.0),
            1.0 if material_props.get("recyclable", False) else 0.0,
            0.0,
            0.0,
            0.0,
            0.0,
        ]

    @staticmethod
    def _angle_to_quaternion(angle: float) -> Tuple[float, float, float, float]:
        """Convert approach angle to quaternion."""
        import math
        half_angle = angle / 2
        return (0, 0, math.sin(half_angle), math.cos(half_angle))

ROS2 Integration

python
# ros2_sorter.py
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image, CameraInfo
from geometry_msgs.msg import Pose, PoseArray, TransformStamped
from std_msgs.msg import String, Float32
import numpy as np
from waste_detection import WasteDetector
from grasp_planner import GraspPlanner


class WasteSorterNode(Node):
    """ROS2 node for robotic waste sorting."""

    def __init__(self):
        super().__init__("waste_sorter")

        self.detector = WasteDetector()
        self.grasp_planner = GraspPlanner()

        self.rgb_sub = self.create_subscription(
            Image, "/camera/color/image_raw", self.rgb_callback, 10
        )
        self.depth_sub = self.create_subscription(
            Image, "/camera/depth/image_raw", self.depth_callback, 10
        )
        self.info_sub = self.create_subscription(
            CameraInfo, "/camera/color/camera_info", self.info_callback, 10
        )

        self.detection_pub = self.create_publisher(
            PoseArray, "/waste/detections", 10
        )
        self.grasp_pub = self.create_publisher(
            Pose, "/waste/grasp_pose", 10
        )
        self.class_pub = self.create_publisher(
            String, "/waste/classification", 10
        )
        self.confidence_pub = self.create_publisher(
            Float32, "/waste/confidence", 10
        )

        self.camera_intrinsics = None
        self.latest_rgb = None
        self.latest_depth = None

        self.get_logger().info("Waste Sorter Node initialized")

    def info_callback(self, msg: CameraInfo):
        """Store camera intrinsics."""
        self.camera_intrinsics = {
            "fx": msg.k[0],
            "fy": msg.k[4],
            "cx": msg.k[2],
            "cy": msg.k[5],
        }

    def rgb_callback(self, msg: Image):
        """Process RGB image."""
        self.latest_rgb = self._image_to_numpy(msg)
        self._process_frame()

    def depth_callback(self, msg: Image):
        """Store depth image."""
        self.latest_depth = self._image_to_numpy(msg)

    def _process_frame(self):
        """Process current frame for detection and grasping."""
        if self.latest_rgb is None or self.camera_intrinsics is None:
            return

        detections = self.detector.detect(self.latest_rgb, self.latest_depth)

        for det in detections[:3]:
            if det["confidence"] < 0.5:
                continue

            pose_array = PoseArray()
            pose = Pose()
            pose.position.x = det.get("depth_mean", 1.0)
            pose.position.y = (det["bbox"][0] + det["bbox"][2]) / 2
            pose.position.z = (det["bbox"][1] + det["bbox"][3]) / 2
            pose_array.poses.append(pose)
            self.detection_pub.publish(pose_array)

            grasp = self.grasp_planner.plan_grasp(
                det["bbox"],
                det.get("depth_mean", 1.0),
                det["class_name"],
                self.camera_intrinsics,
            )

            if grasp:
                grasp_pose = Pose()
                grasp_pose.position.x = grasp.position[0]
                grasp_pose.position.y = grasp.position[1]
                grasp_pose.position.z = grasp.position[2]
                grasp_pose.orientation.w = grasp.orientation[3]
                grasp_pose.orientation.z = grasp.orientation[2]
                self.grasp_pub.publish(grasp_pose)

            class_msg = String()
            class_msg.data = det["class_name"]
            self.class_pub.publish(class_msg)

            conf_msg = Float32()
            conf_msg.data = det["confidence"]
            self.confidence_pub.publish(conf_msg)

    @staticmethod
    def _image_to_numpy(msg: Image) -> np.ndarray:
        """Convert ROS Image message to numpy array."""
        import cv2
        if msg.encoding == "rgb8":
            return np.frombuffer(msg.data, dtype=np.uint8).reshape(
                msg.height, msg.width, 3
            )
        elif msg.encoding == "16UC1":
            return np.frombuffer(msg.data, dtype=np.uint16).reshape(
                msg.height, msg.width
            )
        return np.zeros((msg.height, msg.width, 3), dtype=np.uint8)


def main(args=None):
    rclpy.init(args=args)
    node = WasteSorterNode()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()


if __name__ == "__main__":
    main()

Throughput arithmetic: keeping up with the belt

A sorting cell fails on arithmetic long before it fails on vision. Take a belt carrying items at a 350 mm pitch: at 0.6 m/s it presents 103 items per minute, at 1.5 m/s it presents 257, and at 2.0 m/s it presents 343. Since one arm sustains about 70 picks per minute, the cell needs two arms at the slow speed, four at 1.5 m/s, and five at 2.0 m/s. Sites that cannot fund that many arms slow the belt instead and accept the lower tonnage. Latency tightens the same constraint: an item travels the length of a crushed can in the time your pipeline spends thinking, so at 1.5 m/s a 100 ms budget leaves only 67 mm before the object has moved past the position the planner aimed at. The planner therefore extrapolates the grasp pose forward using measured belt speed, which is why the node tracks belt motion through TF2 instead of stamping poses at capture time.

Belt speedItems per minuteArms needed at 70 picks eachLatency budget for 100 mm of travel
0.6 m/s1032167 ms
1.5 m/s257467 ms
2.0 m/s343550 ms

What the cell costs to run

A 6-DOF arm averaging 350 W across a 24-hour shift draws 8.4 kWh a day, about 0.12 per kWh. Two vision PCs at 150 W add 7.2 kWh and another 2 of electricity while replacing three sorters working three shifts at a loaded 600 a day. The cleanest comparison for a plant manager is picks per kilowatt-hour: 70 picks per minute over 1,440 minutes is 100,800 picks against 15.6 kWh, or about 6,460 picks per kWh. Manual sorting, counting only the sorter's share of labour and lighting, sits near 300. That ratio is what drives a payback inside eighteen months even when the arms themselves cost more than the labour they displace.

Choosing the sensor stack

Buy the cheapest sensor that separates the classes you actually sell. A 300 for a RealSense D435i, contributes 3D geometry for grasp planning and tells flat stock from crushed stock, yet adds no chemical information whatever. Hyperspectral imaging in the 1,000–1,700 nm band is what separates PET from PVC and polyethylene, but a line-scan head costs $4,000–8,000, demands controlled illumination, and slows the lane, so mount it only where resin type changes the bale price rather than across the whole belt.

Results & Impact

MetricManual SortingAI Robotic SortingImprovement
Pick Rate30 items/min70 items/min133%
Accuracy80%95%++15%
Material Purity75%92%+23%
Operating Hours8 hrs/day24 hrs/day3×
Cost per Tonne2569% reduction
Injury RateHighZero100%

Real-World Case Study

AMP Robotics deployed 100+ robotic sorting systems across MRFs in North America, processing 80+ material categories at 80 picks per minute. Their system uses dual-arm robots with computer vision achieving 99% accuracy for common recyclables. The robots process 2,400 items per hour versus 400 for manual sorters, reducing facility labor costs by 60% while improving material purity by 20%. A single system saves approximately 5,000 tonnes of recyclables from landfill annually, equivalent to 8,000 tonnes of CO₂ avoided.

Common Pitfalls

  1. Conveyor Speed Mismatch: Detection latency must be <100ms for 2 m/s conveyors; use GPU inference and predictive tracking
  2. Occlusion Handling: Stacked items require instance segmentation, not just bounding boxes; use Mask R-CNN or YOLOv8-seg
  3. Gripper Design: Parallel jaw grippers fail on round objects; use vacuum or soft grippers for diverse waste
  4. Contamination Detection: Wet or food-contaminated recyclables must be rejected; add contamination classifier
  5. Real-Time Constraints: ROS2 must guarantee <200ms pick cycle; use real-time kernel and priority scheduling

Summary with Key Takeaways

Robotic waste sorting with AI vision achieves 95%+ accuracy at 70+ picks per minute, transforming material recovery economics. The system combines YOLOv8 instance segmentation for detection, material classification for sorting decisions, and grasp planning for robotic manipulation, all integrated through ROS2.

Key innovations include multi-spectral imaging for material identification, reinforcement learning for grasp optimization, and conveyor tracking for dynamic pick planning. The resulting systems pay for themselves in 12-18 months while significantly improving recycling rates and reducing landfill waste.

Common Mistakes

Aiming the gripper at the pose returned by the vision node, so every pick lands behind a fast-moving object

Fix: Extrapolate the pose with measured belt speed and command a lead point, then verify with force-torque feedback before closing the jaws

Adding a hyperspectral camera to solve a pick-rate problem that was really an arm-count problem

Fix: Do the belt arithmetic first: divide items per minute by 70 to size the cell, and only then spend on sensors for the classes that change the bale price

Training the material classifier on laboratory-lit samples and letting it fail on wet, dusty or food-stained items in the real stream

Fix: Collect training frames from the working line in every shift lighting condition, and route low-confidence picks to a reject lane instead of a recycling bin

Key Takeaways

  • Belt speed, pitch and picks per minute determine how many arms a cell needs; vision quality cannot compensate for a short-staffed belt
  • Latency is measured in millimetres of belt travel, so grasp poses must be extrapolated forward rather than used where the object was detected
  • RGB separates shape, depth adds geometry, and only near-infrared spectra separate resins, so match sensor cost to the classes that affect revenue
  • Electricity is a rounding error against labour, which is why a cell paying for itself in twelve to eighteen months remains viable even with multiple arms
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Sustainable AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement