Remove points outside defined 3D box inside PCL visualizer

Ravi Joshi picture Ravi Joshi · Aug 21, 2017 · Viewed 9.4k times · Source

In a given point cloud, I want to remove all the points which are less than min and greater than max for all x, y and z direction. Below is the sample code:

#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/passthrough.h>
#include <pcl/visualization/pcl_visualizer.h>

// Define min and max for X, Y and Z
float minX = -0.1, minY = -0.5, minZ = -2.5;
float maxX = +0.1, maxY = +0.5, maxZ = +2.5;

int main (int argc, char** argv)
{
    pcl::visualization::PCLVisualizer viewer("Cloud Viewer");

    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr body (new pcl::PointCloud<pcl::PointXYZRGBA>);
    pcl::io::loadPCDFile ("body.pcd", *body);

    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr bodyFiltered (new pcl::PointCloud<pcl::PointXYZRGBA>);

    pcl::PassThrough<pcl::PointXYZRGBA> filter;
    filter.setInputCloud (body);
    filter.setFilterFieldName ("x");
    filter.setFilterLimits (minX, maxX);
    filter.setFilterFieldName ("y");
    filter.setFilterLimits (minY, maxY);
    filter.setFilterFieldName ("z");
    filter.setFilterLimits (minZ, maxZ);
    filter.filter (*bodyFiltered);

    viewer.addPointCloud (bodyFiltered,"body");
    viewer.spin();
    return 0;
}

It seems that only last filter is being applied. Any solution, please?

Answer

Gabriel Devillers picture Gabriel Devillers · Aug 21, 2017

What about using pcl::CropBox? (documentation)

pcl::CropBox<pcl::PointXYZRGBA> boxFilter;
boxFilter.setMin(Eigen::Vector4f(minX, minY, minZ, 1.0));
boxFilter.setMax(Eigen::Vector4f(maxX, maxY, maxZ, 1.0));
boxFilter.setInputCloud(body);
boxFilter.filter(*bodyFiltered);

To know why this filter takes Vector4f (and not Vector3f) see the comments below and this question.