Loading and Visualizing Point Clouds with PCL


#include <iostream>
#include <pcl>
#include <pcl>
#include <pcl>

int main(int argc, char** argv)
{
    // Create a smart pointer to a point cloud
    pcl::PointCloud<:pointxyz>::Ptr pointCloud(new pcl::PointCloud<:pointxyz>);
    
    // Load point cloud data from PCD file
    if (pcl::io::loadPCDFile<:pointxyz>(argv[1], *pointCloud) == -1)
    {
        PCL_ERROR("Failed to read the specified PCD file \n");
        return (-1);
    }
    
    // Display information about the loaded point cloud
    std::cout << "Successfully loaded "
        << pointCloud->width * pointCloud->height
        << " data points from the PCD file. Available fields: "
        << std::endl;
    
    // Optional point data printing (commented out)
    /*
    for (size_t i = 0; i < pointCloud->points.size(); ++i)
        std::cout << "    " << pointCloud->points[i].x
        << " " << pointCloud->points[i].y
        << " " << pointCloud->points[i].z << std::endl;
    */ 

    // Create a cloud viewer window
    pcl::visualization::CloudViewer viewer("Point Cloud Visualization");
    
    // Display the point cloud
    viewer.showCloud(pointCloud);
    
    // Keep the window open until it's closed by the user
    while (!viewer.wasStopped()){}
    
    return (0);
}
</:pointxyz></:pointxyz></:pointxyz></pcl></pcl></pcl></iostream>

Code Explanation

The code begins by including necessary PCL headers for I/O operations, point types, and visualization. The main function is responsible for loading and displaying point cloud data.

The line pcl::PointCloud<:pointxyz>::Ptr pointCloud(new pcl::PointCloud<:pointxyz>)</:pointxyz></:pointxyz> creates a smart pointer (shared_ptr) to a point cloud object. PCL's PointCloud is a template class, and PointXYZ specifies that each point contains x, y, and z coordinates.

The loadPCDFile function reads data from a PCD file into the point cloud object. The function returns -1 if the file cannot be opened, triggering an error message.

Point cloud data can be organized in two ways:

  • Ordered point clouds: Structured as a 2D matrix with width and height dimensions
  • Unordered point clouds: Represented as a 1D array where width equals the number of points and height is 1

In both cases, width * height gives the total number of points in the cloud.

The visualization part creates a CloudViewer object with a specified window title and displays the point cloud using the showCloud method. The while loop keeps the application running until the user closes the visualizaiton window.

This example can be used to visualize any PCD file, including the PCL logo or other 3D point cloud datasets.

Tags: PCL point-cloud 3D-visualization PCD-files C++

Posted on Sun, 10 May 2026 20:59:32 +0000 by denoteone