update svn to r776

This commit is contained in:
Razvan Mihalyi 2012-11-19 13:34:43 +01:00
parent 12b8fe558d
commit 357975f78e
71 changed files with 9558 additions and 1324 deletions

View file

@ -0,0 +1,118 @@
### TOOLS
IF(WITH_TOOLS)
### SCAN_RED
add_executable(scan_red scan_red.cc fbr/fbr_global.cc fbr/panorama.cc fbr/scan_cv.cc)
IF(UNIX)
target_link_libraries(scan_red scan dl ANN fbr_cv_io fbr_panorama ${OpenCV_LIBS} ${Boost_LIBRARIES})
ENDIF(UNIX)
IF (WIN32)
target_link_libraries(scan_red scan ANN XGetopt)
ENDIF(WIN32)
### SCAN_DIFF
add_executable(scan_diff scan_diff.cc)
# add_executable(scan_diff2d scan_diff2d.cc ../show/colormanager.cc)
IF(UNIX)
target_link_libraries(scan_diff scan dl ANN)
# target_link_libraries(scan_diff2d scan dl ANN)
ENDIF(UNIX)
IF (WIN32)
target_link_libraries(scan_diff scan ANN XGetopt)
# target_link_libraries(scan_diff2d scan ANN XGetopt)
ENDIF(WIN32)
add_executable(frame_to_graph frame_to_graph.cc)
add_executable(convergence convergence.cc)
add_executable(graph_balancer graph_balancer.cc)
add_executable(exportPoints exportPoints.cc)
add_executable(frames2riegl frames2riegl.cc)
add_executable(frames2pose frames2pose.cc)
add_executable(pose2frames pose2frames.cc)
add_executable(riegl2frames riegl2frames.cc)
add_executable(toGlobal toGlobal.cc)
IF(UNIX)
target_link_libraries(graph_balancer scan ${Boost_GRAPH_LIBRARY} ${Boost_SERIALIZATION_LIBRARY} ${Boost_REGEX_LIBRARY})
target_link_libraries(exportPoints scan dl ANN)
target_link_libraries(toGlobal scan)
ENDIF(UNIX)
IF (WIN32)
target_link_libraries(frame_to_graph XGetopt ${Boost_LIBRARIES})
target_link_libraries(convergence XGetopt ${Boost_LIBRARIES})
target_link_libraries(graph_balancer scan XGetopt ${Boost_LIBRARIES})
target_link_libraries(exportPoints scan ANN XGetopt ${Boost_LIBRARIES})
target_link_libraries(frames2pose XGetopt ${Boost_LIBRARIES})
target_link_libraries(pose2frames XGetopt ${Boost_LIBRARIES})
target_link_libraries(frames2riegl XGetopt ${Boost_LIBRARIES})
target_link_libraries(riegl2frames XGetopt ${Boost_LIBRARIES})
target_link_libraries(toGlobal XGetopt ${Boost_LIBRARIES})
ENDIF(WIN32)
ENDIF(WITH_TOOLS)
### SCANLIB
SET(SCANLIB_SRCS
kd.cc kdManaged.cc kdMeta.cc graphSlam6D.cc
graph.cc icp6D.cc icp6Dapx.cc icp6Dsvd.cc
icp6Dortho.cc icp6Dquat.cc icp6Dhelix.cc icp6Dlumeuler.cc
icp6Dlumquat.cc icp6Ddual.cc lum6Deuler.cc lum6Dquat.cc
ghelix6DQ2.cc gapx6D.cc ann_kd.cc elch6D.cc
elch6Dquat.cc elch6DunitQuat.cc elch6Dslerp.cc elch6Deuler.cc
point_type.cc icp6Dquatscale.cc searchTree.cc Boctree.cc
scan.cc basicScan.cc managedScan.cc metaScan.cc
io_types.cc io_utils.cc pointfilter.cc allocator.cc
)
if(WITH_METRICS)
set(SCANLIB_SRCS ${SCANLIB_SRCS} metrics.cc)
endif(WITH_METRICS)
add_library(scan STATIC ${SCANLIB_SRCS})
FIND_PACKAGE(OpenCV REQUIRED)
target_link_libraries(scan scanclient scanio normals)
IF(UNIX)
target_link_libraries(scan dl)
ENDIF(UNIX)
### EXPORT SHARED LIBS
IF(EXPORT_SHARED_LIBS)
add_library(scan_s SHARED ${SCANLIB_SRCS})
#target_link_libraries(scan_s ${Boost_LIBRARIES} newmat)
target_link_libraries(scan_s newmat_s sparse_s ANN_s )
ENDIF(EXPORT_SHARED_LIBS)
### SLAM6D
IF(WITH_CUDA)
CUDA_COMPILE(CUDA_FILES cuda/CIcpGpuCuda.cu )
add_executable(slam6D slam6D.cc cuda/icp6Dcuda.cc ${CUDA_FILES})
target_link_libraries(slam6D ${CUDA_LIBRARIES} ANN cudpp64)
CUDA_ADD_CUBLAS_TO_TARGET(slam6D)
CUDA_ADD_CUTIL_TO_TARGET(slam6D)
ELSE(WITH_CUDA)
add_executable(slam6D slam6D.cc)
ENDIF(WITH_CUDA)
IF(UNIX)
target_link_libraries(slam6D scan newmat sparse ANN)
ENDIF(UNIX)
IF(WIN32)
target_link_libraries(slam6D scan newmat sparse ANN XGetopt ${Boost_LIBRARIES})
ENDIF(WIN32)
#IF(MSVC)
# INSTALL(TARGETS slam6D RUNTIME DESTINATION ${CMAKE_SOURCE_DIR}/windows)
#ENDIF(MSVC)

View file

@ -0,0 +1,893 @@
/*
* scan implementation
*
* Copyright (C) Andreas Nuechter, Kai Lingemann, Dorit Borrmann, Jan Elseberg, Thomas Escher
*
* Released under the GPL version 3.
*
*/
#include "slam6d/scan.h"
#include "slam6d/basicScan.h"
#include "slam6d/managedScan.h"
#include "slam6d/metaScan.h"
#include "slam6d/searchTree.h"
#include "slam6d/kd.h"
#include "slam6d/Boctree.h"
#include "slam6d/globals.icc"
#include "normals/normals.h"
#ifdef WITH_METRICS
#include "slam6d/metrics.h"
#endif
#ifdef _MSC_VER
#define _NO_PARALLEL_READ
#endif
#ifdef __APPLE__
#define _NO_PARALLEL_READ
#endif
using std::vector;
vector<Scan*> Scan::allScans;
bool Scan::scanserver = false;
void Scan::openDirectory(bool scanserver, const std::string& path, IOType type,
int start, int end)
{
Scan::scanserver = scanserver;
if(scanserver)
ManagedScan::openDirectory(path, type, start, end);
else
BasicScan::openDirectory(path, type, start, end);
}
void Scan::closeDirectory()
{
if(scanserver)
ManagedScan::closeDirectory();
else
BasicScan::closeDirectory();
}
Scan::Scan()
{
unsigned int i;
// pose and transformations
for(i = 0; i < 3; ++i) rPos[i] = 0;
for(i = 0; i < 3; ++i) rPosTheta[i] = 0;
for(i = 0; i < 4; ++i) rQuat[i] = 0;
M4identity(transMat);
M4identity(transMatOrg);
M4identity(dalignxf);
// trees and reduction methods
cuda_enabled = false;
nns_method = -1;
kd = 0;
ann_kd_tree = 0;
// reduction on-demand
reduction_voxelSize = 0.0;
reduction_nrpts = 0;
reduction_pointtype = PointType();
// flags
m_has_reduced = false;
// octtree
octtree_reduction_voxelSize = 0.0;
octtree_voxelSize = 0.0;
octtree_pointtype = PointType();
octtree_loadOct = false;
octtree_saveOct = false;
}
Scan::~Scan()
{
if(kd) delete kd;
}
void Scan::setReductionParameter(double voxelSize, int nrpts, PointType pointtype)
{
reduction_voxelSize = voxelSize;
reduction_nrpts = nrpts;
reduction_pointtype = pointtype;
}
void Scan::setSearchTreeParameter(int nns_method, bool cuda_enabled)
{
searchtree_nnstype = nns_method;
searchtree_cuda_enabled = cuda_enabled;
}
void Scan::setOcttreeParameter(double reduction_voxelSize, double voxelSize, PointType pointtype, bool loadOct, bool saveOct)
{
octtree_reduction_voxelSize = reduction_voxelSize;
octtree_voxelSize = voxelSize;
octtree_pointtype = pointtype;
octtree_loadOct = loadOct;
octtree_saveOct = saveOct;
}
void Scan::clear(unsigned int types)
{
if(types & DATA_XYZ) clear("xyz");
if(types & DATA_RGB) clear("rgb");
if(types & DATA_REFLECTANCE) clear("reflectance");
if(types & DATA_TEMPERATURE) clear("temperature");
if(types & DATA_AMPLITUDE) clear("amplitude");
if(types & DATA_TYPE) clear("type");
if(types & DATA_DEVIATION) clear("deviation");
}
SearchTree* Scan::getSearchTree()
{
// if the search tree hasn't been created yet, calculate everything
if(kd == 0) {
createSearchTree();
}
return kd;
}
void Scan::toGlobal() {
calcReducedPoints();
transform(transMatOrg, INVALID);
}
/**
* Computes a search tree depending on the type.
*/
void Scan::createSearchTree()
{
// multiple threads will call this function at the same time because they
// all work on one pair of Scans, just let the first one (who sees a nullpointer)
// do the creation
boost::lock_guard<boost::mutex> lock(m_mutex_create_tree);
if(kd != 0) return;
// make sure the original points are created before starting the measurement
DataXYZ xyz_orig(get("xyz reduced original"));
#ifdef WITH_METRICS
Timer tc = ClientMetric::create_tree_time.start();
#endif //WITH_METRICS
createSearchTreePrivate();
#ifdef WITH_METRICS
ClientMetric::create_tree_time.end(tc);
#endif //WITH_METRICS
}
void Scan::calcReducedOnDemand()
{
// multiple threads will call this function at the same time
// because they all work on one pair of Scans,
// just let the first one (who sees count as zero) do the reduction
boost::lock_guard<boost::mutex> lock(m_mutex_reduction);
if(m_has_reduced) return;
#ifdef WITH_METRICS
Timer t = ClientMetric::on_demand_reduction_time.start();
#endif //WITH_METRICS
calcReducedOnDemandPrivate();
m_has_reduced = true;
#ifdef WITH_METRICS
ClientMetric::on_demand_reduction_time.end(t);
#endif //WITH_METRICS
}
void Scan::calcNormalsOnDemand()
{
// multiple threads will call this function at the same time
// because they all work on one pair of Scans,
// just let the first one (who sees count as zero) do the reduction
boost::lock_guard<boost::mutex> lock(m_mutex_normals);
if(m_has_normals) return;
calcNormalsOnDemandPrivate();
m_has_normals = true;
}
void Scan::copyReducedToOriginal()
{
#ifdef WITH_METRICS
Timer t = ClientMetric::copy_original_time.start();
#endif //WITH_METRICS
DataXYZ xyz_reduced(get("xyz reduced"));
unsigned int size = xyz_reduced.size();
DataXYZ xyz_reduced_orig(create("xyz reduced original", sizeof(double)*3*size));
for(unsigned int i = 0; i < size; ++i) {
for(unsigned int j = 0; j < 3; ++j) {
xyz_reduced_orig[i][j] = xyz_reduced[i][j];
}
}
#ifdef WITH_METRICS
ClientMetric::copy_original_time.end(t);
#endif //WITH_METRICS
}
void Scan::copyOriginalToReduced()
{
#ifdef WITH_METRICS
Timer t = ClientMetric::copy_original_time.start();
#endif //WITH_METRICS
DataXYZ xyz_reduced_orig(get("xyz reduced original"));
unsigned int size = xyz_reduced_orig.size();
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*size));
for(unsigned int i = 0; i < size; ++i) {
for(unsigned int j = 0; j < 3; ++j) {
xyz_reduced[i][j] = xyz_reduced_orig[i][j];
}
}
#ifdef WITH_METRICS
ClientMetric::copy_original_time.end(t);
#endif //WITH_METRICS
}
/**
* Computes normals for all points
*/
void Scan::calcNormals()
{
cout << "calcNormals" << endl;
DataXYZ xyz(get("xyz"));
DataNormal xyz_normals(create("normal", sizeof(double)*3*xyz.size()));
if(xyz.size() == 0)
throw runtime_error("Could not calculate reduced points, XYZ data is empty");
vector<Point> points;
points.reserve(xyz.size());
vector<Point> normals;
normals.reserve(xyz.size());
for(unsigned int j = 0; j < xyz.size(); j++) {
points.push_back(Point(xyz[j][0], xyz[j][1], xyz[j][2]));
}
const int K_NEIGHBOURS = 10;
calculateNormalsApxKNN(normals, points, K_NEIGHBOURS, get_rPos(), 1.0);
for (unsigned int i = 0; i < normals.size(); ++i) {
xyz_normals[i][0] = normals[i].x;
xyz_normals[i][1] = normals[i].y;
xyz_normals[i][2] = normals[i].z;
}
}
/**
* Computes an octtree of the current scan, then getting the
* reduced points as the centers of the octree voxels.
*/
void Scan::calcReducedPoints()
{
#ifdef WITH_METRICS
Timer t = ClientMetric::scan_load_time.start();
#endif //WITH_METRICS
// get xyz to start the scan load, separated here for time measurement
DataXYZ xyz(get("xyz"));
DataXYZ xyz_normals(get(""));
if (reduction_pointtype.hasNormal()) {
DataXYZ my_xyz_normals(get("normal"));
xyz_normals = my_xyz_normals;
}
DataReflectance reflectance(get(""));
if (reduction_pointtype.hasReflectance()) {
DataReflectance my_reflectance(get("reflectance"));
reflectance = my_reflectance;
}
#ifdef WITH_METRICS
ClientMetric::scan_load_time.end(t);
Timer tl = ClientMetric::calc_reduced_points_time.start();
#endif //WITH_METRICS
if(reduction_voxelSize <= 0.0) {
// copy the points
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*xyz.size()));
for(unsigned int i = 0; i < xyz.size(); ++i) {
for(unsigned int j = 0; j < 3; ++j) {
xyz_reduced[i][j] = xyz[i][j];
}
}
if (reduction_pointtype.hasReflectance()) {
DataReflectance reflectance_reduced(create("reflectance reduced", sizeof(float)*reflectance.size()));
for(unsigned int i = 0; i < xyz.size(); ++i) {
reflectance_reduced[i] = reflectance[i];
}
}
if (reduction_pointtype.hasNormal()) {
DataNormal normal_reduced(create("normal reduced", sizeof(double)*3*xyz.size()));
for(unsigned int i = 0; i < xyz.size(); ++i) {
for(unsigned int j = 0; j < 3; ++j) {
normal_reduced[i][j] = xyz_normals[i][j];
}
}
}
} else {
double **xyz_in = new double*[xyz.size()];
for (unsigned int i = 0; i < xyz.size(); ++i) {
xyz_in[i] = new double[reduction_pointtype.getPointDim()];
unsigned int j = 0;
for (; j < 3; ++j)
xyz_in[i][j] = xyz[i][j];
if (reduction_pointtype.hasReflectance())
xyz_in[i][j++] = reflectance[i];
if (reduction_pointtype.hasNormal())
for (unsigned int l = 0; l < 3; ++l)
xyz_in[i][j] = xyz_normals[i][l];
}
// start reduction
// build octree-tree from CurrentScan
// put full data into the octtree
BOctTree<double> *oct = new BOctTree<double>(xyz_in,
xyz.size(),
reduction_voxelSize,
reduction_pointtype);
vector<double*> center;
center.clear();
if (reduction_nrpts > 0) {
if (reduction_nrpts == 1) {
oct->GetOctTreeRandom(center);
} else {
oct->GetOctTreeRandom(center, reduction_nrpts);
}
} else {
oct->GetOctTreeCenter(center);
}
// storing it as reduced scan
unsigned int size = center.size();
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*size));
DataReflectance reflectance_reduced(get(""));
DataNormal normal_reduced(get(""));
if (reduction_pointtype.hasReflectance()) {
DataReflectance my_reflectance_reduced(create("reflectance reduced",
sizeof(float)*size));
reflectance_reduced = my_reflectance_reduced;
}
if (reduction_pointtype.hasNormal()) {
DataNormal my_normal_reduced(create("normal reduced", sizeof(double)*3*size));
normal_reduced = my_normal_reduced;
}
for(unsigned int i = 0; i < size; ++i) {
unsigned int j = 0;
for (; j < 3; ++j)
xyz_reduced[i][j] = center[i][j];
if (reduction_pointtype.hasReflectance())
reflectance_reduced[i] = center[i][j++];
if (reduction_pointtype.hasNormal())
for (unsigned int l = 0; l < 3; ++l)
normal_reduced[i][l] = center[i][j++];
}
}
#ifdef WITH_METRICS
ClientMetric::calc_reduced_points_time.end(tl);
#endif //WITH_METRICS
}
/**
* Merges the scan's intrinsic coordinates with the robot position.
* @param prevScan The scan that's transformation is extrapolated,
* i.e., odometry extrapolation
*
* For additional information see the following paper (jfr2007.pdf):
*
* Andreas Nüchter, Kai Lingemann, Joachim Hertzberg, and Hartmut Surmann,
* 6D SLAM - 3D Mapping Outdoor Environments Journal of Field Robotics (JFR),
* Special Issue on Quantitative Performance Evaluation of Robotic and Intelligent
* Systems, Wiley & Son, ISSN 1556-4959, Volume 24, Issue 8-9, pages 699 - 722,
* August/September, 2007
*
*/
void Scan::mergeCoordinatesWithRoboterPosition(Scan* prevScan)
{
double tempMat[16], deltaMat[16];
M4inv(prevScan->get_transMatOrg(), tempMat);
MMult(prevScan->get_transMat(), tempMat, deltaMat);
transform(deltaMat, INVALID); //apply delta transformation of the previous scan
}
/**
* The method transforms all points with the given transformation matrix.
*/
void Scan::transformAll(const double alignxf[16])
{
DataXYZ xyz(get("xyz"));
unsigned int i=0 ;
// #pragma omp parallel for
for(; i < xyz.size(); ++i) {
transform3(alignxf, xyz[i]);
}
// TODO: test for ManagedScan compability, may need a touch("xyz") to mark saving the new values
}
//! Internal function of transform which alters the reduced points
void Scan::transformReduced(const double alignxf[16])
{
#ifdef WITH_METRICS
Timer t = ClientMetric::transform_time.start();
#endif //WITH_METRICS
DataXYZ xyz_reduced(get("xyz reduced"));
unsigned int i=0;
// #pragma omp parallel for
for( ; i < xyz_reduced.size(); ++i) {
transform3(alignxf, xyz_reduced[i]);
}
DataNormal normal_reduced(get("normal reduced"));
for (unsigned int i = 0; i < normal_reduced.size(); ++i) {
transform3normal(alignxf, normal_reduced[i]);
}
#ifdef WITH_METRICS
ClientMetric::transform_time.end(t);
#endif //WITH_METRICS
}
//! Internal function of transform which handles the matrices
void Scan::transformMatrix(const double alignxf[16])
{
double tempxf[16];
// apply alignxf to transMat and update pose vectors
MMult(alignxf, transMat, tempxf);
memcpy(transMat, tempxf, sizeof(transMat));
Matrix4ToEuler(transMat, rPosTheta, rPos);
Matrix4ToQuat(transMat, rQuat);
#ifdef DEBUG
cerr << "(" << rPos[0] << ", " << rPos[1] << ", " << rPos[2] << ", "
<< rPosTheta[0] << ", " << rPosTheta[1] << ", " << rPosTheta[2] << ")" << endl;
cerr << transMat << endl;
#endif
// apply alignxf to dalignxf
MMult(alignxf, dalignxf, tempxf);
memcpy(dalignxf, tempxf, sizeof(transMat));
}
/**
* Transforms the scan by a given transformation and writes a new frame. The idea
* is to write for every transformation in all files, such that the show program
* is able to determine, whcih scans have to be drawn in which color. Hidden scans
* (or later processed scans) are written with INVALID.
*
* @param alignxf Transformation matrix
* @param colour Specifies which colour should the written to the frames file
* @param islum Is the transformtion part of LUM, i.e., all scans are transformed?
* In this case only LUM transformation is stored, otherwise all scans are processed
* -1 no transformation is stored
* 0 ICP transformation
* 1 LUM transformation, all scans except last scan
* 2 LUM transformation, last scan only
*/
void Scan::transform(const double alignxf[16], const AlgoType type, int islum)
{
MetaScan* meta = dynamic_cast<MetaScan*>(this);
if(meta) {
for(unsigned int i = 0; i < meta->size(); ++i) {
meta->getScan(i)->transform(alignxf, type, -1);
}
}
#ifdef TRANSFORM_ALL_POINTS
transformAll(alignxf);
#endif //TRANSFORM_ALL_POINTS
#ifdef DEBUG
cerr << alignxf << endl;
cerr << "(" << rPos[0] << ", " << rPos[1] << ", " << rPos[2] << ", "
<< rPosTheta[0] << ", " << rPosTheta[1] << ", " << rPosTheta[2] << ") ---> ";
#endif
// transform points
transformReduced(alignxf);
// update matrices
transformMatrix(alignxf);
// store transformation in frames
if(type != INVALID) {
#ifdef WITH_METRICS
Timer t = ClientMetric::add_frames_time.start();
#endif //WITH_METRICS
bool in_meta;
MetaScan* meta = dynamic_cast<MetaScan*>(this);
int found = 0;
unsigned int scans_size = allScans.size();
switch (islum) {
case -1:
// write no tranformation
break;
case 0:
for(unsigned int i = 0; i < scans_size; ++i) {
Scan* scan = allScans[i];
in_meta = false;
if(meta) {
for(unsigned int j = 0; j < meta->size(); ++j) {
if(meta->getScan(j) == scan) {
found = i;
in_meta = true;
}
}
}
if(scan == this || in_meta) {
found = i;
scan->addFrame(type);
} else {
if(found == 0) {
scan->addFrame(ICPINACTIVE);
} else {
scan->addFrame(INVALID);
}
}
}
break;
case 1:
addFrame(type);
break;
case 2:
for(unsigned int i = 0; i < scans_size; ++i) {
Scan* scan = allScans[i];
if(scan == this) {
found = i;
addFrame(type);
allScans[0]->addFrame(type);
continue;
}
if (found != 0) {
scan->addFrame(INVALID);
}
}
break;
default:
cerr << "invalid point transformation mode" << endl;
}
#ifdef WITH_METRICS
ClientMetric::add_frames_time.end(t);
#endif //WITH_METRICS
}
}
/**
* Transforms the scan by a given transformation and writes a new frame. The idea
* is to write for every transformation in all files, such that the show program
* is able to determine, whcih scans have to be drawn in which color. Hidden scans
* (or later processed scans) are written with INVALID.
*
* @param alignQuat Quaternion for the rotation
* @param alignt Translation vector
* @param colour Specifies which colour should the written to the frames file
* @param islum Is the transformtion part of LUM, i.e., all scans are transformed?
* In this case only LUM transformation is stored, otherwise all scans are processed
* -1 no transformation is stored
* 0 ICP transformation
* 1 LUM transformation, all scans except last scan
* 2 LUM transformation, last scan only
*/
void Scan::transform(const double alignQuat[4], const double alignt[3],
const AlgoType type, int islum)
{
double alignxf[16];
QuatToMatrix4(alignQuat, alignt, alignxf);
transform(alignxf, type, islum);
}
/**
* Transforms the scan, so that the given Matrix
* prepresent the next pose.
*
* @param alignxf Transformation matrix to which this scan will be set to
* @param islum Is the transformation part of LUM?
*/
void Scan::transformToMatrix(double alignxf[16], const AlgoType type, int islum)
{
double tinv[16];
M4inv(transMat, tinv);
transform(tinv, INVALID);
transform(alignxf, type, islum);
}
/**
* Transforms the scan, so that the given Euler angles
* prepresent the next pose.
*
* @param rP Translation to which this scan will be set to
* @param rPT Orientation as Euler angle to which this scan will be set
* @param islum Is the transformation part of LUM?
*/
void Scan::transformToEuler(double rP[3], double rPT[3], const AlgoType type, int islum)
{
#ifdef WITH_METRICS
// called in openmp context in lum6Deuler.cc:422
ClientMetric::transform_time.set_threadsafety(true);
ClientMetric::add_frames_time.set_threadsafety(true);
#endif //WITH_METRICS
double tinv[16];
double alignxf[16];
M4inv(transMat, tinv);
transform(tinv, INVALID);
EulerToMatrix4(rP, rPT, alignxf);
transform(alignxf, type, islum);
#ifdef WITH_METRICS
ClientMetric::transform_time.set_threadsafety(false);
ClientMetric::add_frames_time.set_threadsafety(false);
#endif //WITH_METRICS
}
/**
* Transforms the scan, so that the given Euler angles
* prepresent the next pose.
*
* @param rP Translation to which this scan will be set to
* @param rPQ Orientation as Quaternion to which this scan will be set
* @param islum Is the transformation part of LUM?
*/
void Scan::transformToQuat(double rP[3], double rPQ[4], const AlgoType type, int islum)
{
double tinv[16];
double alignxf[16];
M4inv(transMat, tinv);
transform(tinv, INVALID);
QuatToMatrix4(rPQ, rP, alignxf);
transform(alignxf, type, islum);
}
/**
* Calculates Source\Target
* Calculates a set of corresponding point pairs and returns them. It
* computes the k-d trees and deletes them after the pairs have been
* found. This slow function should be used only for testing
*
* @param pairs The resulting point pairs (vector will be filled)
* @param Target The scan to whiche the points are matched
* @param thread_num number of the thread (for parallelization)
* @param rnd randomized point selection
* @param max_dist_match2 maximal allowed distance for matching
*/
void Scan::getNoPairsSimple(vector <double*> &diff,
Scan* Source, Scan* Target,
int thread_num,
double max_dist_match2)
{
DataXYZ xyz_reduced(Source->get("xyz reduced"));
KDtree* kd = new KDtree(PointerArray<double>(Target->get("xyz reduced")).get(), Target->size<DataXYZ>("xyz reduced"));
cout << "Max: " << max_dist_match2 << endl;
for (unsigned int i = 0; i < xyz_reduced.size(); i++) {
double p[3];
p[0] = xyz_reduced[i][0];
p[1] = xyz_reduced[i][1];
p[2] = xyz_reduced[i][2];
double *closest = kd->FindClosest(p, max_dist_match2, thread_num);
if (!closest) {
diff.push_back(xyz_reduced[i]);
//diff.push_back(closest);
}
}
delete kd;
}
/**
* Calculates a set of corresponding point pairs and returns them. It
* computes the k-d trees and deletes them after the pairs have been
* found. This slow function should be used only for testing
*
* @param pairs The resulting point pairs (vector will be filled)
* @param Source The scan whose points are matched to Targets' points
* @param Target The scan to whiche the points are matched
* @param thread_num number of the thread (for parallelization)
* @param rnd randomized point selection
* @param max_dist_match2 maximal allowed distance for matching
*/
void Scan::getPtPairsSimple(vector <PtPair> *pairs,
Scan* Source, Scan* Target,
int thread_num,
int rnd, double max_dist_match2,
double *centroid_m, double *centroid_d)
{
KDtree* kd = new KDtree(PointerArray<double>(Source->get("xyz reduced")).get(), Source->size<DataXYZ>("xyz reduced"));
DataXYZ xyz_reduced(Target->get("xyz reduced"));
for (unsigned int i = 0; i < xyz_reduced.size(); i++) {
if (rnd > 1 && rand(rnd) != 0) continue; // take about 1/rnd-th of the numbers only
double p[3];
p[0] = xyz_reduced[i][0];
p[1] = xyz_reduced[i][1];
p[2] = xyz_reduced[i][2];
double *closest = kd->FindClosest(p, max_dist_match2, thread_num);
if (closest) {
centroid_m[0] += closest[0];
centroid_m[1] += closest[1];
centroid_m[2] += closest[2];
centroid_d[0] += p[0];
centroid_d[1] += p[1];
centroid_d[2] += p[2];
PtPair myPair(closest, p);
pairs->push_back(myPair);
}
}
centroid_m[0] /= pairs[thread_num].size();
centroid_m[1] /= pairs[thread_num].size();
centroid_m[2] /= pairs[thread_num].size();
centroid_d[0] /= pairs[thread_num].size();
centroid_d[1] /= pairs[thread_num].size();
centroid_d[2] /= pairs[thread_num].size();
delete kd;
}
/**
* Calculates a set of corresponding point pairs and returns them.
* The function uses the k-d trees stored the the scan class, thus
* the function createTrees and deletTrees have to be called before
* resp. afterwards.
* Here we implement the so called "fast corresponding points"; k-d
* trees are not recomputed, instead the apply the inverse transformation
* to to the given point set.
*
* @param pairs The resulting point pairs (vector will be filled)
* @param Source The scan whose points are matched to Targets' points
* @param Target The scan to whiche the points are matched
* @param thread_num number of the thread (for parallelization)
* @param rnd randomized point selection
* @param max_dist_match2 maximal allowed distance for matching
* @return a set of corresponding point pairs
*/
void Scan::getPtPairs(vector <PtPair> *pairs,
Scan* Source, Scan* Target,
int thread_num,
int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d, PairingMode pairing_mode)
{
// initialize centroids
for(unsigned int i = 0; i < 3; ++i) {
centroid_m[i] = 0;
centroid_d[i] = 0;
}
// get point pairs
DataXYZ xyz_reduced(Target->get("xyz reduced"));
DataNormal normal_reduced(Target->get("normal reduced"));
Source->getSearchTree()->getPtPairs(pairs, Source->dalignxf,
xyz_reduced, normal_reduced, 0, xyz_reduced.size(),
thread_num,
rnd, max_dist_match2, sum, centroid_m, centroid_d,
pairing_mode);
// normalize centroids
unsigned int size = pairs->size();
if(size != 0) {
for(unsigned int i = 0; i < 3; ++i) {
centroid_m[i] /= size;
centroid_d[i] /= size;
}
}
}
/**
* Calculates a set of corresponding point pairs and returns them.
* The function uses the k-d trees stored the the scan class, thus
* the function createTrees and delteTrees have to be called before
* resp. afterwards.
*
* @param pairs The resulting point pairs (vector will be filled)
* @param Source The scan whose points are matched to Targets' points
* @param Target The scan to whiche the points are matched
* @param thread_num The number of the thread that is computing ptPairs in parallel
* @param step The number of steps for parallelization
* @param rnd randomized point selection
* @param max_dist_match2 maximal allowed distance for matching
* @param sum The sum of distances of the points
*
* These intermediate values are for the parallel ICP algorithm
* introduced in the paper
* "The Parallel Iterative Closest Point Algorithm"
* by Langis / Greenspan / Godin, IEEE 3DIM 2001
*
*/
void Scan::getPtPairsParallel(vector <PtPair> *pairs,
Scan* Source, Scan* Target,
int thread_num, int step,
int rnd, double max_dist_match2,
double *sum,
double centroid_m[OPENMP_NUM_THREADS][3],
double centroid_d[OPENMP_NUM_THREADS][3],
PairingMode pairing_mode)
{
// initialize centroids
for(unsigned int i = 0; i < 3; ++i) {
centroid_m[thread_num][i] = 0;
centroid_d[thread_num][i] = 0;
}
// get point pairs
SearchTree* search = Source->getSearchTree();
// differentiate between a meta scan (which has no reduced points) and a normal scan
// if Source is also a meta scan it already has a special meta-kd-tree
MetaScan* meta = dynamic_cast<MetaScan*>(Target);
if(meta) {
for(unsigned int i = 0; i < meta->size(); ++i) {
// determine step for each scan individually
DataXYZ xyz_reduced(meta->getScan(i)->get("xyz reduced"));
DataNormal normal_reduced(Target->get("normal reduced"));
unsigned int max = xyz_reduced.size();
unsigned int step = max / OPENMP_NUM_THREADS;
// call ptpairs for each scan and accumulate ptpairs, centroids and sum
search->getPtPairs(&pairs[thread_num], Source->dalignxf,
xyz_reduced, normal_reduced,
step * thread_num, step * thread_num + step,
thread_num,
rnd, max_dist_match2, sum[thread_num],
centroid_m[thread_num], centroid_d[thread_num], pairing_mode);
}
} else {
DataXYZ xyz_reduced(Target->get("xyz reduced"));
DataNormal normal_reduced(Target->get("normal reduced"));
search->getPtPairs(&pairs[thread_num], Source->dalignxf,
xyz_reduced, normal_reduced,
thread_num * step, thread_num * step + step,
thread_num,
rnd, max_dist_match2, sum[thread_num],
centroid_m[thread_num], centroid_d[thread_num], pairing_mode);
}
// normalize centroids
unsigned int size = pairs[thread_num].size();
if(size != 0) {
for(unsigned int i = 0; i < 3; ++i) {
centroid_m[thread_num][i] /= size;
centroid_d[thread_num][i] /= size;
}
}
}
unsigned int Scan::getMaxCountReduced(ScanVector& scans)
{
unsigned int max = 0;
for(std::vector<Scan*>::iterator it = scans.begin(); it != scans.end(); ++it) {
unsigned int count = (*it)->size<DataXYZ>("xyz reduced");
if(count > max)
max = count;
}
return max;
}

View file

@ -0,0 +1,386 @@
/** @file
* @brief Representation of the optimized k-d tree.
* @author Remus Dumitru. Jacobs University Bremen, Germany
* @author Corneliu-Claudiu Prodescu. Jacobs University Bremen, Germany
* @author Andreas Nuechter. Jacobs University Bremen, Germany
* @author Kai Lingemann. Inst. of CS, University of Osnabrueck, Germany
* @author Thomas Escher. Inst. of CS, University of Osnabrueck, Germany
*/
#ifndef __KD_TREE_IMPL_H__
#define __KD_TREE_IMPL_H__
#include "slam6d/kdparams.h"
#include "globals.icc"
#ifdef _MSC_VER
#if !defined _OPENMP && defined OPENMP
#define _OPENMP
#endif
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
class PointCompare {
public:
bool operator() (const std::pair<Point, double>& left,
const std::pair<Point, double>& right)
{
return left.second > right.second;
}
};
/**
* @brief The optimized k-d tree.
*
* A kD tree for points, with limited
* capabilities (find nearest point to
* a given point, or to a ray).
**/
template<class PointData, class AccessorData, class AccessorFunc>
class KDTreeImpl {
public:
inline KDTreeImpl() { }
virtual inline ~KDTreeImpl() {
if (!npts) {
#ifdef WITH_OPENMP_KD
omp_set_num_threads(OPENMP_NUM_THREADS);
#pragma omp parallel for schedule(dynamic)
#endif
for (int i = 0; i < 2; i++) {
if (i == 0 && node.child1) delete node.child1;
if (i == 1 && node.child2) delete node.child2;
}
} else {
if (leaf.p) delete [] leaf.p;
}
}
virtual void create(PointData pts, AccessorData *indices, size_t n) {
AccessorFunc point;
// Find bbox
double xmin = point(pts, indices[0])[0], xmax = point(pts, indices[0])[0];
double ymin = point(pts, indices[0])[1], ymax = point(pts, indices[0])[1];
double zmin = point(pts, indices[0])[2], zmax = point(pts, indices[0])[2];
for(unsigned int i = 1; i < n; i++) {
xmin = min(xmin, point(pts, indices[i])[0]);
xmax = max(xmax, point(pts, indices[i])[0]);
ymin = min(ymin, point(pts, indices[i])[1]);
ymax = max(ymax, point(pts, indices[i])[1]);
zmin = min(zmin, point(pts, indices[i])[2]);
zmax = max(zmax, point(pts, indices[i])[2]);
}
// Leaf nodes
if ((n > 0) && (n <= 10)) {
npts = n;
leaf.p = new AccessorData[n];
// fill leaf index array with indices
for(unsigned int i = 0; i < n; ++i) {
leaf.p[i] = indices[i];
}
return;
}
// Else, interior nodes
npts = 0;
node.center[0] = 0.5 * (xmin+xmax);
node.center[1] = 0.5 * (ymin+ymax);
node.center[2] = 0.5 * (zmin+zmax);
node.dx = 0.5 * (xmax-xmin);
node.dy = 0.5 * (ymax-ymin);
node.dz = 0.5 * (zmax-zmin);
node.r2 = sqr(node.dx) + sqr(node.dy) + sqr(node.dz);
// Find longest axis
if (node.dx > node.dy) {
if (node.dx > node.dz) {
node.splitaxis = 0;
} else {
node.splitaxis = 2;
}
} else {
if (node.dy > node.dz) {
node.splitaxis = 1;
} else {
node.splitaxis = 2;
}
}
// Partition
double splitval = node.center[node.splitaxis];
if ( fabs(max(max(node.dx,node.dy),node.dz)) < 0.01 ) {
npts = n;
leaf.p = new AccessorData[n];
// fill leaf index array with indices
for(unsigned int i = 0; i < n; ++i) {
leaf.p[i] = indices[i];
}
return;
}
AccessorData* left = indices, * right = indices + n - 1;
while(true) {
while(point(pts, *left)[node.splitaxis] < splitval)
left++;
while(point(pts, *right)[node.splitaxis] >= splitval)
right--;
if(right < left)
break;
std::swap(*left, *right);
}
// Build subtrees
int i;
#ifdef WITH_OPENMP_KD // does anybody know the reason why this is slower ?? --Andreas
omp_set_num_threads(OPENMP_NUM_THREADS);
#pragma omp parallel for schedule(dynamic)
#endif
for (i = 0; i < 2; i++) {
if (i == 0) {
node.child1 = new KDTreeImpl();
node.child1->create(pts, indices, left - indices);
}
if (i == 1) {
node.child2 = new KDTreeImpl();
node.child2->create(pts, left, n - (left - indices));
}
}
}
protected:
/**
* storing the parameters of the k-d tree, i.e., the current closest point,
* the distance to the current closest point and the point itself.
* These global variable are needed in this search.
*
* Padded in the parallel case.
*/
#ifdef _OPENMP
#ifdef __INTEL_COMPILER
__declspec (align(16)) static KDParams params[MAX_OPENMP_NUM_THREADS];
#else
static KDParams params[MAX_OPENMP_NUM_THREADS];
#endif //__INTEL_COMPILER
#else
static KDParams params[MAX_OPENMP_NUM_THREADS];
#endif
/**
* number of points. If this is 0: intermediate node. If nonzero: leaf.
*/
int npts;
/**
* Cue the standard rant about anon unions but not structs in C++
*/
union {
/**
* in case of internal node...
*/
struct {
double center[3]; ///< storing the center of the voxel (R^3)
double dx, ///< defining the voxel itself
dy, ///< defining the voxel itself
dz, ///< defining the voxel itself
r2; ///< defining the voxel itself
int splitaxis; ///< defining the kind of splitaxis
KDTreeImpl *child1; ///< pointers to the childs
KDTreeImpl *child2; ///< pointers to the childs
} node;
/**
* in case of leaf node ...
*/
struct {
/**
* store the value itself
* Here we store just a pointer to the data
*/
AccessorData* p;
} leaf;
};
void _FindClosest(const PointData& pts, int threadNum) const {
AccessorFunc point;
// Leaf nodes
if (npts) {
for (int i = 0; i < npts; i++) {
double myd2 = Dist2(params[threadNum].p, point(pts, leaf.p[i]));
if (myd2 < params[threadNum].closest_d2) {
params[threadNum].closest_d2 = myd2;
params[threadNum].closest = point(pts, leaf.p[i]);
}
}
return;
}
// Quick check of whether to abort
double approx_dist_bbox =
max(max(fabs(params[threadNum].p[0]-node.center[0])-node.dx,
fabs(params[threadNum].p[1]-node.center[1])-node.dy),
fabs(params[threadNum].p[2]-node.center[2])-node.dz);
if (approx_dist_bbox >= 0 &&
sqr(approx_dist_bbox) >= params[threadNum].closest_d2)
return;
// Recursive case
double myd = node.center[node.splitaxis] - params[threadNum].p[node.splitaxis];
if (myd >= 0.0) {
node.child1->_FindClosest(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child2->_FindClosest(pts, threadNum);
}
} else {
node.child2->_FindClosest(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child1->_FindClosest(pts, threadNum);
}
}
}
void _FindClosestAlongDir(const PointData& pts, int threadNum) const {
AccessorFunc point;
// Leaf nodes
if (npts) {
for (int i=0; i < npts; i++) {
double p2p[] = { params[threadNum].p[0] - point(pts, leaf.p[i])[0],
params[threadNum].p[1] - point(pts, leaf.p[i])[1],
params[threadNum].p[2] - point(pts, leaf.p[i])[2] };
double myd2 = Len2(p2p) - sqr(Dot(p2p, params[threadNum].dir));
if ((myd2 < params[threadNum].closest_d2)) {
params[threadNum].closest_d2 = myd2;
params[threadNum].closest = point(pts, leaf.p[i]);
}
}
return;
}
// Quick check of whether to abort
double p2c[] = { params[threadNum].p[0] - node.center[0],
params[threadNum].p[1] - node.center[1],
params[threadNum].p[2] - node.center[2] };
double myd2center = Len2(p2c) - sqr(Dot(p2c, params[threadNum].dir));
if (myd2center > node.r2 + params[threadNum].closest_d2 + 2.0f * max(node.r2, params[threadNum].closest_d2))
return;
// Recursive case
if (params[threadNum].p[node.splitaxis] < node.center[node.splitaxis] ) {
node.child1->_FindClosestAlongDir(pts, threadNum);
node.child2->_FindClosestAlongDir(pts, threadNum);
} else {
node.child2->_FindClosestAlongDir(pts, threadNum);
node.child1->_FindClosestAlongDir(pts, threadNum);
}
}
void _FixedRangeSearch(const PointData& pts, int threadNum) const {
AccessorFunc point;
// Leaf nodes
if (npts) {
for (int i = 0; i < npts; i++) {
double myd2 = Dist2(params[threadNum].p, point(pts, leaf.p[i]));
if (myd2 < params[threadNum].closest_d2) {
params[threadNum].closest = point(pts, leaf.p[i]);
Point newPt;
double* currPt = point(pts, leaf.p[i]);
newPt.x = currPt[0];
newPt.y = currPt[1];
newPt.z = currPt[2];
params[threadNum].heap.push_back(std::make_pair(newPt, myd2));
std::push_heap(params[threadNum].heap.begin(),
params[threadNum].heap.end(),
PointCompare());
}
}
return;
}
// Quick check of whether to abort
double approx_dist_bbox =
max(max(fabs(params[threadNum].p[0]-node.center[0])-node.dx,
fabs(params[threadNum].p[1]-node.center[1])-node.dy),
fabs(params[threadNum].p[2]-node.center[2])-node.dz);
if (approx_dist_bbox >= 0 &&
sqr(approx_dist_bbox) >= params[threadNum].closest_d2)
return;
// Recursive case
double myd = node.center[node.splitaxis] - params[threadNum].p[node.splitaxis];
if (myd >= 0.0) {
node.child1->_FixedRangeSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child2->_FixedRangeSearch(pts, threadNum);
}
} else {
node.child2->_FixedRangeSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child1->_FixedRangeSearch(pts, threadNum);
}
}
}
void _KNNSearch(const PointData& pts, int threadNum) const {
AccessorFunc point;
// Leaf nodes
if (npts) {
for (int i = 0; i < npts; i++) {
double myd2 = Dist2(params[threadNum].p, point(pts, leaf.p[i]));
if (myd2 < params[threadNum].closest_d2) {
Point newPt;
double* currPt = point(pts, leaf.p[i]);
newPt.x = currPt[0];
newPt.y = currPt[1];
newPt.z = currPt[2];
params[threadNum].heap.push_back(std::make_pair(newPt, myd2));
std::push_heap(params[threadNum].heap.begin(),
params[threadNum].heap.end(),
PointCompare());
params[threadNum].closest = point(pts, leaf.p[i]);
}
}
return;
}
// Quick check of whether to abort
double approx_dist_bbox =
max(max(fabs(params[threadNum].p[0]-node.center[0])-node.dx,
fabs(params[threadNum].p[1]-node.center[1])-node.dy),
fabs(params[threadNum].p[2]-node.center[2])-node.dz);
if (approx_dist_bbox >= 0 &&
sqr(approx_dist_bbox) >= params[threadNum].closest_d2)
return;
// Recursive case
double myd = node.center[node.splitaxis] - params[threadNum].p[node.splitaxis];
if (myd >= 0.0) {
node.child1->_KNNSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child2->_KNNSearch(pts, threadNum);
}
} else {
node.child2->_KNNSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child1->_KNNSearch(pts, threadNum);
}
}
}
};
#endif

View file

@ -0,0 +1,39 @@
/**
* @file
* @brief IO of a 3D scan given in ply format
* @author Andreas Nuechter
*/
#ifndef __SCAN_IO_PLY_H__
#define __SCAN_IO_PLY_H__
#include "scan_io.h"
/**
* @brief 3D scan loader for UOS scans
*
* The compiled class is available as shared object file
*/
class ScanIO_ply : public ScanIO {
public:
virtual std::list<std::string> readDirectory(const char* dir_path,
unsigned int start,
unsigned int end);
virtual void readPose(const char* dir_path,
const char* identifier,
double* pose);
virtual void readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation);
virtual bool supports(IODataType type);
};
#endif

View file

@ -0,0 +1,68 @@
/** @file
* @brief Representation of the optimized k-d tree.
* @author Andreas Nuechter. Institute of Computer Science, University of Osnabrueck, Germany.
* @author Kai Lingemann. Institute of Computer Science, University of Osnabrueck, Germany.
* @author Thomas Escher
*/
#ifndef __KD_H__
#define __KD_H__
#include "slam6d/kdparams.h"
#include "slam6d/searchTree.h"
#include "slam6d/kdTreeImpl.h"
#ifdef _MSC_VER
#if !defined _OPENMP && defined OPENMP
#define _OPENMP
#endif
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
struct Void { };
struct PtrAccessor {
inline double *operator() (Void, double* indices) {
return indices;
}
};
/**
* @brief The optimized k-d tree.
*
* A kD tree for points, with limited
* capabilities (find nearest point to
* a given point, or to a ray).
**/
class KDtree : public SearchTree, private KDTreeImpl<Void, double*, PtrAccessor>
{
public:
KDtree(double **pts, int n);
virtual ~KDtree();
virtual double *FindClosest(double *_p,
double maxdist2,
int threadNum = 0) const;
virtual double *FindClosestAlongDir(double *_p,
double *_dir,
double maxdist2,
int threadNum = 0) const;
virtual vector<Point> kNearestNeighbors(double *_p,
int k,
double sqRad2,
int threadNum = 0) const;
virtual vector<Point> fixedRangeSearch(double *_p,
double sqRad2,
int threadNum = 0) const;
};
#endif

View file

@ -0,0 +1,186 @@
/*
* searchTree implementation
*
* Copyright (C) Jan Elseberg, Andreas Nuechter
*
* Released under the GPL version 3.
*
*/
/**
* @file
* @brief Representation of a general search trees
* @author Jan Elseberg. Jacobs University Bremen gGmbH, Germany
* @author Andreas Nuechter. Jacobs University Bremen gGmbH, Germany
*/
#include "slam6d/searchTree.h"
#include "slam6d/scan.h"
#include "slam6d/globals.icc"
#include <stdexcept>
double *SearchTree::FindClosestAlongDir(double *_p, double *_dir, double maxdist2, int threadNum) const
{
throw std::runtime_error("Method FindClosestAlongDir is not implemented");
}
void SearchTree::getPtPairs(vector <PtPair> *pairs,
double *source_alignxf, // source
double * const *q_points,
unsigned int startindex, unsigned int endindex, // target
int thread_num,
int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d)
{
// prepare this tree for resource access in FindClosest
lock();
double local_alignxf_inv[16];
M4inv(source_alignxf, local_alignxf_inv);
// t is the original point from target, s is the (inverted) query point from target and then
// the closest point in source
double t[3], s[3];
for (unsigned int i = startindex; i < endindex; i++) {
if (rnd > 1 && rand(rnd) != 0) continue; // take about 1/rnd-th of the numbers only
t[0] = q_points[i][0];
t[1] = q_points[i][1];
t[2] = q_points[i][2];
transform3(local_alignxf_inv, t, s);
double *closest = this->FindClosest(s, max_dist_match2, thread_num);
if (closest) {
transform3(source_alignxf, closest, s);
// This should be right, model=Source=First=not moving
centroid_m[0] += s[0];
centroid_m[1] += s[1];
centroid_m[2] += s[2];
centroid_d[0] += t[0];
centroid_d[1] += t[1];
centroid_d[2] += t[2];
PtPair myPair(s, t);
double p12[3] = {
myPair.p1.x - myPair.p2.x,
myPair.p1.y - myPair.p2.y,
myPair.p1.z - myPair.p2.z };
sum += Len2(p12);
pairs->push_back(myPair);
/*cout << "PTPAIR" << i << " "
<< p[0] << " "
<< p[1] << " "
<< p[2] << " - "
<< q_points[i][0] << " "
<< q_points[i][1] << " "
<< q_points[i][2] << " " << Len2(p12) << endl; */
}
}
// release resource access lock
unlock();
return;
}
void SearchTree::getPtPairs(vector <PtPair> *pairs,
double *source_alignxf, // source
const DataXYZ& xyz_r, const DataNormal& normal_r,
unsigned int startindex, unsigned int endindex, // target
int thread_num,
int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d,
PairingMode pairing_mode)
{
// prepare this tree for resource access in FindClosest
lock();
double local_alignxf_inv[16];
M4inv(source_alignxf, local_alignxf_inv);
// t is the original point from target, s is the (inverted) query point from target and then
// the closest point in source
double t[3], s[3], normal[3];
for (unsigned int i = startindex; i < endindex; i++) {
if (rnd > 1 && rand(rnd) != 0) continue; // take about 1/rnd-th of the numbers only
t[0] = xyz_r[i][0];
t[1] = xyz_r[i][1];
t[2] = xyz_r[i][2];
transform3(local_alignxf_inv, t, s);
double *closest;
if (pairing_mode != CLOSEST_POINT) {
normal[0] = normal_r[i][0];
normal[1] = normal_r[i][1];
normal[2] = normal_r[i][2];
Normalize3(normal);
}
if (pairing_mode == CLOSEST_POINT_ALONG_NORMAL) {
transform3normal(local_alignxf_inv, normal);
closest = this->FindClosestAlongDir(s, normal, max_dist_match2, thread_num);
// discard points farther than 20 cm
if (closest && sqrt(Dist2(closest, s)) > 20) closest = NULL;
} else {
closest = this->FindClosest(s, max_dist_match2, thread_num);
}
if (closest) {
transform3(source_alignxf, closest, s);
if (pairing_mode == CLOSEST_PLANE) {
// need to mutate s if we are looking for closest point-to-plane
// s_ = (n,s-t)*n + t
// to find the projection of s onto plane formed by normal n and point t
double tmp[3], s_[3];
double dot;
sub3(s, t, tmp);
dot = Dot(normal, tmp);
scal_mul3(normal, dot, tmp);
add3(tmp, t, s_);
s[0] = s_[0];
s[1] = s_[1];
s[2] = s_[2];
}
// This should be right, model=Source=First=not moving
centroid_m[0] += s[0];
centroid_m[1] += s[1];
centroid_m[2] += s[2];
centroid_d[0] += t[0];
centroid_d[1] += t[1];
centroid_d[2] += t[2];
PtPair myPair(s, t);
double p12[3] = {
myPair.p1.x - myPair.p2.x,
myPair.p1.y - myPair.p2.y,
myPair.p1.z - myPair.p2.z };
sum += Len2(p12);
pairs->push_back(myPair);
/*cout << "PTPAIR" << i << " "
<< p[0] << " "
<< p[1] << " "
<< p[2] << " - "
<< q_points[i][0] << " "
<< q_points[i][1] << " "
<< q_points[i][2] << " " << Len2(p12) << endl; */
}
}
// release resource access lock
unlock();
return;
}

View file

@ -0,0 +1,42 @@
/**
* @file scan_io_uosr.h
* @brief IO of a 3D scan in xyz file format plus an intensity
* @author Billy Okal
*/
#ifndef __SCAN_IO_XYZR_H__
#define __SCAN_IO_XYZR_H__
#include "scan_io.h"
/**
* @brief IO of a 3D scan in uos file format plus a
* reflectance/intensity/temperature value
*
* The compiled class is available as shared object file
*/
class ScanIO_xyzr : public ScanIO {
public:
virtual std::list<std::string> readDirectory(const char* dir_path,
unsigned int start,
unsigned int end);
virtual void readPose(const char* dir_path,
const char* identifier,
double* pose);
virtual void readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation);
virtual bool supports(IODataType type);
};
#endif

View file

@ -0,0 +1,55 @@
/**
* @file
* @brief Representation of the parameter of a k-d tree
* @author Andreas Nuechter. jacobs University Bremen, Germany.
*/
#ifndef __KDPARAMS_H__
#define __KDPARAMS_H__
#include "slam6d/point.h"
#include <vector>
/**
* @brief Contains the intermediate (static) values of a k-d tree
*
* A parameter class for the latter k-d tree.
* Includes the padding for parallelizetion
* to avoid cache conflicts.
**/
class KDParams
{
public:
/**
* pointer to the closest point. size = 4 bytes of 32 bit machines
*/
double *closest;
/**
* distance to the closest point. size = 8 bytes
*/
double closest_d2;
/**
* pointer to the point, size = 4 bytes of 32 bit machines
*/
double *p;
/**
* pointer to direction vector, if we're using FindClosestAlongDir
*/
double *dir;
/**
* heap for KNN.
*/
std::vector<std::pair<Point, double> > heap;
/**
* expand to 128 bytes to avoid false-sharing, 16 bytes from above + 28*4 bytes = 128 bytes
*/
int padding[28];
};
#endif

View file

@ -0,0 +1,851 @@
/*
* compacttree implementation
*
* Copyright (C) Jan Elseberg, Kai Lingemann, Jan Elseberg
*
* Released under the GPL version 3.
*
*/
/**
* @file
* @brief Efficient representation of an octree
* @author Jan Elsberg. Automation Group, Jacobs University Bremen gGmbH, Germany.
* @author Kai Lingemann. Institute of Computer Science, University of Osnabrueck, Germany.
* @author Andreas Nuechter. Institute of Computer Science, University of Osnabrueck, Germany.
*/
#include <stdio.h>
#include <vector>
using std::vector;
#include <deque>
using std::deque;
#include <set>
using std::set;
#include <list>
using std::list;
#include <iostream>
#include <fstream>
#include <string>
#include "slam6d/globals.icc"
#include "slam6d/point_type.h"
#include "slam6d/Boctree.h"
#include "show/compacttree.h"
#include "show/colormanager.h"
#include "show/scancolormanager.h"
#include "show/viewcull.h"
using namespace show;
compactTree::~compactTree(){
delete alloc;
delete[] mins;
delete[] maxs;
}
void compactTree::AllPoints( cbitoct &node, vector<double*> &vp, double center[3], double size) {
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
tshort *point = children->getPoints();
lint length = children->getLength();
for(unsigned int iterator = 0; iterator < length; iterator++ ) {
double *p = new double[3];
//cout << point[0] << " " << point[1] << " " << point[2] << endl;
for (unsigned int k = 0; k < 3; k++){
p[k] = point[k] * precision + ccenter[k];
}
vp.push_back(p);
point+=POINTDIM;
}
} else { // recurse
AllPoints( children->node, vp, ccenter, size/2.0);
}
++children; // next child
}
}
}
void compactTree::GetOctTreeCenter(vector<double*>&c, cbitoct &node, double *center, double size) {
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (unsigned char i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
double * cp = new double[POINTDIM];
for (unsigned int iterator = 0; iterator < POINTDIM; iterator++) {
cp[iterator] = ccenter[iterator];
}
c.push_back(cp);
} else { // recurse
GetOctTreeCenter(c, children->node, ccenter, size/2.0);
}
++children; // next child
}
}
}
long compactTree::countNodes(cbitoct &node) {
long result = 0;
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf
// ++result;
} else { // recurse
result += countNodes(children->node) + 1;
}
++children; // next child
}
}
return result;
}
long compactTree::countLeaves(cbitoct &node) {
long result = 0;
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf
lint nrpts = children->getLength();
result += POINTDIM*nrpts + 1;
} else { // recurse
result += countLeaves(children->node);
}
++children; // next child
}
}
return result;
}
void compactTree::deletetNodes(cbitoct &node) {
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
bool haschildren = false;
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf
tshort *points = children->getPoints();
delete [] points;
// delete [] children->points;
} else { // recurse
deletetNodes(children->node);
}
++children; // next child
haschildren = true;
}
}
// delete children
if (haschildren) {
cbitoct::getChildren(node, children);
delete[] children;
}
}
unsigned long compactTree::maxTargetPoints( cbitoct &node ) {
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
unsigned long max = 0;
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
lint length = children->getLength();
if (length > max) max = length;
} else { // recurse
unsigned long tp = maxTargetPoints( children->node);
if (tp > max) max = tp;
}
++children; // next child
}
}
return max*POPCOUNT(node.valid);
}
void compactTree::displayOctTreeAll( cbitoct &node, double *center, double size) {
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
tshort *point = children->getPoints();
lint length = children->getLength();
glBegin(GL_POINTS);
for(unsigned int iterator = 0; iterator < length; iterator++ ) {
if(cm) cm->setColor(point);
//cout << "C " << point[1] << " " << cm << endl;
//glVertex3f( point[0], point[1], point[2]);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
point+=POINTDIM;
}
glEnd();
} else { // recurse
displayOctTreeAll( children->node, ccenter, size/2.0);
}
++children; // next child
}
}
}
void compactTree::displayOctTreeAllCulled( cbitoct &node, double *center, double size ) {
int res = CubeInFrustum2(center[0], center[1], center[2], size);
if (res==0) return; // culled do not continue with this branch of the tree
if (res == 2) { // if entirely within frustrum discontinue culling
displayOctTreeAll(node, center, size);
return;
}
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
// check if leaf is visible
if ( CubeInFrustum(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) {
tshort *point = children->getPoints();
lint length = children->getLength();
glBegin(GL_POINTS);
for(unsigned int iterator = 0; iterator < length; iterator++ ) {
if(cm) cm->setColor(point);
//glVertex3f( point[0], point[1], point[2]);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
point+=POINTDIM;
}
glEnd();
}
} else { // recurse
displayOctTreeAllCulled( children->node, ccenter, size/2.0);
}
++children; // next child
}
}
}
void compactTree::displayOctTreeCulledLOD(long targetpts, cbitoct &node, double *center, double size ) {
if (targetpts <= 0) return; // no need to display anything
int res = CubeInFrustum2(center[0], center[1], center[2], size);
if (res==0) return; // culled do not continue with this branch of the tree
if (res == 2) { // if entirely within frustrum discontinue culling
displayOctTreeLOD(targetpts, node, center, size);
return;
}
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
unsigned short nc = POPCOUNT(node.valid);
long newtargetpts = targetpts;
if (nc > 0) {
newtargetpts = newtargetpts/nc;
if (newtargetpts <= 0 ) return;
}
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
// check if leaf is visible
if ( CubeInFrustum(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) {
tshort *point = children->getPoints();
lint length = children->getLength();
glBegin(GL_POINTS);
if (length > 10 && !LOD(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) { // only a single pixel on screen only paint one point
if(cm) cm->setColor(point);
//glVertex3f( point[0], point[1], point[2]);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
} else if (length <= newtargetpts) { // more points requested than possible, plot all
for(unsigned int iterator = 0; iterator < length; iterator++ ) {
if(cm) cm->setColor(point);
//glVertex3f( point[0], point[1], point[2]);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
point+=POINTDIM;
}
} else { // select points to show
// TODO smarter subselection of points here
double each = (double)POINTDIM * (double)((double)length/(double)newtargetpts);
tshort *p;
int index;
for(unsigned int iterator = 0; iterator < newtargetpts; iterator++ ) {
index = (double)iterator * each;
p = point + index - index%POINTDIM;
if(cm) cm->setColor(p);
//glVertex3f( p[0], p[1], p[2]);
glVertex3f( p[0] * precision + ccenter[0], p[1] * precision + ccenter[1], p[2] * precision + ccenter[2]);
//point += each;
}
}
glEnd();
}
} else { // recurse
displayOctTreeCulledLOD(newtargetpts, children->node, ccenter, size/2.0);
}
++children; // next child
}
}
}
void compactTree::displayOctTreeLOD(long targetpts, cbitoct &node, double *center, double size ) {
if (targetpts <= 0) return; // no need to display anything
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
unsigned short nc = POPCOUNT(node.valid);
long newtargetpts = targetpts;
if (nc > 0) {
newtargetpts = newtargetpts/nc;
if (newtargetpts <= 0 ) return;
}
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
tshort *point = children->getPoints();
lint length = children->getLength();
glBegin(GL_POINTS);
/* if (length > 10 && !LOD(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) { // only a single pixel on screen only paint one point
if(cm) cm->setColor(point);
//glVertex3f( point[0], point[1], point[2]);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
} else*/ if (length <= newtargetpts) { // more points requested than possible, plot all
for(unsigned int iterator = 0; iterator < length; iterator++ ) {
if(cm) cm->setColor(point);
//glVertex3f( point[0], point[1], point[2]);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
point+=POINTDIM;
}
} else { // select points to show
// TODO smarter subselection of points here
double each = (double)POINTDIM * (double)((double)length/(double)newtargetpts);
tshort *p;
int index;
for(unsigned int iterator = 0; iterator < newtargetpts; iterator++ ) {
index = (double)iterator * each;
p = point + index - index%POINTDIM;
if(cm) cm->setColor(p);
//glVertex3f( p[0], p[1], p[2]);
glVertex3f( p[0] * precision + ccenter[0], p[1] * precision + ccenter[1], p[2] * precision + ccenter[2]);
//point += each;
}
}
glEnd();
} else { // recurse
displayOctTreeLOD(newtargetpts, children->node, ccenter, size/2.0);
}
++children; // next child
}
}
}
void compactTree::displayOctTreeCulledLOD2(float ratio, cbitoct &node, double *center, double size ) {
int res = CubeInFrustum2(center[0], center[1], center[2], size);
if (res==0) return; // culled do not continue with this branch of the tree
if (res == 2) { // if entirely within frustrum discontinue culling
displayOctTreeLOD2(ratio, node, center, size);
return;
}
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
// check if leaf is visible
if ( CubeInFrustum(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) {
tshort *point = children->getPoints();
lint length = children->getLength();
int l = LOD2(ccenter[0], ccenter[1], ccenter[2], size/2.0); // only a single pixel on screen only paint one point
l = max((int)(l*l*ratio), 0);
if (l != 0) {
if ((int)length > l ) {
double each = (double)POINTDIM * (double)((double)length/(double)l);
tshort *p;
int index;
for(int iterator = 0; iterator < l; iterator++ ) {
index = (double)iterator * each;
p = point + index - index%POINTDIM;
if(cm) cm->setColor(p);
glVertex3f( p[0] * precision + ccenter[0], p[1] * precision + ccenter[1], p[2] * precision + ccenter[2]);
}
} else if ((int)length <= l) {
for(unsigned int iterator = 0; iterator < length; iterator++ ) {
if(cm) cm->setColor(point);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
point+=POINTDIM;
}
} else if (l == 1) {
if(cm) cm->setColor(point);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
}
}
}
} else { // recurse
int l = LOD2(ccenter[0], ccenter[1], ccenter[2], size/2.0); // only a single pixel on screen only paint one point
l = max((int)(l*l*ratio), 0);
if (l > 0) {
displayOctTreeCulledLOD2(ratio, children->node, ccenter, size/2.0);
}
}
++children; // next child
}
}
}
void compactTree::displayOctTreeLOD2(float ratio, cbitoct &node, double *center, double size ) {
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center
tshort *point = children->getPoints();
lint length = children->getLength();
int l = LOD2(ccenter[0], ccenter[1], ccenter[2], size/2.0); // only a single pixel on screen only paint one point
l = max((int)(l*l*ratio), 0);
if (l > 1) {
if ((int)length > l ) {
double each = (double)POINTDIM * (double)((double)length/(double)l);
tshort *p;
int index;
for(int iterator = 0; iterator < l; iterator++ ) {
index = (double)iterator * each;
p = point + index - index%POINTDIM;
if(cm) cm->setColor(p);
glVertex3f( p[0] * precision + ccenter[0], p[1] * precision + ccenter[1], p[2] * precision + ccenter[2]);
}
} else if ((int)length <= l) {
for(unsigned int iterator = 0; iterator < length; iterator++ ) {
if(cm) cm->setColor(point);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
point+=POINTDIM;
}
}
} else {
if(cm) cm->setColor(point);
glVertex3f( point[0] * precision + ccenter[0], point[1] * precision + ccenter[1], point[2] * precision + ccenter[2]);
}
} else { // recurse
int l = LOD2(ccenter[0], ccenter[1], ccenter[2], size/2.0); // only a single pixel on screen only paint one point
l = max((int)(l*l*ratio), 0);
if (l > 0) {
displayOctTreeLOD2(ratio, children->node, ccenter, size/2.0);
}
}
++children; // next child
}
}
}
void compactTree::displayOctTreeCAllCulled( cbitoct &node, double *center, double size, double minsize ) {
int res = CubeInFrustum2(center[0], center[1], center[2], size);
if (res==0) return; // culled do not continue with this branch of the tree
if (res == 2) { // if entirely within frustrum discontinue culling
displayOctTreeCAll(node, center, size, minsize);
return;
}
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf || minsize > size ) { // if ith node is leaf get center
// check if leaf is visible
if ( CubeInFrustum(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) {
showCube(ccenter, size/2.0);
}
} else { // recurse
displayOctTreeCAllCulled( children->node, ccenter, size/2.0, minsize);
}
++children; // next child
}
}
}
void compactTree::displayOctTreeCAll( cbitoct &node, double *center, double size, double minsize ) {
double ccenter[3];
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
childcenter(center, ccenter, size, i); // childrens center
if ( ( 1 << i ) & node.leaf || minsize > size ) { // if ith node is leaf get center
showCube(ccenter, size/2.0);
} else { // recurse
displayOctTreeCAll( children->node, ccenter, size/2.0, minsize);
}
++children; // next child
}
}
}
void compactTree::showCube(double *center, double size) {
glLineWidth(1.0);
glBegin(GL_QUADS); // draw a cube with 6 quads
glColor3f(0.0f,1.0f,0.0f); // Set The Color To Green
glVertex3f(center[0] + size, center[1] + size, center[2] - size);
glVertex3f(center[0] - size, center[1] + size, center[2] - size);
glVertex3f(center[0] - size, center[1] + size, center[2] + size);
glVertex3f(center[0] + size, center[1] + size, center[2] + size);
glColor3f(1.0f,0.5f,0.0f); // Set The Color To Orange
glVertex3f(center[0] + size, center[1] - size, center[2] + size);
glVertex3f(center[0] - size, center[1] - size, center[2] + size);
glVertex3f(center[0] - size, center[1] - size, center[2] - size);
glVertex3f(center[0] + size, center[1] - size, center[2] - size);
glColor3f(1.0f,0.0f,0.0f); // Set The Color To Red
glVertex3f(center[0] + size, center[1] + size, center[2] + size);
glVertex3f(center[0] - size, center[1] + size, center[2] + size);
glVertex3f(center[0] - size, center[1] - size, center[2] + size);
glVertex3f(center[0] + size, center[1] - size, center[2] + size);
glColor3f(1.0f,1.0f,0.0f); // Set The Color To Yellow
glVertex3f(center[0] + size, center[1] - size, center[2] - size);
glVertex3f(center[0] - size, center[1] - size, center[2] - size);
glVertex3f(center[0] - size, center[1] + size, center[2] - size);
glVertex3f(center[0] + size, center[1] + size, center[2] - size);
glColor3f(0.0f,0.0f,1.0f); // Set The Color To Blue
glVertex3f(center[0] - size, center[1] + size, center[2] + size);
glVertex3f(center[0] - size, center[1] + size, center[2] - size);
glVertex3f(center[0] - size, center[1] - size, center[2] - size);
glVertex3f(center[0] - size, center[1] - size, center[2] + size);
glColor3f(1.0f,0.0f,1.0f); // Set The Color To Violet
glVertex3f(center[0] + size, center[1] + size, center[2] - size);
glVertex3f(center[0] + size, center[1] + size, center[2] + size);
glVertex3f(center[0] + size, center[1] - size, center[2] + size);
glVertex3f(center[0] + size, center[1] - size, center[2] - size);
glEnd();
}
template <class T>
void compactTree::selectRay(vector<T *> &points) {
//selectRay(points, *root, center, size);
}
void compactTree::childcenter(double *pcenter, double *ccenter, double size, unsigned char i) {
switch (i) {
case 0:
ccenter[0] = pcenter[0] - size / 2.0;
ccenter[1] = pcenter[1] - size / 2.0;
ccenter[2] = pcenter[2] - size / 2.0;
break;
case 1:
ccenter[0] = pcenter[0] + size / 2.0;
ccenter[1] = pcenter[1] - size / 2.0;
ccenter[2] = pcenter[2] - size / 2.0;
break;
case 2:
ccenter[0] = pcenter[0] - size / 2.0;
ccenter[1] = pcenter[1] + size / 2.0;
ccenter[2] = pcenter[2] - size / 2.0;
break;
case 3:
ccenter[0] = pcenter[0] + size / 2.0;
ccenter[1] = pcenter[1] + size / 2.0;
ccenter[2] = pcenter[2] - size / 2.0;
break;
case 4:
ccenter[0] = pcenter[0] - size / 2.0;
ccenter[1] = pcenter[1] - size / 2.0;
ccenter[2] = pcenter[2] + size / 2.0;
break;
case 5:
ccenter[0] = pcenter[0] + size / 2.0;
ccenter[1] = pcenter[1] - size / 2.0;
ccenter[2] = pcenter[2] + size / 2.0;
break;
case 6:
ccenter[0] = pcenter[0] - size / 2.0;
ccenter[1] = pcenter[1] + size / 2.0;
ccenter[2] = pcenter[2] + size / 2.0;
break;
case 7:
ccenter[0] = pcenter[0] + size / 2.0;
ccenter[1] = pcenter[1] + size / 2.0;
ccenter[2] = pcenter[2] + size / 2.0;
break;
default:
break;
}
}
void compactTree::GetOctTreeCenter(vector<double*>&c) { GetOctTreeCenter(c, *root, center, size); }
void compactTree::AllPoints(vector<double *> &vp) { AllPoints(*compactTree::root, vp, center, size); }
long compactTree::countNodes() { return 1 + countNodes(*root); }
long compactTree::countLeaves() { return 1 + countLeaves(*root); }
void compactTree::setColorManager(ColorManager *_cm) { cm = _cm; }
void compactTree::drawLOD(float ratio) {
switch (current_lod_mode) {
case 1:
glBegin(GL_POINTS);
displayOctTreeCulledLOD2(ratio , *root, center, size);
glEnd();
break;
case 2:
/*
#ifdef WITH_GLEE
if (GLEE_ARB_point_parameters) {
glPointParameterfARB(GL_POINT_SIZE_MIN_ARB, 1.0);
glPointParameterfARB(GL_POINT_SIZE_MAX_ARB, 100000.0);
GLfloat p[3] = {0.0, 0.0000, 0.0000005};
glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB, p);
displayOctTreeCPAllCulled(*BOctTree<T>::root, BOctTree<T>::center, BOctTree<T>::size, BOctTree<T>::size/ pow(2, min( (int)(ratio * BOctTree<T>::max_depth ), BOctTree<T>::max_depth - 3) ) );
p[0] = 1.0;
p[2] = 0.0;
glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB, p);
}
#endif
*/
//break;
case 0:
glBegin(GL_POINTS);
displayOctTreeCulledLOD(maxtargetpoints * ratio, *root, center, size);
glEnd();
break;
default:
break;
}
}
void compactTree::draw() {
displayOctTreeAllCulled(*root, center, size);
}
void compactTree::displayOctTree(double minsize ) {
displayOctTreeCAllCulled(*root, center, size, minsize);
}
shortpointrep* compactTree::createPoints(lint length) {
//shortpointrep *points = new shortpointrep[POINTDIM*length];
shortpointrep *points = alloc->allocate<shortpointrep> (POINTDIM*length);
return points;
}
void compactTree::deserialize(std::string filename)
{
char buffer[sizeof(float) * 20];
float *p = reinterpret_cast<float*>(buffer);
std::ifstream file;
file.open (filename.c_str(), std::ios::in | std::ios::binary);
// read magic bits
file.read(buffer, 2);
if ( buffer[0] != 'X' || buffer[1] != 'T') {
std::cerr << "Not an octree file!!" << endl;
file.close();
return;
}
// read header
pointtype = PointType::deserialize(file);
file.read(buffer, 5 * sizeof(float));
voxelSize = p[0];
center[0] = p[1];
center[1] = p[2];
center[2] = p[3];
size = p[4];
file.read(buffer, sizeof(int));
int *ip = reinterpret_cast<int*>(buffer);
POINTDIM = *ip;
float *fmins = new float[POINTDIM];
float *fmaxs = new float[POINTDIM];
mins = new double[POINTDIM];
maxs = new double[POINTDIM];
file.read(reinterpret_cast<char*>(fmins), POINTDIM * sizeof(float));
file.read(reinterpret_cast<char*>(fmaxs), POINTDIM * sizeof(float));
for (unsigned int i = 0; i < POINTDIM; i++) {
mins[i] = fmins[i];
maxs[i] = fmaxs[i];
}
double vs = size;
while (vs > voxelSize) {
vs = vs * 0.5;
}
// precision = vs / 32768; // 2^15
precision = vs / TSHORT_MAXP1; // 2^15
// read root node
//root = new cbitoct();
root = alloc->allocate<cbitoct>();
deserialize(file, *root );
file.close();
}
void compactTree::deserialize(std::ifstream &f, cbitoct &node) {
char buffer[2];
f.read(buffer, 2);
node.valid = buffer[0];
node.leaf = buffer[1];
unsigned short n_children = POPCOUNT(node.valid);
// create children
//cbitunion<tshort> *children = new cbitunion<tshort>[n_children];
cbitunion<tshort> *children = alloc->allocate<cbitunion<tshort> >(n_children);
cbitoct::link(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf read points
lint length;
f.read(reinterpret_cast<char*>(&length), sizeof(lint));
shortpointrep *points = createPoints(length);
f.read(reinterpret_cast<char*>(points), sizeof(shortpointrep) * length * POINTDIM); // read the points
children->linkPoints(points, length);
} else { // write child
deserialize(f, children->node);
}
++children; // next child
}
}
}
void compactTree::serialize(std::string filename) {
char buffer[sizeof(float) * 20];
float *p = reinterpret_cast<float*>(buffer);
std::ofstream file;
file.open (filename.c_str(), std::ios::out | std::ios::binary);
// write magic bits
buffer[0] = 'X';
buffer[1] = 'T';
file.write(buffer, 2);
// write header
pointtype.serialize(file);
p[0] = voxelSize;
p[1] = center[0];
p[2] = center[1];
p[3] = center[2];
p[4] = size;
int *ip = reinterpret_cast<int*>(&(buffer[5 * sizeof(float)]));
*ip = POINTDIM;
file.write(buffer, 5 * sizeof(float) + sizeof(int));
for (unsigned int i = 0; i < POINTDIM; i++) {
p[i] = mins[i];
}
for (unsigned int i = 0; i < POINTDIM; i++) {
p[i+POINTDIM] = maxs[i];
}
file.write(buffer, 2*POINTDIM * sizeof(float));
// write root node
serialize(file, *root);
file.close();
}
void compactTree::serialize(std::ofstream &of, cbitoct &node) {
char buffer[2];
buffer[0] = node.valid;
buffer[1] = node.leaf;
of.write(buffer, 2);
// write children
cbitunion<tshort> *children;
cbitoct::getChildren(node, children);
for (short i = 0; i < 8; i++) {
if ( ( 1 << i ) & node.valid ) { // if ith node exists
if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf write points
tshort *points = children->getPoints();
lint length = children->getLength();
of.write(reinterpret_cast<char*>(&length), sizeof(lint) );
of.write(reinterpret_cast<char*>(points), POINTDIM*length*sizeof(tshort) );
} else { // write child
serialize(of, children->node);
}
++children; // next child
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
IF(WITH_SEGMENTATION)
IF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
add_executable(scan2segments scan2segments.cc ../slam6d/fbr/fbr_global.cc)
target_link_libraries(scan2segments scan ANN fbr_cv_io fbr_panorama fbr_feature fbr_feature_matcher fbr_registration ${Boost_LIBRARIES} ${OpenCV_LIBS})
ELSE(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
MESSAGE("OpenCV Version > 2.2 required for scan2segmentation")
ENDIF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
add_executable(fhsegmentation fhsegmentation.cc FHGraph.cc disjoint-set.cc segment-graph.cc)
target_link_libraries(fhsegmentation scan ANN ${Boost_LIBRARIES} ${OpenCV_LIBS})
ENDIF(WITH_SEGMENTATION)

View file

@ -0,0 +1,129 @@
/*
* kd implementation
*
* Copyright (C) Andreas Nuechter, Kai Lingemann, Thomas Escher
*
* Released under the GPL version 3.
*
*/
/** @file
* @brief An optimized k-d tree implementation
* @author Remus Dumitru. Jacobs University Bremen, Germany
* @author Corneliu-Claudiu Prodescu. Jacobs University Bremen, Germany
* @author Andreas Nuechter. Jacobs University Bremen, Germany.
* @author Kai Lingemann. Inst. of CS, University of Osnabrueck, Germany.
* @author Thomas Escher Inst. of CS, University of Osnabrueck, Germany.
*/
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif
#include "slam6d/kd.h"
#include "slam6d/globals.icc"
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <algorithm>
using std::swap;
#include <cmath>
#include <cstring>
#include <limits>
#include <vector>
// KDtree class static variables
template<class PointData, class AccessorData, class AccessorFunc>
KDParams KDTreeImpl<PointData, AccessorData, AccessorFunc>::params[MAX_OPENMP_NUM_THREADS];
/**
* Constructor
*
* Create a KD tree from the points pointed to by the array pts
*
* @param pts 3D array of points
* @param n number of points
*/
KDtree::KDtree(double **pts, int n)
{
create(Void(), pts, n);
}
KDtree::~KDtree()
{
}
/**
* Finds the closest point within the tree,
* wrt. the point given as first parameter.
* @param _p point
* @param maxdist2 maximal search distance.
* @param threadNum Thread number, for parallelization
* @return Pointer to the closest point
*/
double *KDtree::FindClosest(double *_p,
double maxdist2,
int threadNum) const
{
params[threadNum].closest = 0;
params[threadNum].closest_d2 = maxdist2;
params[threadNum].p = _p;
_FindClosest(Void(), threadNum);
return params[threadNum].closest;
}
double *KDtree::FindClosestAlongDir(double *_p,
double *_dir,
double maxdist2,
int threadNum) const
{
params[threadNum].closest = NULL;
params[threadNum].closest_d2 = maxdist2;
params[threadNum].p = _p;
params[threadNum].dir = _dir;
_FindClosestAlongDir(Void(), threadNum);
return params[threadNum].closest;
}
vector<Point> KDtree::kNearestNeighbors(double *_p,
int k,
double sqRad2,
int threadNum) const
{
vector<Point> result;
params[threadNum].closest = 0;
params[threadNum].closest_d2 = sqRad2;
params[threadNum].p = _p;
params[threadNum].heap.clear();
_KNNSearch(Void(), threadNum);
while (k > 0 && params[threadNum].heap.empty() == false) {
Point pt = params[threadNum].heap.front().first;
result.push_back(pt);
std::pop_heap(params[threadNum].heap.begin(), params[threadNum].heap.end(), PointCompare());
params[threadNum].heap.pop_back();
k--;
}
return result;
}
vector<Point> KDtree::fixedRangeSearch(double *_p,
double sqRad2,
int threadNum) const
{
vector<Point> result;
params[threadNum].closest = 0;
params[threadNum].closest_d2 = sqRad2;
params[threadNum].p = _p;
params[threadNum].heap.clear();
_FixedRangeSearch(Void(), threadNum);
for (vector<std::pair<Point, double> >::iterator it = params[threadNum].heap.begin(); it != params[threadNum].heap.end(); ++it) {
result.push_back(it->first);
}
return result;
}

View file

@ -0,0 +1,35 @@
1.
--metascan segfaults when destroying the allscanlist.
2.
scanserver segfaults whith reflectances sometimes.
E.g.,
bin/scanserver -c 3500
and
bin/show -s 0 -e 1 -f riegl_txt --reflectance ~/dat/bremen_city --scanserver
or
bin/scanserver
and
bin/slam6D -s 0 -e 1 -f uosr dat --scanserver
3.
scan_red with panorama range image and cylindrical coordinates does
not work correctly.
4.
fast_normals does not work on SRI yet. Commented out.
5.
reflectance_reduced not in managedScan/scanserver
6.
normals not integrated managedScan/scanserver
7.
kdMeta/kdManaged does not support kNN nor range search yet
8.
Make our own knn efficient, then get rid of ANN ;-)

View file

@ -0,0 +1,7 @@
add_library(normals normals.cc)
target_link_libraries(normals newmat scan ANN fbr_cv_io fbr_panorama ${OpenCV_LIBS})
IF(WITH_TOOLS)
add_executable(calc_normals calc_normals.cc)
target_link_libraries(calc_normals normals ${Boost_LIBRARIES})
ENDIF(WITH_TOOLS)

View file

@ -0,0 +1,37 @@
SET(FBR_IO_SRC scan_cv.cc)
add_library(fbr_cv_io STATIC ${FBR_IO_SRC})
SET(FBR_PANORAMA_SRC panorama.cc)
add_library(fbr_panorama STATIC ${FBR_PANORAMA_SRC} fbr_global.cc)
IF(WITH_FBR)
IF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
SET(FBR_FEATURE_SRC feature.cc)
add_library(fbr_feature STATIC ${FBR_FEATURE_SRC})
SET(FBR_FEATURE_MATCHER_SRC feature_matcher.cc)
add_library(fbr_feature_matcher STATIC ${FBR_FEATURE_MATCHER_SRC})
SET(FBR_REGISTRATION_SRC registration.cc)
add_library(fbr_registration STATIC ${FBR_REGISTRATION_SRC})
SET(FBR_SRC scan_cv.cc panorama.cc feature.cc feature_matcher.cc registration.cc fbr_global.cc)
add_library(fbr STATIC ${FBR_SRC})
SET(FBR_LIBS scan ANN ${OpenCV_LIBS})
add_executable(featurebasedregistration feature_based_registration.cc fbr_global.cc)
#target_link_libraries(featurebasedregistration fbr_cv_io fbr_panorama fbr_feature fbr_feature_matcher fbr_registration ${FBR_LIBS})
target_link_libraries(featurebasedregistration fbr ${FBR_LIBS})
### EXPORT SHARED LIBS
IF(EXPORT_SHARED_LIBS)
add_library(fbr_s SHARED ${FBR_SRC})
target_link_libraries(fbr_s scan_s ANN_s ${OpenCV_LIBS})
ENDIF(EXPORT_SHARED_LIBS)
ELSE(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
MESSAGE("OpenCV Version > 2.2 required for FBR")
ENDIF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
ENDIF(WITH_FBR)

View file

@ -0,0 +1,155 @@
#ifndef NORMALS_H
#define NORMALS_H
#include <vector>
#include <slam6d/scan.h>
#if (CV_MAJOR_VERSION == 2) && (CV_MINOR_VERSION < 2)
#include <opencv/cv.h>
#include <opencv/highgui.h>
#else
#include <opencv2/opencv.hpp>
#endif
void calculateNormalsApxKNN(std::vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3],
double eps = 0.0);
void calculateNormalsAdaptiveApxKNN(std::vector<Point> &normals,
vector<Point> &points,
int kmin,
int kmax,
const double _rPos[3],
double eps = 0.0);
void calculateNormalsKNN(std::vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3] );
void calculateNormalsAdaptiveKNN(vector<Point> &normals,
vector<Point> &points,
int kmin, int kmax,
const double _rPos[3]);
void calculateNormalsPANORAMA(vector<Point> &normals,
vector<Point> &points,
vector< vector< vector< cv::Vec3f > > > extendedMap,
const double _rPos[3]);
// TODO should be exported to separate library
/*
* retrieve a cv::Mat with x,y,z,r from a scan object
* functionality borrowed from scan_cv::convertScanToMat but this function
* does not allow a scanserver to be used, prints to stdout and can only
* handle a single scan
*/
static inline cv::Mat scan2mat(Scan *source)
{
DataXYZ xyz = source->get("xyz");
DataReflectance xyz_reflectance = source->get("reflectance");
unsigned int nPoints = xyz.size();
cv::Mat scan(nPoints,1,CV_32FC(4));
scan = cv::Scalar::all(0);
cv::MatIterator_<cv::Vec4f> it;
it = scan.begin<cv::Vec4f>();
for(unsigned int i = 0; i < nPoints; i++){
float x, y, z, reflectance;
x = xyz[i][0];
y = xyz[i][1];
z = xyz[i][2];
if(xyz_reflectance.size() != 0)
{
reflectance = xyz_reflectance[i];
//normalize the reflectance
reflectance += 32;
reflectance /= 64;
reflectance -= 0.2;
reflectance /= 0.3;
if (reflectance < 0) reflectance = 0;
if (reflectance > 1) reflectance = 1;
}
(*it)[0] = x;
(*it)[1] = y;
(*it)[2] = z;
if(xyz_reflectance.size() != 0)
(*it)[3] = reflectance;
else
(*it)[3] = 0;
++it;
}
return scan;
}
// TODO should be exported to separate library
/*
* convert a matrix of float values (range image) to a matrix of unsigned
* eight bit characters using different techniques
*/
static inline cv::Mat float2uchar(cv::Mat &source, bool logarithm, float cutoff)
{
cv::Mat result(source.size(), CV_8U, cv::Scalar::all(0));
float max = 0;
// find maximum value
if (cutoff == 0.0) {
// without cutoff, just iterate through all values to find the largest
for (cv::MatIterator_<float> it = source.begin<float>();
it != source.end<float>(); ++it) {
float val = *it;
if (val > max) {
max = val;
}
}
} else {
// when a cutoff is specified, sort all the points by value and then
// specify the max so that <cutoff> values are larger than it
vector<float> sorted(source.cols*source.rows);
int i = 0;
for (cv::MatIterator_<float> it = source.begin<float>();
it != source.end<float>(); ++it, ++i) {
sorted[i] = *it;
}
std::sort(sorted.begin(), sorted.end());
max = sorted[(int)(source.cols*source.rows*(1.0-cutoff))];
cout << "A cutoff of " << cutoff << " resulted in a max value of " << max << endl;
}
cv::MatIterator_<float> src = source.begin<float>();
cv::MatIterator_<uchar> dst = result.begin<uchar>();
cv::MatIterator_<float> end = source.end<float>();
if (logarithm) {
// stretch values from 0 to max logarithmically over 0 to 255
// using the logarithm allows to represent smaller values with more
// precision and larger values with less
max = log(max+1);
for (; src != end; ++src, ++dst) {
float val = (log(*src+1)*255.0)/max;
if (val > 255)
*dst = 255;
else
*dst = (uchar)val;
}
} else {
// stretch values from 0 to max linearly over 0 to 255
for (; src != end; ++src, ++dst) {
float val = (*src*255.0)/max;
if (val > 255)
*dst = 255;
else
*dst = (uchar)val;
}
}
return result;
}
#endif // NORMALS_H

View file

@ -0,0 +1,194 @@
/*
* scan_io_xyzr implementation
*
* Copyright (C) Andreas Nuechter
*
* Released under the GPL version 3.
*
*/
/**
* @file scan_io_xyzr.cc
* @brief IO of a 3D scan in xyz file format plus a reflectance/intensity
* @author Andreas Nuechter. Jacobs University Bremen, Germany.
*/
#include "scanio/scan_io_xyzr.h"
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <vector>
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
#include "slam6d/globals.icc"
#define DATA_PATH_PREFIX "scan"
#define DATA_PATH_SUFFIX ".3d"
#define POSE_PATH_PREFIX "scan"
#define POSE_PATH_SUFFIX ".pose"
std::list<std::string> ScanIO_xyzr::readDirectory(const char* dir_path,
unsigned int start,
unsigned int end)
{
std::list<std::string> identifiers;
for(unsigned int i = start; i <= end; ++i) {
// identifier is /d/d/d (000-999)
std::string identifier(to_string(i,3));
// scan consists of data (.3d) and pose (.pose) files
path data(dir_path);
data /= path(std::string(DATA_PATH_PREFIX) + identifier + DATA_PATH_SUFFIX);
path pose(dir_path);
pose /= path(std::string(POSE_PATH_PREFIX) + identifier + POSE_PATH_SUFFIX);
// stop if part of a scan is missing or end by absence is detected
if(!exists(data) || !exists(pose))
break;
identifiers.push_back(identifier);
}
return identifiers;
}
void ScanIO_xyzr::readPose(const char* dir_path,
const char* identifier,
double* pose)
{
unsigned int i;
path pose_path(dir_path);
pose_path /= path(std::string(POSE_PATH_PREFIX)
+ identifier +
POSE_PATH_SUFFIX);
if(!exists(pose_path))
throw std::runtime_error(std::string("There is no pose file for [")
+ identifier + "] in [" + dir_path + "]");
// open pose file
ifstream pose_file(pose_path);
// if the file is open, read contents
if(pose_file.good()) {
// read 6 plain doubles
for(i = 0; i < 6; ++i) pose_file >> pose[i];
pose_file.close();
// convert angles from deg to rad
for(i = 3; i < 6; ++i) pose[i] = rad(pose[i]);
} else {
throw std::runtime_error(std::string("Pose file could not be opened for [")
+ identifier + "] in ["
+ dir_path + "]");
}
}
bool ScanIO_xyzr::supports(IODataType type)
{
return !!(type & ( DATA_REFLECTANCE | DATA_XYZ ));
}
void ScanIO_xyzr::readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation)
{
unsigned int i;
// error handling
path data_path(dir_path);
data_path /= path(std::string(DATA_PATH_PREFIX)
+ identifier
+ DATA_PATH_SUFFIX);
if(!exists(data_path))
throw std::runtime_error(std::string("There is no scan file for [")
+ identifier + "] in ["
+ dir_path + "]");
if(xyz != 0) {
// open data file
ifstream data_file(data_path);
data_file.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
// overread the first line ignoring the header information
char dummy[255];
data_file.getline(dummy, 255);
// read points and reflectance/intensity/temperature value
double point[3];
float reflection;
while(data_file.good()) {
try {
for(i = 0; i < 3; ++i) data_file >> point[i];
/*
point[0] -= 485531.0;
point[1] -= 5882078.400;
point[2] -= 52;
*/
std::swap(point[2], point[1]);
data_file >> reflection;
} catch(std::ios_base::failure& e) {
break;
}
// apply filter then insert point and reflectance
if(filter.check(point)) {
for(i = 0; i < 3; ++i) xyz->push_back(point[i]);
reflectance->push_back(reflection);
}
}
data_file.close();
}
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) ScanIO* create()
#else
extern "C" ScanIO* create()
#endif
{
return new ScanIO_xyzr;
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) void destroy(ScanIO *sio)
#else
extern "C" void destroy(ScanIO *sio)
#endif
{
delete sio;
}
#ifdef _MSC_VER
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
return TRUE;
}
#endif

View file

@ -0,0 +1,48 @@
if(WIN32)
add_library(pointfilter STATIC ../slam6d/pointfilter.cc)
else(WIN32)
add_library(pointfilter SHARED ../slam6d/pointfilter.cc)
endif(WIN32)
set(SCANIO_LIBNAMES
uos uosr uos_rgb uos_rrgbt xyzr ply ks ks_rgb riegl_txt riegl_rgb rts velodyne
)
if(WITH_RIVLIB)
set(SCANIO_LIBNAMES ${SCANIO_LIBNAMES} rxp)
if(LIBXML2_FOUND)
include_directories(${LIBXML2_INCLUDE_DIR})
# set(SCANIO_LIBNAMES ${SCANIO_LIBNAMES} riegl_project)
# target_link_libraries(scan_io_riegl_project ${RIVLIB} scan_io_rxp ${LIBXML2_LIBRARIES})
endif(LIBXML2_FOUND)
endif(WITH_RIVLIB)
foreach(libname ${SCANIO_LIBNAMES})
if(WIN32)
#add_library(scan_io_${libname} STATIC scan_io_${libname}.cc)
add_library(scan_io_${libname} SHARED scan_io_${libname}.cc)
else(WIN32)
add_library(scan_io_${libname} SHARED scan_io_${libname}.cc)
endif(WIN32)
target_link_libraries(scan_io_${libname} pointfilter ${Boost_LIBRARIES} ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_FILESYSTEM_LIBRARY} ${Boost_SYSTEM_LIBRARY})
endforeach(libname)
if(WITH_RIVLIB)
target_link_libraries(scan_io_rxp ${RIVLIB})
if(LIBXML2_FOUND)
target_link_libraries(scan_io_rxp ${LIBXML2_LIBRARIES}) #scan_io_riegl_project ${RIVLIB})
endif(LIBXML2_FOUND)
endif(WITH_RIVLIB)
if(WIN32)
add_library(scanio STATIC scan_io.cc ../slam6d/io_types.cc)
else(WIN32)
add_library(scanio SHARED scan_io.cc ../slam6d/io_types.cc)
endif(WIN32)
if(UNIX)
target_link_libraries(scanio dl)
endif(UNIX)

View file

@ -0,0 +1,227 @@
/*
* scan_io_ply implementation
*
* Copyright (C) Dorit Borrmann, Thomas Escher, Kai Lingemann, Andreas Nuechter
*
* Released under the GPL version 3.
*
*/
/**
* @file
* @brief Implementation of reading 3D scans
* @author Dorit Borrmann. Jacobs University Bremen, Germany.
* @author Kai Lingemann. Inst. of CS, University of Osnabrueck, Germany.
* @author Andreas Nuechter. Jacobs University Bremen, Germany.
* @author Thomas Escher. Inst. of CS, University of Osnabrueck, Germany.
*/
#include "scanio/scan_io_ply.h"
#include "slam6d/point.h"
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <vector>
#include <string.h>
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
#include "slam6d/globals.icc"
#define DATA_PATH_PREFIX "scan"
#define DATA_PATH_SUFFIX ".ply"
std::list<std::string> ScanIO_ply::readDirectory(const char* dir_path,
unsigned int start,
unsigned int end)
{
std::list<std::string> identifiers;
for (unsigned int i = start; i <= end; ++i) {
// identifier is /d/d/d (000-999)
std::string identifier(to_string(i,3));
// scan consists of data (.3d) and pose (.pose) files
path data(dir_path);
data /= path(std::string(DATA_PATH_PREFIX) + identifier + DATA_PATH_SUFFIX);
// stop if part of a scan is missing or end by absence is detected
if (!exists(data))
break;
identifiers.push_back(identifier);
}
return identifiers;
}
void ScanIO_ply::readPose(const char* dir_path,
const char* identifier,
double* pose)
{
for (unsigned int i = 0; i < 6; ++i) pose[i] = 0.0;
}
bool ScanIO_ply::supports(IODataType type)
{
return !!(type & (DATA_XYZ | DATA_REFLECTANCE | DATA_RGB));
}
void ScanIO_ply::readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation)
{
unsigned int i;
// error handling
path data_path(dir_path);
data_path /= path(std::string(DATA_PATH_PREFIX) +
identifier + DATA_PATH_SUFFIX);
if(!exists(data_path))
throw std::runtime_error(std::string("There is no scan file for [")
+ identifier + "] in [" + dir_path + "]");
// open data file
ifstream data_file;
data_file.open(data_path);
data_file.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
if(xyz != 0 && rgb != 0 && reflectance != 0) {
// read ply file
bool binary = false;
char dummy[256];
char str[20]; // whatever size
double matrix[16];
int matrixPos = 0;
int nr;
float d1,d2,d3,d4;
// header
int counter = -2;
do {
if (counter > -2) counter++;
if (data_file.good()) {
data_file.getline(dummy, 255);
}
if (strncmp(dummy, "format", 6) == 0) {
if (dummy[7] == 'a') binary = false;
else if (dummy[7] == 'b') binary = true;
else { cerr << "Don't recognize the format!" << endl; exit(1); }
}
else if (strncmp(dummy, "element vertex", 14) == 0) {
sscanf(dummy,"%s %*s %d",str,&nr);
counter++;
}
else if (strncmp(dummy, "matrix", 6) == 0) {
sscanf(dummy,"%s %f %f %f %f", str, &d1, &d2, &d3, &d4);
matrix[matrixPos++] = d1;
matrix[matrixPos++] = d2;
matrix[matrixPos++] = d3;
matrix[matrixPos++] = d4;
}
} while (!(strncmp(dummy, "end_header",10) == 0 || !data_file.good()));
if (matrixPos > 0) {
double rPosTheta[3];
double rPos[3];
Matrix4ToEuler(matrix, rPosTheta, rPos);
}
for (int i=0; i < nr; i++) {
Point p;
float data, confidence, intensity;
float dummy;
int r, g, b;
if (!binary) {
switch(counter) {
case 6:
case 12:
data_file >> p.z >> p.y >> p.x >> r >> g >> b;
break;
case 9:
data_file >> p.z >> p.y >> p.x
>> dummy >> dummy >> dummy
>> r >> g >> b;
break;
default:
data_file >> p.z >> p.x >> p.y >> confidence >> intensity;
break;
}
if(counter == 6 || counter == 9 || counter == 12) {
p.rgb[0] = (char)r;
p.rgb[1] = (char)g;
p.rgb[2] = (char)b;
} else {
p.reflectance = intensity;
}
} else {
data_file.read((char*)&data, sizeof(float));
p.z = (double)data;
data_file.read((char*)&data, sizeof(float));
p.x = (double)data;
data_file.read((char*)&data, sizeof(float));
p.y = (double)data;
data_file.read((char*)&confidence, sizeof(float));
data_file.read((char*)&intensity, sizeof(float));
}
reflectance->push_back(p.reflectance);
xyz->push_back(p.x * 100);
xyz->push_back(p.y * 100);
xyz->push_back(p.z * 100);
rgb->push_back(static_cast<unsigned char>(p.rgb[0]));
rgb->push_back(static_cast<unsigned char>(p.rgb[1]));
rgb->push_back(static_cast<unsigned char>(p.rgb[2]));
}
}
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) ScanIO* create()
#else
extern "C" ScanIO* create()
#endif
{
return new ScanIO_ply;
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) void destroy(ScanIO *sio)
#else
extern "C" void destroy(ScanIO *sio)
#endif
{
delete sio;
}
#ifdef _MSC_VER
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
return TRUE;
}
#endif

View file

@ -0,0 +1,26 @@
IF (WITH_THERMO)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob)
include_directories(${CMAKE_SOURCE_DIR}/include/shapes/)
include_directories(${CMAKE_SOURCE_DIR}/include/thermo/)
include_directories(/usr/include/)
include_directories(/usr/include/opencv)
add_executable(caliboard caliboard.cc)
add_executable(thermo thermo.cc)
# add_executable(thermo thermo.cc src/cvaux.cpp src/cvblob.cpp src/cvcolor.cpp src/cvcontour.cpp src/cvlabel.cpp src/cvtrack.cpp)
IF(UNIX)
target_link_libraries(caliboard scan shape newmat dl ANN)
target_link_libraries(thermo scan shape newmat dl ANN)
target_link_libraries(thermo GL GLU cvblob ${OpenCV_LIBS} scan ANN)
ENDIF(UNIX)
IF (WIN32)
target_link_libraries(caliboard scan shape newmat XGetopt ANN)
target_link_libraries(thermo scan shape newmat XGetopt ANN)
target_link_libraries(thermo GL GLU cvblob ${OpenCV_LIBS} scan ANN)
ENDIF(WIN32)
ENDIF(WITH_THERMO)

View file

@ -0,0 +1,275 @@
/**
*
* Copyright (C) Jacobs University Bremen
*
* @author Vaibhav Kumar Mehta
* @file calc_normals.cc
*/
#include <iostream>
#include <string>
#include <fstream>
#include <errno.h>
#include <boost/program_options.hpp>
#include <slam6d/io_types.h>
#include <slam6d/globals.icc>
#include <slam6d/scan.h>
#include "slam6d/fbr/panorama.h"
#include <scanserver/clientInterface.h>
#include <normals/normals.h>
#ifdef _MSC_VER
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#else
#include <strings.h>
#endif
namespace po = boost::program_options;
using namespace std;
enum normal_method {AKNN, ADAPTIVE_AKNN, PANORAMA, PANORAMA_FAST};
/*
* validates normal calculation method specification
*/
void validate(boost::any& v, const std::vector<std::string>& values,
normal_method*, int) {
if (values.size() == 0)
throw std::runtime_error("Invalid model specification");
string arg = values.at(0);
if(strcasecmp(arg.c_str(), "AKNN") == 0) v = AKNN;
else if(strcasecmp(arg.c_str(), "ADAPTIVE_AKNN") == 0) v = ADAPTIVE_AKNN;
else if(strcasecmp(arg.c_str(), "PANORAMA") == 0) v = PANORAMA;
else if(strcasecmp(arg.c_str(), "PANORAMA_FAST") == 0) v = PANORAMA_FAST;
else throw std::runtime_error(std::string("normal calculation method ") + arg + std::string(" is unknown"));
}
/// validate IO types
void validate(boost::any& v, const std::vector<std::string>& values,
IOType*, int) {
if (values.size() == 0)
throw std::runtime_error("Invalid model specification");
string arg = values.at(0);
try {
v = formatname_to_io_type(arg.c_str());
} catch (...) { // runtime_error
throw std::runtime_error("Format " + arg + " unknown.");
}
}
/// Parse commandline options
void parse_options(int argc, char **argv, int &start, int &end, bool &scanserver, int &max_dist, int &min_dist, string &dir,
IOType &iotype, int &k1, int &k2, normal_method &ntype,int &width,int &height)
{
/// ----------------------------------
/// set up program commandline options
/// ----------------------------------
po::options_description cmd_options("Usage: calculateNormals <options> where options are (default values in brackets)");
cmd_options.add_options()
("help,?", "Display this help message")
("start,s", po::value<int>(&start)->default_value(0), "Start at scan number <arg>")
("end,e", po::value<int>(&end)->default_value(-1), "Stop at scan number <arg>")
("scanserver,S", po::value<bool>(&scanserver)->default_value(false), "Use the scanserver as an input method")
("format,f", po::value<IOType>(&iotype)->default_value(UOS),
"using shared library <arg> for input. (chose format from [uos|uosr|uos_map|"
"uos_rgb|uos_frames|uos_map_frames|old|rts|rts_map|ifp|"
"riegl_txt|riegl_rgb|riegl_bin|zahn|ply])")
("max,M", po::value<int>(&max_dist)->default_value(-1),"neglegt all data points with a distance larger than <arg> 'units")
("min,m", po::value<int>(&min_dist)->default_value(-1),"neglegt all data points with a distance smaller than <arg> 'units")
("normal,g", po::value<normal_method>(&ntype)->default_value(AKNN), "normal calculation method "
"(AKNN, ADAPTIVE_AKNN, PANORAMA, PANORAMA_FAST)")
("K1,k", po::value<int>(&k1)->default_value(20), "<arg> value of K value used in the nearest neighbor search of ANN or" "kmin for k-adaptation")
("K2,K", po::value<int>(&k2)->default_value(20), "<arg> value of Kmax for k-adaptation")
("width,w", po::value<int>(&width)->default_value(1280),"width of panorama image")
("height,h", po::value<int>(&height)->default_value(960),"height of panorama image")
;
po::options_description hidden("Hidden options");
hidden.add_options()
("input-dir", po::value<string>(&dir), "input dir");
po::positional_options_description pd;
pd.add("input-dir", 1);
po::options_description all;
all.add(cmd_options).add(hidden);
po::variables_map vmap;
po::store(po::command_line_parser(argc, argv).options(all).positional(pd).run(), vmap);
po::notify(vmap);
if (vmap.count("help")) {
cout << cmd_options << endl << endl;
cout << "SAMPLE COMMAND FOR CALCULATING NORMALS" << endl;
cout << " bin/normals -s 0 -e 0 -f UOS -g AKNN -k 20 dat/" <<endl;
cout << endl << endl;
cout << "SAMPLE COMMAND FOR VIEWING CALCULATING NORMALS IN RGB SPACE" << endl;
cout << " bin/show -c -f UOS_RGB dat/normals/" << endl;
exit(-1);
}
// read scan path
if (dir[dir.length()-1] != '/') dir = dir + "/";
}
/// Write a pose file with the specofied name
void writePoseFiles(string dir, const double* rPos, const double* rPosTheta,int scanNumber)
{
string poseFileName = dir + "/scan" + to_string(scanNumber, 3) + ".pose";
ofstream posout(poseFileName.c_str());
posout << rPos[0] << " "
<< rPos[1] << " "
<< rPos[2] << endl
<< deg(rPosTheta[0]) << " "
<< deg(rPosTheta[1]) << " "
<< deg(rPosTheta[2]) << endl;
posout.clear();
posout.close();
}
/// write scan files for all segments
void writeScanFiles(string dir, vector<Point> &points, vector<Point> &normals, int scanNumber)
{
string ofilename = dir + "/scan" + to_string(scanNumber, 3) + ".3d";
ofstream normptsout(ofilename.c_str());
for (size_t i=0; i<points.size(); ++i)
{
int r,g,b;
r = (int)(normals[i].x * (127.5) + 127.5);
g = (int)(normals[i].y * (127.5) + 127.5);
b = (int)(fabs(normals[i].z) * (255.0));
normptsout <<points[i].x<<" "<<points[i].y<<" "<<points[i].z<<" "<<r<<" "<<g<<" "<<b<<" "<<endl;
}
normptsout.clear();
normptsout.close();
}
/// =============================================
/// Main
/// =============================================
int main(int argc, char** argv)
{
int start, end;
bool scanserver;
int max_dist, min_dist;
string dir;
IOType iotype;
int k1, k2;
normal_method ntype;
int width, height;
parse_options(argc, argv, start, end, scanserver, max_dist, min_dist,
dir, iotype, k1, k2, ntype, width, height);
/// ----------------------------------
/// Prepare and read scans
/// ----------------------------------
if (scanserver) {
try {
ClientInterface::create();
} catch(std::runtime_error& e) {
cerr << "ClientInterface could not be created: " << e.what() << endl;
cerr << "Start the scanserver first." << endl;
exit(-1);
}
}
/// Make directory for saving the scan segments
string normdir = dir + "normals";
#ifdef _MSC_VER
int success = mkdir(normdir.c_str());
#else
int success = mkdir(normdir.c_str(), S_IRWXU|S_IRWXG|S_IRWXO);
#endif
if(success == 0) {
cout << "Writing segments to " << normdir << endl;
} else if(errno == EEXIST) {
cout << "WARN: Directory " << normdir << " exists already. Contents will be overwriten" << endl;
} else {
cerr << "Creating directory " << normdir << " failed" << endl;
exit(1);
}
/// Read the scans
Scan::openDirectory(scanserver, dir, iotype, start, end);
if(Scan::allScans.size() == 0) {
cerr << "No scans found. Did you use the correct format?" << endl;
exit(-1);
}
cv::Mat img;
/// --------------------------------------------
/// Initialize and perform segmentation
/// --------------------------------------------
std::vector<Scan*>::iterator it = Scan::allScans.begin();
int scanNumber = 0;
for( ; it != Scan::allScans.end(); ++it) {
Scan* scan = *it;
// apply optional filtering
scan->setRangeFilter(max_dist, min_dist);
const double* rPos = scan->get_rPos();
const double* rPosTheta = scan->get_rPosTheta();
/// read scan into points
DataXYZ xyz(scan->get("xyz"));
vector<Point> points;
points.reserve(xyz.size());
vector<Point> normals;
normals.reserve(xyz.size());
for(unsigned int j = 0; j < xyz.size(); j++) {
points.push_back(Point(xyz[j][0], xyz[j][1], xyz[j][2]));
}
if(ntype == AKNN)
calculateNormalsApxKNN(normals,points, k1, rPos);
else if(ntype == ADAPTIVE_AKNN)
calculateNormalsAdaptiveApxKNN(normals,points, k1, k2, rPos);
else
{
// create panorama
fbr::panorama fPanorama(width, height, fbr::EQUIRECTANGULAR, 1, 0, fbr::EXTENDED);
fPanorama.createPanorama(scan2mat(scan));
// the range image has to be converted from float to uchar
img = fPanorama.getRangeImage();
img = float2uchar(img, 0, 0.0);
if(ntype == PANORAMA)
calculateNormalsPANORAMA(normals,points,fPanorama.getExtendedMap(), rPos);
else if(ntype == PANORAMA_FAST)
cout << "PANORAMA_FAST is not working yet" << endl;
// calculateNormalsFAST(normals,points,img,fPanorama.getExtendedMap());
}
// pose file (repeated for the number of segments
writePoseFiles(normdir, rPos, rPosTheta, scanNumber);
// scan files for all segments
writeScanFiles(normdir, points,normals,scanNumber);
scanNumber++;
}
// shutdown everything
if (scanserver)
ClientInterface::destroy();
Scan::closeDirectory();
cout << "Normal program end" << endl;
return 0;
}

View file

@ -0,0 +1,996 @@
/*
* slam6D implementation
*
* Copyright (C) Andreas Nuechter, Kai Lingemann, Jochen Sprickerhof
*
* Released under the GPL version 3.
*
*/
/**
* @file
* @brief Main programm for matching 3D scans (6D SLAM)
*
* Main programm to match 3D scans with ICP and the globally
* consistent matching approach.
* Use -i from the command line to match with ICP,
* and -I to match 3D Scans using the global algorithm.
*
* @author Andreas Nuechter. Jacobs University Bremen gGmbH, Germany
* @author Kai Lingemann. Institute of Computer Science, University of Osnabrueck, Germany.
* @author Jochen Sprickerhof. Institute of Computer Science, University of Osnabrueck, Germany.
*/
#include "slam6d/scan.h"
#include "slam6d/metaScan.h"
#include "slam6d/io_utils.h"
#include "slam6d/icp6Dapx.h"
#include "slam6d/icp6Dsvd.h"
#include "slam6d/icp6Dquat.h"
#include "slam6d/icp6Dortho.h"
#include "slam6d/icp6Dhelix.h"
#include "slam6d/icp6Ddual.h"
#include "slam6d/icp6Dlumeuler.h"
#include "slam6d/icp6Dlumquat.h"
#include "slam6d/icp6Dquatscale.h"
#include "slam6d/icp6D.h"
#ifdef WITH_CUDA
#include "slam6d/cuda/icp6Dcuda.h"
#endif
#include "slam6d/lum6Deuler.h"
#include "slam6d/lum6Dquat.h"
#include "slam6d/ghelix6DQ2.h"
#include "slam6d/elch6Deuler.h"
#include "slam6d/elch6Dquat.h"
#include "slam6d/elch6DunitQuat.h"
#include "slam6d/elch6Dslerp.h"
#include "slam6d/graphSlam6D.h"
#include "slam6d/gapx6D.h"
#include "slam6d/graph.h"
#include "slam6d/globals.icc"
#ifndef _MSC_VER
#include <getopt.h>
#else
#include "XGetopt.h"
#endif
#include <csignal>
#ifdef _MSC_VER
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#else
#include <strings.h>
#endif
#ifdef WITH_METRICS
#include "slam6d/metrics.h"
#endif //WITH_METRICS
#ifdef _MSC_VER
#if !defined _OPENMP && defined OPENMP
#define _OPENMP
#endif
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
#define WANT_STREAM ///< define the WANT stream :)
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <fstream>
using std::ifstream;
// Handling Segmentation faults and CTRL-C
void sigSEGVhandler (int v)
{
static bool segfault = false;
if(!segfault) {
segfault = true;
cout << endl
<< "# **************************** #" << endl
<< " Segmentation fault or Ctrl-C" << endl
<< "# **************************** #" << endl
<< endl;
// save frames and close scans
for(ScanVector::iterator it = Scan::allScans.begin(); it != Scan::allScans.end(); ++it) {
(*it)->saveFrames();
}
cout << "Frames saved." << endl;
Scan::closeDirectory();
}
exit(-1);
}
/**
* Explains the usage of this program's command line parameters
*/
void usage(char* prog)
{
#ifndef _MSC_VER
const string bold("\033[1m");
const string normal("\033[m");
#else
const string bold("");
const string normal("");
#endif
cout << endl
<< bold << "USAGE " << normal << endl
<< " " << prog << " [options] directory" << endl << endl;
cout << bold << "OPTIONS" << normal << endl
<< bold << " -a" << normal << " NR, " << bold << "--algo=" << normal << "NR [default: 1]" << endl
<< " selects the minimizazion method for the ICP matching algorithm" << endl
<< " 1 = unit quaternion based method by Horn" << endl
<< " 2 = singular value decomposition by Arun et al. " << endl
<< " 3 = orthonormal matrices by Horn et al." << endl
<< " 4 = dual quaternion method by Walker et al." << endl
<< " 5 = helix approximation by Hofer & Potmann" << endl
<< " 6 = small angle approximation" << endl
<< " 7 = Lu & Milios style, i.e., uncertainty based, with Euler angles" << endl
<< " 8 = Lu & Milios style, i.e., uncertainty based, with Quaternion" << endl
<< " 9 = unit quaternion with scale method by Horn" << endl
<< endl
<< bold << " -A" << normal << " NR, " << bold << "--anim=" << normal << "NR [default: first and last frame only]" << endl
<< " if specified, use only every NR-th frame for animation" << endl
<< endl
<< bold << " -c" << normal << " NR, " << bold << "--cldist=" << normal << "NR [default: 500]" << endl
<< " specifies the maximal distance for closed loops" << endl
<< endl
<< bold << " -C" << normal << " NR, " << bold << "--clpairs=" << normal << "NR [default: 6]" << endl
<< " specifies the minimal number of points for an overlap. If not specified" << endl
<< " cldist is used instead" << endl
<< endl
<< bold << " --cache" << normal << endl
<< " turns on cached k-d tree search" << endl
<< endl
<< bold << " -d" << normal << " NR, " << bold << "--dist=" << normal << "NR [default: 25]" << endl
<< " sets the maximal point-to-point distance for matching with ICP to <NR> 'units'" << endl
<< " (unit of scan data, e.g. cm)" << endl
<< endl
<< bold << " -D" << normal << " NR, " << bold << "--distSLAM="
<< normal << "NR [default: same value as -d option]" << endl
<< " sets the maximal point-to-point distance for matching with SLAM to <NR> 'units'" << endl
<< " (unit of scan data, e.g. cm)" << endl
<< endl
<< bold << " --DlastSLAM" << normal << " NR [default not set]" << endl
<< " sets the maximal point-to-point distance for the final SLAM correction," << endl
<< " if final SLAM is not required don't set it." << endl
<< endl
<< bold << " -e" << normal << " NR, " << bold << "--end=" << normal << "NR" << endl
<< " end after scan NR" << endl
<< endl
<< bold << " --exportAllPoints" << normal << endl
<< " writes all registered reduced points to the file points.pts before" << endl
<< " slam6D terminated" << endl
<< endl
<< bold << " --epsICP=" << normal << "NR [default: 0.00001]" << endl
<< " stop ICP iteration if difference is smaller than NR" << endl
<< endl
<< bold << " --epsSLAM=" << normal << " NR [default: 0.5]" << endl
<< " stop SLAM iteration if average difference is smaller than NR" << endl
<< endl
<< bold << " -f" << normal << " F, " << bold << "--format=" << normal << "F" << endl
<< " using shared library F for input" << endl
<< " (chose F from {uos, uos_map, uos_rgb, uos_frames, uos_map_frames, old, rts, rts_map, ifp, riegl_txt, riegl_rgb, riegl_bin, zahn, ply, wrl, xyz, zuf, iais, front, x3d, rxp, ais })" << endl
<< endl
<< bold << " -G" << normal << " NR, " << bold << "--graphSlam6DAlgo=" << normal << "NR [default: 0]" << endl
<< " selects the minimizazion method for the SLAM matching algorithm" << endl
<< " 0 = no global relaxation technique" << endl
<< " 1 = Lu & Milios extension using euler angles due to Borrmann et al." << endl
<< " 2 = Lu & Milios extension using using unit quaternions" << endl
<< " 3 = HELIX approximation by Hofer and Pottmann" << endl
<< " 4 = small angle approximation" << endl
<< bold << " -i" << normal << " NR, " << bold << "--iter=" << normal << "NR [default: 50]" << endl
<< " sets the maximal number of ICP iterations to <NR>" << endl
<< endl
<< bold << " -I" << normal << " NR, " << bold << "--iterSLAM=" << normal << "NR [default: 0]" << endl
<< " sets the maximal number of iterations for SLAM to <NR>" << endl
<< " (if not set, graphSLAM is not executed)" << endl
<< endl
<< bold << " -l" << normal << " NR, " << bold << "--loopsize=" << normal << "NR [default: 20]" << endl
<< " sets the size of a loop, i.e., a loop must exceed <NR> of scans" << endl
<< endl
<< bold << " -L" << normal << " NR, " << bold << "--loop6DAlgo=" << normal << "NR [default: 0]" << endl
<< " selects the method for closing the loop explicitly" << endl
<< " 0 = no loop closing technique" << endl
<< " 1 = euler angles" << endl
<< " 2 = quaternions " << endl
<< " 3 = unit quaternions" << endl
<< " 4 = SLERP (recommended)" << endl
<< endl
<< bold << " --metascan" << normal << endl
<< " Match current scan against a meta scan of all previous scans (default match against the last scan only)" << endl
<< endl
<< bold << " -m" << normal << " NR, " << bold << "--max=" << normal << "NR" << endl
<< " neglegt all data points with a distance larger than NR 'units'" << endl
<< endl
<< bold << " -M" << normal << " NR, " << bold << "--min=" << normal << "NR" << endl
<< " neglegt all data points with a distance smaller than NR 'units'" << endl
<< endl
<< bold << " -n" << normal << " FILE, " << bold << "--net=" << normal << "FILE" << endl
<< " specifies the file that includes the net structure for SLAM" << endl
<< endl
<< bold << " -O" << normal << "NR (optional), " << bold << "--octree=" << normal << "NR (optional)" << endl
<< " use randomized octree based point reduction (pts per voxel=<NR>)" << endl
<< " requires " << bold << "-r" << normal <<" or " << bold << "--reduce" << endl
<< endl
<< bold << " -p, --trustpose" << normal << endl
<< " Trust the pose file, do not extrapolate the last transformation." << endl
<< " (just for testing purposes, or gps input.)" << endl
<< endl
<< bold << " -q, --quiet" << normal << endl
<< " Quiet mode. Suppress (most) messages" << endl
<< endl
<< bold << " -Q, --veryquiet" << normal << endl
<< " Very quiet mode. Suppress all messages, except in case of error." << endl
<< endl
<< bold << " -S, --scanserver" << normal << endl
<< " Use the scanserver as an input method and handling of scan data" << endl
<< endl
<< bold << " -r" << normal << " NR, " << bold << "--reduce=" << normal << "NR" << endl
<< " turns on octree based point reduction (voxel size=<NR>)" << endl
<< endl
<< bold << " -R" << normal << " NR, " << bold << "--random=" << normal << "NR" << endl
<< " turns on randomized reduction, using about every <NR>-th point only" << endl
<< endl
<< bold << " -s" << normal << " NR, " << bold << "--start=" << normal << "NR" << endl
<< " start at scan NR (i.e., neglects the first NR scans)" << endl
<< " [ATTENTION: counting naturally starts with 0]" << endl
<< endl
<< bold << " -t" << normal << " NR, " << bold << "--nns_method=" << normal << "NR [default: 1]" << endl
<< " selects the Nearest Neighbor Search Algorithm" << endl
<< " 0 = simple k-d tree " << endl
<< " 1 = cached k-d tree " << endl
<< " 2 = ANNTree " << endl
<< " 3 = BOCTree " << endl
<< endl
<< bold << " -u" << normal <<", "<< bold<<"--cuda" << normal << endl
<< " this option activates icp running on GPU instead of CPU"<<endl
<< endl << endl;
cout << bold << "EXAMPLES " << normal << endl
<< " " << prog << " dat" << endl
<< " " << prog << " --max=500 -r 10.2 -i 20 dat" << endl
<< " " << prog << " -s 2 -e 10 dat" << endl << endl;
exit(1);
}
/** A function that parses the command-line arguments and sets the respective flags.
* @param argc the number of arguments
* @param argv the arguments
* @param dir the directory
* @param red using point reduction?
* @param rand use randomized point reduction?
* @param mdm maximal distance match
* @param mdml maximal distance match for SLAM
* @param mni maximal number of iterations
* @param start starting at scan number 'start'
* @param end stopping at scan number 'end'
* @param maxDist - maximal distance of points being loaded
* @param minDist - minimal distance of points being loaded
* @param quiet switches on/off the quiet mode
* @param veryQuiet switches on/off the 'very quiet' mode
* @param extrapolate_pose - i.e., extrapolating the odometry by the last transformation
* (vs. taking the pose file as <b>exact</b>)
* @param meta match against all scans (= meta scan), or against the last scan only???
* @param anim selects the rotation representation for the matching algorithm
* @param mni_lum sets the maximal number of iterations for SLAM
* @param net specifies the file that includes the net structure for SLAM
* @param cldist specifies the maximal distance for closed loops
* @param epsilonICP stop ICP iteration if difference is smaller than this value
* @param epsilonSLAM stop SLAM iteration if average difference is smaller than this value
* @param algo specfies the used algorithm for rotation computation
* @param lum6DAlgo specifies the used algorithm for global SLAM correction
* @param loopsize defines the minimal loop size
* @return 0, if the parsing was successful. 1 otherwise
*/
int parseArgs(int argc, char **argv, string &dir, double &red, int &rand,
double &mdm, double &mdml, double &mdmll,
int &mni, int &start, int &end, int &maxDist, int &minDist, bool &quiet, bool &veryQuiet,
bool &extrapolate_pose, bool &meta, int &algo, int &loopSlam6DAlgo, int &lum6DAlgo, int &anim,
int &mni_lum, string &net, double &cldist, int &clpairs, int &loopsize,
double &epsilonICP, double &epsilonSLAM, int &nns_method, bool &exportPts, double &distLoop,
int &iterLoop, double &graphDist, int &octree, bool &cuda_enabled, IOType &type,
bool& scanserver, PairingMode& pairing_mode)
{
int c;
// from unistd.h:
extern char *optarg;
extern int optind;
WriteOnce<IOType> w_type(type);
WriteOnce<int> w_start(start), w_end(end);
/* options descriptor */
// 0: no arguments, 1: required argument, 2: optional argument
static struct option longopts[] = {
{ "format", required_argument, 0, 'f' },
{ "algo", required_argument, 0, 'a' },
{ "nns_method", required_argument, 0, 't' },
{ "loop6DAlgo", required_argument, 0, 'L' },
{ "graphSlam6DAlgo", required_argument, 0, 'G' },
{ "net", required_argument, 0, 'n' },
{ "iter", required_argument, 0, 'i' },
{ "iterSLAM", required_argument, 0, 'I' },
{ "max", required_argument, 0, 'm' },
{ "loopsize", required_argument, 0, 'l' },
{ "cldist", required_argument, 0, 'c' },
{ "clpairs", required_argument, 0, 'C' },
{ "min", required_argument, 0, 'M' },
{ "dist", required_argument, 0, 'd' },
{ "distSLAM", required_argument, 0, 'D' },
{ "start", required_argument, 0, 's' },
{ "end", required_argument, 0, 'e' },
{ "reduce", required_argument, 0, 'r' },
{ "octree", optional_argument, 0, 'O' },
{ "random", required_argument, 0, 'R' },
{ "quiet", no_argument, 0, 'q' },
{ "veryquiet", no_argument, 0, 'Q' },
{ "trustpose", no_argument, 0, 'p' },
{ "anim", required_argument, 0, 'A' },
{ "metascan", no_argument, 0, '2' }, // use the long format only
{ "DlastSLAM", required_argument, 0, '4' }, // use the long format only
{ "epsICP", required_argument, 0, '5' }, // use the long format only
{ "epsSLAM", required_argument, 0, '6' }, // use the long format only
{ "normalshoot", no_argument, 0, '7' }, // use the long format only
{ "point-to-plane", no_argument, 0, 'z' }, // use the long format only
{ "exportAllPoints", no_argument, 0, '8' },
{ "distLoop", required_argument, 0, '9' }, // use the long format only
{ "iterLoop", required_argument, 0, '1' }, // use the long format only
{ "graphDist", required_argument, 0, '3' }, // use the long format only
{ "cuda", no_argument, 0, 'u' }, // cuda will be enabled
{ "scanserver", no_argument, 0, 'S' },
{ 0, 0, 0, 0} // needed, cf. getopt.h
};
cout << endl;
while ((c = getopt_long(argc, argv, "O:f:A:G:L:a:t:r:R:d:D:i:l:I:c:C:n:s:e:m:M:uqQpS", longopts, NULL)) != -1) {
switch (c) {
case 'a':
algo = atoi(optarg);
if ((algo < 0) || (algo > 9)) {
cerr << "Error: ICP Algorithm not available." << endl;
exit(1);
}
break;
case 't':
nns_method = atoi(optarg);
if ((nns_method < 0) || (nns_method > 3)) {
cerr << "Error: NNS Method not available." << endl;
exit(1);
}
break;
case 'L':
loopSlam6DAlgo = atoi(optarg);
if (loopSlam6DAlgo < 0 || loopSlam6DAlgo > 6) {
cerr << "Error: global loop closing algorithm not available." << endl;
exit(1);
}
break;
case 'G':
lum6DAlgo = atoi(optarg);
if ((lum6DAlgo < 0) || (lum6DAlgo > 6)) {
cerr << "Error: global relaxation algorithm not available." << endl;
exit(1);
}
break;
case 'c':
cldist = atof(optarg);
break;
case 'C':
clpairs = atoi(optarg);
break;
case 'l':
loopsize = atoi(optarg);
break;
case 'r':
red = atof(optarg);
break;
case 'O':
if (optarg) {
octree = atoi(optarg);
} else {
octree = 1;
}
break;
case 'R':
rand = atoi(optarg);
break;
case 'd':
mdm = atof(optarg);
break;
case 'D':
mdml = atof(optarg);
break;
case 'i':
mni = atoi(optarg);
break;
case 'I':
mni_lum = atoi(optarg);
break;
case 'n':
net = optarg;
break;
case 's':
w_start = atoi(optarg);
if (start < 0) { cerr << "Error: Cannot start at a negative scan number.\n"; exit(1); }
break;
case 'e':
w_end = atoi(optarg);
if (end < 0) { cerr << "Error: Cannot end at a negative scan number.\n"; exit(1); }
if (end < start) { cerr << "Error: <end> cannot be smaller than <start>.\n"; exit(1); }
break;
case 'm':
maxDist = atoi(optarg);
break;
case 'M':
minDist = atoi(optarg);
break;
case 'q':
quiet = true;
break;
case 'Q':
quiet = veryQuiet = true;
break;
case 'p':
extrapolate_pose = false;
break;
case 'A':
anim = atoi(optarg);
break;
case '2': // = --metascan
meta = true;
break;
case '4': // = --DlastSLAM
mdmll = atof(optarg);
break;
case '5': // = --epsICP
epsilonICP = atof(optarg);
break;
case '6': // = --epsSLAM
epsilonSLAM = atof(optarg);
break;
case '8': // not used
exportPts = true;
break;
case '9': // = --distLoop
distLoop = atof(optarg);
break;
case '1': // = --iterLoop
iterLoop = atoi(optarg);
break;
case '3': // = --graphDist
graphDist = atof(optarg);
break;
case '7': // = --normalshoot
pairing_mode = CLOSEST_POINT_ALONG_NORMAL;
break;
case 'z': // = --point-to-plane
pairing_mode = CLOSEST_PLANE;
break;
case 'f':
try {
w_type = formatname_to_io_type(optarg);
} catch (...) { // runtime_error
cerr << "Format " << optarg << " unknown." << endl;
abort();
}
break;
case 'u':
cuda_enabled = true;
break;
case 'S':
scanserver = true;
break;
case '?':
usage(argv[0]);
return 1;
default:
abort ();
}
}
if (optind != argc-1) {
cerr << "\n*** Directory missing ***" << endl;
usage(argv[0]);
}
dir = argv[optind];
#ifndef _MSC_VER
if (dir[dir.length()-1] != '/') dir = dir + "/";
#else
if (dir[dir.length()-1] != '\\') dir = dir + "\\";
#endif
parseFormatFile(dir, w_type, w_start, w_end);
return 0;
}
/**
* This function is does all the matching stuff
* it iterates over all scans using the algorithm objects to calculate new poses
* objects could be NULL if algorithm should not be used
*
* @param cldist maximal distance for closing loops
* @param loopsize minimal loop size
* @param allScans Contains all laser scans
* @param my_icp6D the ICP implementation
* @param meta_icp math ICP against a metascan
* @param nns_method Indicates the nearest neigbor search method to be used
* @param my_loopSlam6D used loopoptimizer
* @param my_graphSlam6D used global optimization
* @param nrIt The number of iterations the global SLAM-algorithm will run
* @param epsilonSLAM epsilon for global SLAM iteration
* @param mdml maximal distance match for global SLAM
* @param mdmll maximal distance match for global SLAM after all scans ar matched
*/
void matchGraph6Dautomatic(double cldist, int loopsize, vector <Scan *> allScans, icp6D *my_icp6D,
bool meta_icp, int nns_method, bool cuda_enabled,
loopSlam6D *my_loopSlam6D, graphSlam6D *my_graphSlam6D, int nrIt,
double epsilonSLAM, double mdml, double mdmll, double graphDist,
bool &eP, IOType type)
{
double cldist2 = sqr(cldist);
// list of scan for metascan
vector < Scan* > metas;
// graph for loop optimization
graph_t g;
int n = allScans.size();
int loop_detection = 0;
double dist, min_dist = -1;
int first = 0, last = 0;
for(int i = 1; i < n; i++) {
cout << i << "/" << n << endl;
add_edge(i-1, i, g);
if(eP) {
allScans[i]->mergeCoordinatesWithRoboterPosition(allScans[i-1]);
}
//Hack to get all icp transformations into the .frames Files
if(i == n-1 && my_icp6D != NULL && my_icp6D->get_anim() == -2) {
my_icp6D->set_anim(-1);
}
/*if(i == 85 || i == 321 || i == 533) {
my_icp6D->set_anim(1);
}*/
if(my_icp6D != NULL){
cout << "ICP" << endl;
// Matching strongly linked scans with ICPs
if(meta_icp) {
metas.push_back(allScans[i - 1]);
MetaScan* meta_scan = new MetaScan(metas);
my_icp6D->match(meta_scan, allScans[i]);
delete meta_scan;
} else {
switch(type) {
case UOS_MAP:
case UOS_MAP_FRAMES:
my_icp6D->match(allScans[0], allScans[i]);
break;
case RTS_MAP:
//untested (and could not work)
//if(i < 220-22 && i > 250-22) match(allScans[0], CurrentScan);
my_icp6D->match(allScans[0], allScans[i]);
break;
default:
my_icp6D->match(allScans[i - 1], allScans[i]);
break;
}
}
} else {
double id[16];
M4identity(id);
allScans[i]->transform(id, Scan::ICP, 0);
}
/*if(i == 85 || i == 321 || i == 533) {
my_icp6D->set_anim(-2);
}*/
if(loop_detection == 1) {
loop_detection = 2;
}
for(int j = 0; j < i - loopsize; j++) {
dist = Dist2(allScans[j]->get_rPos(), allScans[i]->get_rPos());
if(dist < cldist2) {
loop_detection = 1;
if(min_dist < 0 || dist < min_dist) {
min_dist = dist;
first = j;
last = i;
}
}
}
if(loop_detection == 2) {
loop_detection = 0;
min_dist = -1;
if(my_loopSlam6D != NULL) {
cout << "Loop close: " << first << " " << last << endl;
my_loopSlam6D->close_loop(allScans, first, last, g);
add_edge(first, last, g);
}
if(my_graphSlam6D != NULL && mdml > 0) {
int j = 0;
double ret;
do {
// recalculate graph
Graph *gr = new Graph(i + 1, cldist2, loopsize);
cout << "Global: " << j << endl;
ret = my_graphSlam6D->doGraphSlam6D(*gr, allScans, 1);
delete gr;
j++;
} while (j < nrIt && ret > epsilonSLAM);
}
}
}
if(loop_detection == 1 && my_loopSlam6D != NULL) {
cout << "Loop close: " << first << " " << last << endl;
my_loopSlam6D->close_loop(allScans, first, last, g);
add_edge(first, last, g);
}
if(my_graphSlam6D != NULL && mdml > 0.0) {
int j = 0;
double ret;
do {
// recalculate graph
Graph *gr = new Graph(n, cldist2, loopsize);
cout << "Global: " << j << endl;
ret = my_graphSlam6D->doGraphSlam6D(*gr, allScans, 1);
delete gr;
j++;
} while (j < nrIt && ret > epsilonSLAM);
}
if(my_graphSlam6D != NULL && mdmll > 0.0) {
my_graphSlam6D->set_mdmll(mdmll);
int j = 0;
double ret;
do {
// recalculate graph
Graph *gr = new Graph(n, sqr(graphDist), loopsize);
cout << "Global: " << j << endl;
ret = my_graphSlam6D->doGraphSlam6D(*gr, allScans, 1);
delete gr;
j++;
} while (j < nrIt && ret > epsilonSLAM);
}
}
/**
* Main program for 6D SLAM.
* Usage: bin/slam6D 'dir',
* with 'dir' the directory of a set of scans
* ...
*/
int main(int argc, char **argv)
{
signal (SIGSEGV, sigSEGVhandler);
signal (SIGINT, sigSEGVhandler);
cout << "slam6D - A highly efficient SLAM implementation based on scan matching" << endl
<< " with 6 degrees of freedom" << endl
<< "(c) Jacobs University Bremen gGmbH, Germany, since 2009" << endl
<< " University of Osnabrueck, Germany, since 2006" << endl << endl;
if (argc <= 1) {
usage(argv[0]);
}
// parsing the command line parameters
// init, default values if not specified
string dir;
double red = -1.0, mdmll = -1.0, mdml = 25.0, mdm = 25.0;
int rand = -1, mni = 50;
int start = 0, end = -1;
bool quiet = false;
bool veryQuiet = false;
int maxDist = -1;
int minDist = -1;
bool eP = true; // should we extrapolate the pose??
bool meta = false; // match against meta scan, or against LAST scan only?
int algo = 1;
int mni_lum = -1;
double cldist = 500;
int clpairs = -1;
int loopsize = 20;
string net = "none";
int anim = -1;
double epsilonICP = 0.00001;
double epsilonSLAM = 0.5;
int nns_method = simpleKD;
bool exportPts = false;
int loopSlam6DAlgo = 0;
int lum6DAlgo = 0;
double distLoop = 700.0;
int iterLoop = 100;
double graphDist = cldist;
int octree = 0; // employ randomized octree reduction?
bool cuda_enabled = false;
IOType type = UOS;
bool scanserver = false;
PairingMode pairing_mode = CLOSEST_POINT;
parseArgs(argc, argv, dir, red, rand, mdm, mdml, mdmll, mni, start, end,
maxDist, minDist, quiet, veryQuiet, eP, meta, algo, loopSlam6DAlgo, lum6DAlgo, anim,
mni_lum, net, cldist, clpairs, loopsize, epsilonICP, epsilonSLAM,
nns_method, exportPts, distLoop, iterLoop, graphDist, octree, cuda_enabled, type,
scanserver, pairing_mode);
cout << "slam6D will proceed with the following parameters:" << endl;
//@@@ to do :-)
// TODO: writer a proper TODO ^
Scan::openDirectory(scanserver, dir, type, start, end);
if(Scan::allScans.size() == 0) {
cerr << "No scans found. Did you use the correct format?" << endl;
exit(-1);
}
for(ScanVector::iterator it = Scan::allScans.begin(); it != Scan::allScans.end(); ++it) {
Scan* scan = *it;
scan->setRangeFilter(maxDist, minDist);
unsigned int types = 0;
if ((pairing_mode == CLOSEST_POINT_ALONG_NORMAL) ||
(pairing_mode == CLOSEST_PLANE)) {
types = PointType::USE_NORMAL;
}
scan->setReductionParameter(red, octree, PointType(types));
scan->setSearchTreeParameter(nns_method, cuda_enabled);
}
icp6Dminimizer *my_icp6Dminimizer = 0;
switch (algo) {
case 1 :
my_icp6Dminimizer = new icp6D_QUAT(quiet);
break;
case 2 :
my_icp6Dminimizer = new icp6D_SVD(quiet);
break;
case 3 :
my_icp6Dminimizer = new icp6D_ORTHO(quiet);
break;
case 4 :
my_icp6Dminimizer = new icp6D_DUAL(quiet);
break;
case 5 :
my_icp6Dminimizer = new icp6D_HELIX(quiet);
break;
case 6 :
my_icp6Dminimizer = new icp6D_APX(quiet);
break;
case 7 :
my_icp6Dminimizer = new icp6D_LUMEULER(quiet);
break;
case 8 :
my_icp6Dminimizer = new icp6D_LUMQUAT(quiet);
break;
case 9 :
my_icp6Dminimizer = new icp6D_QUAT_SCALE(quiet);
break;
}
// match the scans and print the time used
long starttime = GetCurrentTimeInMilliSec();
#ifdef WITH_METRICS
Timer t = ClientMetric::matching_time.start();
#endif //WITH_METRICS
if (mni_lum == -1 && loopSlam6DAlgo == 0) {
icp6D *my_icp = 0;
if (cuda_enabled) {
#ifdef WITH_CUDA
my_icp = new icp6Dcuda(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, cuda_enabled);
#else
cout << "slam6d was not compiled for excuting CUDA code" << endl;
#endif
} else {
my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, cuda_enabled);
}
// check if CAD matching was selected as type
if (type == UOS_CAD)
{
my_icp->set_cad_matching (true);
}
if (my_icp) my_icp->doICP(Scan::allScans, pairing_mode);
delete my_icp;
} else if (clpairs > -1) {
//!!!!!!!!!!!!!!!!!!!!!!!!
icp6D *my_icp = 0;
if (cuda_enabled) {
#ifdef WITH_CUDA
my_icp = new icp6Dcuda(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, cuda_enabled);
#else
cout << "slam6d was not compiled for excuting CUDA code" << endl;
#endif
} else {
my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, cuda_enabled);
}
my_icp->doICP(Scan::allScans, pairing_mode);
graphSlam6D *my_graphSlam6D = new lum6DEuler(my_icp6Dminimizer, mdm, mdml, mni, quiet, meta,
rand, eP, anim, epsilonICP, nns_method, epsilonSLAM);
my_graphSlam6D->matchGraph6Dautomatic(Scan::allScans, mni_lum, clpairs, loopsize);
//!!!!!!!!!!!!!!!!!!!!!!!!
} else {
graphSlam6D *my_graphSlam6D = 0;
switch (lum6DAlgo) {
case 1 :
my_graphSlam6D = new lum6DEuler(my_icp6Dminimizer, mdm, mdml, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, epsilonSLAM);
break;
case 2 :
my_graphSlam6D = new lum6DQuat(my_icp6Dminimizer, mdm, mdml, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, epsilonSLAM);
break;
case 3 :
my_graphSlam6D = new ghelix6DQ2(my_icp6Dminimizer, mdm, mdml, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, epsilonSLAM);
break;
case 4 :
my_graphSlam6D = new gapx6D(my_icp6Dminimizer, mdm, mdml, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, epsilonSLAM);
break;
}
// Construct Network
if (net != "none") {
icp6D *my_icp = 0;
if (cuda_enabled) {
#ifdef WITH_CUDA
my_icp = new icp6Dcuda(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method);
#else
cout << "slam6d was not compiled for excuting CUDA code" << endl;
#endif
} else {
my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method);
}
my_icp->doICP(Scan::allScans, pairing_mode);
Graph* structure;
structure = new Graph(net);
my_graphSlam6D->doGraphSlam6D(*structure, Scan::allScans, mni_lum);
if(mdmll > 0.0) {
my_graphSlam6D->set_mdmll(mdmll);
my_graphSlam6D->doGraphSlam6D(*structure, Scan::allScans, mni_lum);
}
} else {
icp6D *my_icp = 0;
if(algo > 0) {
if (cuda_enabled) {
#ifdef WITH_CUDA
my_icp = new icp6Dcuda(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method);
#else
cout << "slam6d was not compiled for excuting CUDA code" << endl;
#endif
} else {
my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method);
}
loopSlam6D *my_loopSlam6D = 0;
switch(loopSlam6DAlgo) {
case 1:
my_loopSlam6D = new elch6Deuler(veryQuiet, my_icp6Dminimizer, distLoop, iterLoop,
rand, eP, 10, epsilonICP, nns_method);
break;
case 2:
my_loopSlam6D = new elch6Dquat(veryQuiet, my_icp6Dminimizer, distLoop, iterLoop,
rand, eP, 10, epsilonICP, nns_method);
break;
case 3:
my_loopSlam6D = new elch6DunitQuat(veryQuiet, my_icp6Dminimizer, distLoop, iterLoop,
rand, eP, 10, epsilonICP, nns_method);
break;
case 4:
my_loopSlam6D = new elch6Dslerp(veryQuiet, my_icp6Dminimizer, distLoop, iterLoop,
rand, eP, 10, epsilonICP, nns_method);
break;
}
matchGraph6Dautomatic(cldist, loopsize, Scan::allScans, my_icp, meta,
nns_method, cuda_enabled, my_loopSlam6D, my_graphSlam6D,
mni_lum, epsilonSLAM, mdml, mdmll, graphDist, eP, type);
delete my_icp;
if(loopSlam6DAlgo > 0) {
delete my_loopSlam6D;
}
}
if(my_graphSlam6D > 0) {
delete my_graphSlam6D;
}
}
}
#ifdef WITH_METRICS
ClientMetric::matching_time.end(t);
#endif //WITH_METRICS
long endtime = GetCurrentTimeInMilliSec() - starttime;
cout << "Matching done in " << endtime << " milliseconds!!!" << endl;
if (exportPts) {
cout << "Export all 3D Points to file \"points.pts\"" << endl;
ofstream redptsout("points.pts");
for(unsigned int i = 0; i < Scan::allScans.size(); i++) {
DataXYZ xyz_r(Scan::allScans[i]->get("xyz reduced"));
DataNormal normal_r(Scan::allScans[i]->get("normal reduced"));
for(unsigned int i = 0; i < xyz_r.size(); ++i) {
int r,g,b;
r = (int)(normal_r[i][0] * (127.5) + 127.5);
g = (int)(normal_r[i][1] * (127.5) + 127.5);
b = (int)(fabs(normal_r[i][2]) * (255.0));
redptsout << xyz_r[i][0] << ' ' << xyz_r[i][1] << ' ' << xyz_r[i][2]
<< ' ' << r << ' ' << g << ' ' << b << '\n';
}
redptsout << std::flush;
}
redptsout.close();
redptsout.clear();
}
const double* p;
ofstream redptsout("loopclose.pts");
for(ScanVector::iterator it = Scan::allScans.begin(); it != Scan::allScans.end(); ++it)
{
Scan* scan = *it;
p = scan->get_rPos();
Point x(p[0], p[1], p[2]);
redptsout << x << endl;
scan->saveFrames();
}
redptsout.close();
Scan::closeDirectory();
delete my_icp6Dminimizer;
cout << endl << endl;
cout << "Normal program end." << endl
<< (red < 0 && rand < 0 ? "(-> HINT: For a significant speedup, please use the '-r' or '-R' parameter <-)\n"
: "")
<< endl;
// print metric information
#ifdef WITH_METRICS
ClientMetric::print(scanserver);
#endif //WITH_METRICS
}

View file

@ -0,0 +1,424 @@
cmake_minimum_required (VERSION 2.8.2)
SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/3rdparty/CMakeModules" ${CMAKE_MODULE_PATH})
project (3DTK)
#include_directories(OPENGL_INCLUDE_DIR)
IF(WIN32)
set(Boost_USE_STATIC_LIBS TRUE)
ELSE(WIN32)
set(Boost_USE_STATIC_LIBS FALSE)
ENDIF(WIN32)
SET(Boost_ADDITIONAL_VERSIONS "1.42" "1.42.0" "1.44" "1.44.0" "1.45.0" "1.45" "1.46" "1.46.1" "1.47.0" "1.47" "1.48" "1.49")
IF(WIN32)
# for some unknown reason no one variant works on all windows platforms
find_package( Boost COMPONENTS serialization graph regex filesystem system thread date_time program_options REQUIRED)
ELSE(WIN32)
find_package( Boost COMPONENTS serialization graph regex filesystem system thread date_time program_options REQUIRED)
ENDIF(WIN32)
if(Boost_FOUND)
link_directories(${BOOST_LIBRARY_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})
endif()
FIND_PACKAGE(OpenCV REQUIRED)
include("3rdparty/CMakeModules/OpenCV.cmake")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ADDITIONAL_OPENCV_FLAGS}")
#################################################
# Declare Options and modify build accordingly ##
#################################################
FUNCTION(ENFORCE_OPTION_DEP_3DTK option VALUE)
SET (${option} "${VALUE}" CACHE BOOL "${${option}_DESCRIPTION}" FORCE) # this option set to VALUE as advised
#now make sure other dependencies are also true
FOREACH(d ${${option}_DEPENDENCIES}) # look through all my dependencies
STRING(REGEX REPLACE " +" ";" CMAKE_DEPENDENT_OPTION_DEP "${d}")
# check for a not in front
STRING(STRIP "${CMAKE_DEPENDENT_OPTION_DEP}" CMAKE_DEPENDENT_OPTION_DEP)
STRING(SUBSTRING "${CMAKE_DEPENDENT_OPTION_DEP}" 0 3 CMAKE_DEPENDENT_OPTION_DEP_3)
STRING(TOUPPER "${CMAKE_DEPENDENT_OPTION_DEP_3}" CMAKE_DEPENDENT_OPTION_DEP_3)
STRING(COMPARE EQUAL "${CMAKE_DEPENDENT_OPTION_DEP_3}" "NOT" CMAKE_DEPENDENT_OPTION_DEP_NOT)
#STRING(REPLACE "NOT " "" CMAKE_DEPENDENT_OPTION_DEP "${d}")
IF(CMAKE_DEPENDENT_OPTION_DEP_NOT) # we found a NOT
STRING(REPLACE "NOT;" "" CMAKE_DEPENDENT_OPTION_DEP "${CMAKE_DEPENDENT_OPTION_DEP}")
IF(${CMAKE_DEPENDENT_OPTION_DEP}) # not met, make sure it is
ENFORCE_OPTION_DEP_3DTK(${CMAKE_DEPENDENT_OPTION_DEP} OFF)
ELSE(${CMAKE_DEPENDENT_OPTION_DEP}) # dependency is met
ENDIF(${CMAKE_DEPENDENT_OPTION_DEP})
ELSE(CMAKE_DEPENDENT_OPTION_DEP_NOT)
IF(${CMAKE_DEPENDENT_OPTION_DEP}) # dependency is met
ELSE(${CMAKE_DEPENDENT_OPTION_DEP}) # not met, make sure it is
ENFORCE_OPTION_DEP_3DTK(${CMAKE_DEPENDENT_OPTION_DEP} ON)
ENDIF(${CMAKE_DEPENDENT_OPTION_DEP})
ENDIF(CMAKE_DEPENDENT_OPTION_DEP_NOT)
ENDFOREACH(d)
ENDFUNCTION(ENFORCE_OPTION_DEP_3DTK)
MACRO(OPT_DEP option doc default depends)
OPTION(${option} "${doc}" "${default}")
SET(${option} "${${option}}" CACHE BOOL "${doc}" FORCE)
SET(${option}_DEPENDENCIES "${depends}" CACHE INTERNAL "" FORCE)
SET(${option}_DESCRIPTION "${doc}" CACHE INTERNAL "" FORCE)
IF (${option})
#MESSAGE(STATUS "Yes ${option} is true")
# MESSAGE("FOREACH d in ${depends}")
FOREACH(d ${depends})
STRING(REGEX REPLACE " +" ";" CMAKE_DEPENDENT_OPTION_DEP "${d}")
# check for a not in front
STRING(STRIP "${CMAKE_DEPENDENT_OPTION_DEP}" CMAKE_DEPENDENT_OPTION_DEP)
STRING(SUBSTRING "${CMAKE_DEPENDENT_OPTION_DEP}" 0 3 CMAKE_DEPENDENT_OPTION_DEP_3)
STRING(TOUPPER "${CMAKE_DEPENDENT_OPTION_DEP_3}" CMAKE_DEPENDENT_OPTION_DEP_3)
STRING(COMPARE EQUAL "${CMAKE_DEPENDENT_OPTION_DEP_3}" "NOT" CMAKE_DEPENDENT_OPTION_DEP_NOT)
IF(CMAKE_DEPENDENT_OPTION_DEP_NOT) # we found a NOT
STRING(REPLACE "NOT;" "" CMAKE_DEPENDENT_OPTION_DEP "${CMAKE_DEPENDENT_OPTION_DEP}")
IF(${CMAKE_DEPENDENT_OPTION_DEP}) # not met, make sure it is
ENFORCE_OPTION_DEP_3DTK(${CMAKE_DEPENDENT_OPTION_DEP} OFF)
ELSE(${CMAKE_DEPENDENT_OPTION_DEP}) # dependency is met
ENDIF(${CMAKE_DEPENDENT_OPTION_DEP})
ELSE(CMAKE_DEPENDENT_OPTION_DEP_NOT)
IF(${CMAKE_DEPENDENT_OPTION_DEP}) # dependency is met
ELSE(${CMAKE_DEPENDENT_OPTION_DEP}) # not met, make sure it is
ENFORCE_OPTION_DEP_3DTK(${CMAKE_DEPENDENT_OPTION_DEP} ON)
ENDIF(${CMAKE_DEPENDENT_OPTION_DEP})
ENDIF(CMAKE_DEPENDENT_OPTION_DEP_NOT)
ENDFOREACH(d)
ENDIF(${option})
ENDMACRO(OPT_DEP)
## FreeGLUT
OPT_DEP(WITH_FREEGLUT "Whether freeglut is available. This enables iterative drawing in show. ON/OFF" ON "")
IF(WITH_FREEGLUT)
MESSAGE(STATUS "With freeglut")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWITH_FREEGLUT")
ELSE(WITH_FREEGLUT)
MESSAGE(STATUS "Without freeglut")
ENDIF(WITH_FREEGLUT)
## Show
OPT_DEP(WITH_SHOW "Whether to build Show. This is the Visualization program of slam6d. ON/OFF" ON "" )
IF(WITH_SHOW)
FIND_PACKAGE(OpenGL REQUIRED)
FIND_PACKAGE(GLUT REQUIRED)
MESSAGE(STATUS "With show")
ELSE(WITH_SHOW)
# SET (WITH_OCTREE_DISPLAY "ON" CACHE INTERNAL "" FORCE)
MESSAGE(STATUS "Without show")
ENDIF(WITH_SHOW)
## WXShow
OPT_DEP(WITH_WXSHOW "Whether to build WXShow. This is the wxwidgets variant of Show. ON/OFF" OFF "")
IF(WITH_WXSHOW)
FIND_PACKAGE(OpenGL REQUIRED)
FIND_PACKAGE(GLUT REQUIRED)
find_package(wxWidgets COMPONENTS core base gl REQUIRED)
# set wxWidgets_wxrc_EXECUTABLE to be ignored in the configuration
SET (wxWidgets_wxrc_EXECUTABLE " " CACHE INTERNAL "" FORCE)
# wxWidgets include (this will do all the magic to configure everything)
include( ${wxWidgets_USE_FILE})
MESSAGE(STATUS "With wxshow")
ELSE(WITH_WXSHOW)
MESSAGE(STATUS "Without wxshow")
ENDIF(WITH_WXSHOW)
## Shapes
OPT_DEP(WITH_SHAPE_DETECTION "Whether to build shapes and planes executable for detecting planes. ON/OFF" OFF "")
IF(WITH_SHAPE_DETECTION)
MESSAGE(STATUS "With shape detection")
ELSE(WITH_SHAPE_DETECTION)
MESSAGE(STATUS "Without shape detection")
ENDIF(WITH_SHAPE_DETECTION)
## Interior reconstruction
OPT_DEP(WITH_MODEL "Whether to build model executable for modelling interior environments. ON/OFF" OFF "")
if(WITH_MODEL)
message(STATUS "With interior reconstruction")
else(WITH_MODEL)
message(STATUS "Without interior reconstruction")
endif(WITH_MODEL)
## Thermo
OPT_DEP(WITH_THERMO "Whether to build executables for mutual calibration of laser scanner and camera. ON/OFF" OFF "WITH_SHAPE_DETECTION")
IF(WITH_THERMO)
add_subdirectory(3rdparty/cvblob)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob)
link_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob)
MESSAGE(STATUS "With thermo")
ELSE(WITH_THERMO)
MESSAGE(STATUS "Without thermo")
ENDIF(WITH_THERMO)
## Octree
OPT_DEP(WITH_COMPACT_OCTREE "Whether to use the compact octree display ON/OFF" OFF "")
IF(WITH_COMPACT_OCTREE)
MESSAGE(STATUS "Using compact octrees")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_COMPACT_TREE")
ELSE(WITH_COMPACT_OCTREE)
MESSAGE(STATUS "Not using compact octreees: Warning uses more memory")
ENDIF(WITH_COMPACT_OCTREE)
## Glee?
OPT_DEP(WITH_GLEE "Whether to use OpenGL extensions, requires glee. ON/OFF" OFF "")
IF(WITH_GLEE)
MESSAGE(STATUS "Using opengl extensions")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWITH_GLEE")
ELSE(WITH_GLEE)
MESSAGE(STATUS "Not using opengl extensions")
ENDIF(WITH_GLEE)
## Gridder
OPT_DEP(WITH_GRIDDER "Whether to build the 2DGridder binary ON/OFF" OFF "")
IF(WITH_GRIDDER)
MESSAGE(STATUS "With 2DGridder")
ELSE(WITH_GRIDDER)
MESSAGE(STATUS "Without 2DGridder")
ENDIF(WITH_GRIDDER)
## Dynamic VELOSLAM
OPT_DEP(WITH_VELOSLAM "Whether to build the Velodyne data processing (veloslam/veloshow) ON/OFF" OFF "WITH_SHOW")
IF(WITH_VELOSLAM)
MESSAGE(STATUS "With VELOSLAM")
ELSE(WITH_VELOSLAM)
MESSAGE(STATUS "Without VELOSLAM")
ENDIF(WITH_VELOSLAM)
## Home-made Laserscanner
OPT_DEP(WITH_DAVID_3D_SCANNER "Whether to build the David scanner app for homemade laser scanners binary ON/OFF" OFF "")
IF(WITH_DAVID_3D_SCANNER)
MESSAGE(STATUS "With David scanner")
ELSE(WITH_DAVID_3D_SCANNER)
MESSAGE(STATUS "Without David scanner")
ENDIF(WITH_DAVID_3D_SCANNER)
## Tools
OPT_DEP(WITH_TOOLS "Whether to build additional tools like convergence frame_to_graph etc. ON/OFF" OFF "WITH_FBR")
IF(WITH_TOOLS)
MESSAGE(STATUS "With Tools")
find_package (Boost COMPONENTS program_options REQUIRED)
ELSE(WITH_TOOLS)
MESSAGE(STATUS "Without Tools")
ENDIF(WITH_TOOLS)
## Segmentation
OPT_DEP(WITH_SEGMENTATION "Whether to build scan segmantion program ON/OFF" OFF "WITH_FBR")
IF(WITH_SEGMENTATION)
MESSAGE(STATUS "With segmentation")
find_package (Boost COMPONENTS program_options REQUIRED)
ELSE(WITH_SEGMENTATION)
MESSAGE(STATUS "Without segmentation")
ENDIF(WITH_SEGMENTATION)
## RivLib
OPT_DEP(WITH_RIVLIB "Whether the RIEGL rivlib is present ON/OFF" OFF "")
IF(WITH_RIVLIB)
MESSAGE(STATUS "Compiling a scan IO for RXP files")
include_directories(${CMAKE_SOURCE_DIR}/3rdparty)
link_directories(${CMAKE_SOURCE_DIR}/3rdparty)
SET(RIEGL_DIR ${CMAKE_SOURCE_DIR}/3rdparty/riegl/)
IF(WIN32)
SET(RIVLIB ${RIEGL_DIR}libscanlib-mt.lib ${RIEGL_DIR}libctrllib-mt.lib ${RIEGL_DIR}libboost_system-mt-1_43_0-vns.lib)
ELSE(WIN32)
SET(RIVLIB ${RIEGL_DIR}libscanlib-mt-s.a ${RIEGL_DIR}libctrllib-mt-s.a ${RIEGL_DIR}libboost_system-mt-s-1_43_0-vns.a pthread)
ENDIF(WIN32)
FIND_PACKAGE(LibXml2 )
ELSE(WITH_RIVLIB)
MESSAGE(STATUS "Do NOT compile a scan IO for RXP")
ENDIF(WITH_RIVLIB)
## CUDA support, TODO depend on CUDA_FIND
OPT_DEP(WITH_CUDA "Compile with CUDA support" OFF "")
IF(WITH_CUDA)
MESSAGE(STATUS "Compiling WITH CUDA support")
FIND_PACKAGE(CUDA)
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWITH_CUDA")
ELSE(WITH_CUDA)
MESSAGE(STATUS "Compiling WITHOUT CUDA support")
ENDIF(WITH_CUDA)
## PMD
OPT_DEP(WITH_PMD "Whether to build the PMD tools like grabVideoAnd3D calibrate etc. ON/OFF" OFF "")
IF(WITH_PMD)
FIND_PACKAGE(OpenGL REQUIRED)
MESSAGE(STATUS "With Tools")
ELSE(WITH_PMD)
MESSAGE(STATUS "Without Tools")
ENDIF(WITH_PMD)
## FBR
OPT_DEP(WITH_FBR "Whether to compile feature based registration. ON/OFF" OFF "")
IF(WITH_FBR)
MESSAGE(STATUS "With FBR ")
ELSE(WITH_FBR)
MESSAGE(STATUS "Without FBR")
ENDIF(WITH_FBR)
# OPEN
FIND_PACKAGE(OpenMP)
IF(OPENMP_FOUND)
OPT_DEP(WITH_OPENMP "Whether to use parallel processing capabilities of OPENMP. ON/OFF" ON "")
ENDIF(OPENMP_FOUND)
IF(OPENMP_FOUND AND WITH_OPENMP)
MESSAGE(STATUS "With OpenMP ")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMAX_OPENMP_NUM_THREADS=${NUMBER_OF_CPUS} -DOPENMP_NUM_THREADS=${NUMBER_OF_CPUS} ${OpenMP_CXX_FLAGS} -DOPENMP")
ELSE(OPENMP_FOUND AND WITH_OPENMP)
MESSAGE(STATUS "Without OpenMP")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMAX_OPENMP_NUM_THREADS=1 -DOPENMP_NUM_THREADS=1")
ENDIF(OPENMP_FOUND AND WITH_OPENMP)
OPT_DEP(EXPORT_SHARED_LIBS "Whether to build additional shared libraries for use in other projects. ON/OFF" OFF "WITH_SHOW;WITH_FBR")
IF(EXPORT_SHARED_LIBS)
## Compile a single shared library containing all of 3DTK
add_library(slam SHARED src/slam6d/icp6D.cc)
target_link_libraries(slam scan_s ANN_s sparse_s newmat_s show_s fbr_s)
MESSAGE(STATUS "exporting additional libraries")
ELSE(EXPORT_SHARED_LIBS)
MESSAGE(STATUS "not exporting libraries")
ENDIF(EXPORT_SHARED_LIBS)
OPT_DEP(WITH_METRICS "Whether to use metrics in slam6d. ON/OFF" OFF "")
IF(WITH_METRICS)
MESSAGE(STATUS "With metrics in slam6d.")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWITH_METRICS")
ELSE(WITH_METRICS)
MESSAGE(STATUS "Without metrics in slam6d.")
ENDIF(WITH_METRICS)
#################################################
# OPERATING SYSTEM SPECIFIC BEHAVIOUR ##
#################################################
## Special treatment for system specifics
IF(APPLE)
add_definitions(-Dfopen64=fopen)
ENDIF(APPLE)
## Multiple Cores
IF(APPLE)
SET(PROCESSOR_COUNT 2)
ELSE(APPLE)
INCLUDE(CountProcessors)
SET(NUMBER_OF_CPUS "${PROCESSOR_COUNT}" CACHE STRING "The number of processors to use (default: ${PROCESSOR_COUNT})" )
ENDIF(APPLE)
IF(WIN32)
SET(ADDITIONAL_CFLAGS "-O2" CACHE STRING "Additional flags given to the compiler ( -O2)" )
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/windows/)
link_directories(${CMAKE_SOURCE_DIR}/3rdparty/windows)
link_directories(${CMAKE_SOURCE_DIR}/3rdparty/windows/x64)
add_library(XGetopt STATIC ${CMAKE_SOURCE_DIR}/3rdparty/windows/XGetopt.cpp)
SET(CMAKE_STATIC_LIBRARY_SUFFIX "32.lib")
ELSE(WIN32)
SET(ADDITIONAL_CFLAGS "-O3 -std=c++0x -msse3 -Wall -finline-functions -Wno-unused-but-set-variable -Wno-write-strings -Wno-char-subscripts -Wno-unused-result" CACHE STRING"Additional flags given to the compiler (-O3 -Wall -finline-functions -Wno-write-strings)" )
# Add include path for OpenGL without GL/-prefix
# to avoid the include incompatibility between MACOS
# and linux
FIND_PATH(OPENGL_INC gl.h /usr/include/GL)
include_directories(${OPENGL_INC})
ENDIF(WIN32)
# Add OpenGL includes for MACOS if needed
# The OSX OpenGL frameworks natively supports freeglut extensions
IF(APPLE)
include_directories(/System/Library/Frameworks/GLUT.framework/Headers)
include_directories(/System/Library/Frameworks/OpenGL.framework/Headers)
ENDIF(APPLE)
# hack to "circumvent" Debug and Release folders that are created under visual studio
# this is why the INSTALL target has to be used in visual studio
IF(MSVC)
INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/bin/Release/ CONFIGURATIONS Release DESTINATION ${CMAKE_SOURCE_DIR}/windows FILES_MATCHING PATTERN "*.dll" PATTERN "*.exe")
IF( CMAKE_SIZEOF_VOID_P EQUAL 8 )
INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/3rdparty/windows/x64/ CONFIGURATIONS Release DESTINATION ${CMAKE_SOURCE_DIR}/windows FILES_MATCHING PATTERN "*.dll" PATTERN "*.exe")
ELSE( CMAKE_SIZEOF_VOID_P EQUAL 8 )
INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/3rdparty/windows/ CONFIGURATIONS Release DESTINATION ${CMAKE_SOURCE_DIR}/windows FILES_MATCHING PATTERN "*.dll" PATTERN "*.exe")
ENDIF(CMAKE_SIZEOF_VOID_P EQUAL 8 )
INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/bin/Debug/ CONFIGURATIONS Debug DESTINATION ${CMAKE_SOURCE_DIR}/windows FILES_MATCHING PATTERN "*.dll" PATTERN "*.exe")
IF( CMAKE_SIZEOF_VOID_P EQUAL 8 )
INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/3rdparty/windows/x64/ CONFIGURATIONS Debug DESTINATION ${CMAKE_SOURCE_DIR}/windows FILES_MATCHING PATTERN "*.dll" PATTERN "*.exe")
ELSE( CMAKE_SIZEOF_VOID_P EQUAL 8 )
INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/3rdparty/windows/ CONFIGURATIONS Debug DESTINATION ${CMAKE_SOURCE_DIR}/windows FILES_MATCHING PATTERN "*.dll" PATTERN "*.exe")
ENDIF(CMAKE_SIZEOF_VOID_P EQUAL 8 )
ENDIF(MSVC)
#################################################
# GENERAL PROJECT SETTINGS ##
#################################################
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ADDITIONAL_CFLAGS}")
# Hide CMake variables
SET (CMAKE_INSTALL_PREFIX "/usr/local" CACHE INTERNAL "" FORCE)
SET (CMAKE_BUILD_TYPE "" CACHE INTERNAL "" FORCE)
# Set output directories for libraries and executables
SET( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib )
SET( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/obj )
SET( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin )
# Set include and link dirs ...
include_directories(${CMAKE_SOURCE_DIR}/include)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/glui)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/wxthings/include/)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/ann_1.1.1_modified/include)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/ann_1.1.1_modified/src)
link_directories(${CMAKE_SOURCE_DIR}/obj)
link_directories(${CMAKE_SOURCE_DIR}/lib)
add_subdirectory(3rdparty)
add_subdirectory(src/slam6d)
add_subdirectory(src/scanio)
add_subdirectory(src/scanserver)
add_subdirectory(src/segmentation)
add_subdirectory(src/normals)
add_subdirectory(src/veloslam)
add_subdirectory(src/show)
add_subdirectory(src/grid)
add_subdirectory(src/pmd)
add_subdirectory(src/shapes)
add_subdirectory(src/thermo)
add_subdirectory(src/slam6d/fbr)
add_subdirectory(src/scanner)
add_subdirectory(src/model)
MESSAGE (STATUS "Build environment is set up!")

View file

@ -0,0 +1,610 @@
/**
*
* Copyright (C) Jacobs University Bremen
*
* @author Vaibhav Kumar Mehta
* @author Corneliu Claudiu Prodescu
* @file normals.cc
*/
#include <vector>
#include <ANN/ANN.h>
#include "slam6d/io_types.h"
#include "slam6d/globals.icc"
#include "slam6d/scan.h"
#include "slam6d/fbr/panorama.h"
#include "slam6d/kd.h"
#include <scanserver/clientInterface.h>
#include "newmat/newmat.h"
#include "newmat/newmatap.h"
#include "normals/normals.h"
using namespace NEWMAT;
using namespace std;
//////////////////////////////////////////////////////
/////////////NORMALS USING AKNN METHOD ////////////////
///////////////////////////////////////////////////////
void calculateNormalsApxKNN(vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3],
double eps)
{
cout<<"Total number of points: "<<points.size()<<endl;
int nr_neighbors = k;
ColumnVector rPos(3);
for (int i = 0; i < 3; ++i)
rPos(i+1) = _rPos[i];
ANNpointArray pa = annAllocPts(points.size(), 3);
for (size_t i=0; i<points.size(); ++i)
{
pa[i][0] = points[i].x;
pa[i][1] = points[i].y;
pa[i][2] = points[i].z;
}
ANNkd_tree t(pa, points.size(), 3);
ANNidxArray nidx = new ANNidx[nr_neighbors];
ANNdistArray d = new ANNdist[nr_neighbors];
for (size_t i=0; i<points.size(); ++i)
{
ANNpoint p = pa[i];
//ANN search for k nearest neighbors
//indexes of the neighbors along with the query point
//stored in the array n
t.annkSearch(p, nr_neighbors, nidx, d, eps);
Point mean(0.0,0.0,0.0);
Matrix X(nr_neighbors,3);
SymmetricMatrix A(3);
Matrix U(3,3);
DiagonalMatrix D(3);
//calculate mean for all the points
for (int j=0; j<nr_neighbors; ++j)
{
mean.x += points[nidx[j]].x;
mean.y += points[nidx[j]].y;
mean.z += points[nidx[j]].z;
}
mean.x /= nr_neighbors;
mean.y /= nr_neighbors;
mean.z /= nr_neighbors;
//calculate covariance = A for all the points
for (int i = 0; i < nr_neighbors; ++i) {
X(i+1, 1) = points[nidx[i]].x - mean.x;
X(i+1, 2) = points[nidx[i]].y - mean.y;
X(i+1, 3) = points[nidx[i]].z - mean.z;
}
A << 1.0/nr_neighbors * X.t() * X;
EigenValues(A, D, U);
//normal = eigenvector corresponding to lowest
//eigen value that is the 1st column of matrix U
ColumnVector n(3);
n(1) = U(1,1);
n(2) = U(2,1);
n(3) = U(3,1);
ColumnVector point_vector(3);
point_vector(1) = p[0] - rPos(1);
point_vector(2) = p[1] - rPos(2);
point_vector(3) = p[2] - rPos(3);
point_vector = point_vector / point_vector.NormFrobenius();
Real angle = (n.t() * point_vector).AsScalar();
if (angle < 0) {
n *= -1.0;
}
n = n / n.NormFrobenius();
normals.push_back(Point(n(1), n(2), n(3)));
}
delete[] nidx;
delete[] d;
annDeallocPts(pa);
}
////////////////////////////////////////////////////////////////
/////////////NORMALS USING ADAPTIVE AKNN METHOD ////////////////
////////////////////////////////////////////////////////////////
void calculateNormalsAdaptiveApxKNN(vector<Point> &normals,
vector<Point> &points,
int kmin,
int kmax,
const double _rPos[3],
double eps)
{
ColumnVector rPos(3);
for (int i = 0; i < 3; ++i)
rPos(i+1) = _rPos[i];
cout<<"Total number of points: "<<points.size()<<endl;
int nr_neighbors;
ANNpointArray pa = annAllocPts(points.size(), 3);
for (size_t i=0; i<points.size(); ++i)
{
pa[i][0] = points[i].x;
pa[i][1] = points[i].y;
pa[i][2] = points[i].z;
}
ANNkd_tree t(pa, points.size(), 3);
Point mean(0.0,0.0,0.0);
double e1,e2,e3;
for (size_t i=0; i<points.size(); ++i)
{
Matrix U(3,3);
ANNpoint p = pa[i];
for(int kidx = kmin; kidx < kmax; kidx++)
{
nr_neighbors=kidx+1;
ANNidxArray nidx = new ANNidx[nr_neighbors];
ANNdistArray d = new ANNdist[nr_neighbors];
//ANN search for k nearest neighbors
//indexes of the neighbors along with the query point
//stored in the array n
t.annkSearch(p, nr_neighbors, nidx, d, eps);
mean.x=0,mean.y=0,mean.z=0;
//calculate mean for all the points
for (int j=0; j<nr_neighbors; ++j)
{
mean.x += points[nidx[j]].x;
mean.y += points[nidx[j]].y;
mean.z += points[nidx[j]].z;
}
mean.x /= nr_neighbors;
mean.y /= nr_neighbors;
mean.z /= nr_neighbors;
Matrix X(nr_neighbors,3);
SymmetricMatrix A(3);
DiagonalMatrix D(3);
//calculate covariance = A for all the points
for (int j = 0; j < nr_neighbors; ++j) {
X(j+1, 1) = points[nidx[j]].x - mean.x;
X(j+1, 2) = points[nidx[j]].y - mean.y;
X(j+1, 3) = points[nidx[j]].z - mean.z;
}
A << 1.0/nr_neighbors * X.t() * X;
EigenValues(A, D, U);
e1 = D(1);
e2 = D(2);
e3 = D(3);
delete[] nidx;
delete[] d;
//We take the particular k if the second maximum eigen value
//is at least 25 percent of the maximum eigen value
if ((e1 > 0.25 * e2) && (fabs(1.0 - (double)e2/(double)e3) < 0.25))
break;
}
//normal = eigenvector corresponding to lowest
//eigen value that is the 1rd column of matrix U
ColumnVector n(3);
n(1) = U(1,1);
n(2) = U(2,1);
n(3) = U(3,1);
ColumnVector point_vector(3);
point_vector(1) = p[0] - rPos(1);
point_vector(2) = p[1] - rPos(2);
point_vector(3) = p[2] - rPos(3);
point_vector = point_vector / point_vector.NormFrobenius();
Real angle = (n.t() * point_vector).AsScalar();
if (angle < 0) {
n *= -1.0;
}
n = n / n.NormFrobenius();
normals.push_back(Point(n(1), n(2), n(3)));
}
annDeallocPts(pa);
}
///////////////////////////////////////////////////////
/////////////NORMALS USING AKNN METHOD ////////////////
///////////////////////////////////////////////////////
void calculateNormalsKNN(vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3] )
{
cout<<"Total number of points: "<<points.size()<<endl;
int nr_neighbors = k;
ColumnVector rPos(3);
for (int i = 0; i < 3; ++i)
rPos(i+1) = _rPos[i];
double** pa = new double*[points.size()];
for (size_t i = 0; i < points.size(); ++i)
{
pa[i] = new double[3];
pa[i][0] = points[i].x;
pa[i][1] = points[i].y;
pa[i][2] = points[i].z;
}
KDtree t(pa, points.size());
for (size_t i=0; i<points.size(); ++i)
{
double p[3] = {pa[i][0], pa[i][1], pa[i][2]};
//ANN search for k nearest neighbors
//indexes of the neighbors along with the query point
//stored in the array n
vector<Point> temp = t.kNearestNeighbors(p,
nr_neighbors,
numeric_limits<double>::max());
nr_neighbors = temp.size();
Point mean(0.0,0.0,0.0);
Matrix X(nr_neighbors,3);
SymmetricMatrix A(3);
Matrix U(3,3);
DiagonalMatrix D(3);
//calculate mean for all the points
for (int j = 0; j < nr_neighbors; ++j)
{
mean.x += temp[j].x;
mean.y += temp[j].y;
mean.z += temp[j].z;
}
mean.x /= nr_neighbors;
mean.y /= nr_neighbors;
mean.z /= nr_neighbors;
//calculate covariance = A for all the points
for (int i = 0; i < nr_neighbors; ++i) {
X(i+1, 1) = temp[i].x - mean.x;
X(i+1, 2) = temp[i].y - mean.y;
X(i+1, 3) = temp[i].z - mean.z;
}
A << 1.0/nr_neighbors * X.t() * X;
EigenValues(A, D, U);
//normal = eigenvector corresponding to lowest
//eigen value that is the 1st column of matrix U
ColumnVector n(3);
n(1) = U(1,1);
n(2) = U(2,1);
n(3) = U(3,1);
ColumnVector point_vector(3);
point_vector(1) = p[0] - rPos(1);
point_vector(2) = p[1] - rPos(2);
point_vector(3) = p[2] - rPos(3);
point_vector = point_vector / point_vector.NormFrobenius();
Real angle = (n.t() * point_vector).AsScalar();
if (angle < 0) {
n *= -1.0;
}
n = n / n.NormFrobenius();
normals.push_back(Point(n(1), n(2), n(3)));
}
for (size_t i = 0; i < points.size(); ++i)
{
delete[] pa[i];
}
delete[] pa;
}
////////////////////////////////////////////////////////////////
/////////////NORMALS USING ADAPTIVE AKNN METHOD ////////////////
////////////////////////////////////////////////////////////////
void calculateNormalsAdaptiveKNN(vector<Point> &normals,
vector<Point> &points,
int kmin,
int kmax,
const double _rPos[3])
{
ColumnVector rPos(3);
for (int i = 0; i < 3; ++i)
rPos(i+1) = _rPos[i];
cout<<"Total number of points: "<<points.size()<<endl;
int nr_neighbors;
double** pa = new double*[points.size()];
for (size_t i = 0; i < points.size(); ++i)
{
pa[i] = new double[3];
pa[i][0] = points[i].x;
pa[i][1] = points[i].y;
pa[i][2] = points[i].z;
}
KDtree t(pa, points.size());
Point mean(0.0,0.0,0.0);
double e1,e2,e3;
for (size_t i=0; i<points.size(); ++i)
{
Matrix U(3,3);
double p[3] = {pa[i][0], pa[i][1], pa[i][2]};
for(int kidx = kmin; kidx < kmax; kidx++)
{
nr_neighbors=kidx+1;
//ANN search for k nearest neighbors
//indexes of the neighbors along with the query point
//stored in the array n
vector<Point> temp = t.kNearestNeighbors(p,
nr_neighbors,
numeric_limits<double>::max());
nr_neighbors = temp.size();
mean.x=0,mean.y=0,mean.z=0;
//calculate mean for all the points
for (int j=0; j<nr_neighbors; ++j)
{
mean.x += temp[j].x;
mean.y += temp[j].y;
mean.z += temp[j].z;
}
mean.x /= nr_neighbors;
mean.y /= nr_neighbors;
mean.z /= nr_neighbors;
Matrix X(nr_neighbors,3);
SymmetricMatrix A(3);
DiagonalMatrix D(3);
//calculate covariance = A for all the points
for (int j = 0; j < nr_neighbors; ++j) {
X(j+1, 1) = temp[j].x - mean.x;
X(j+1, 2) = temp[j].y - mean.y;
X(j+1, 3) = temp[j].z - mean.z;
}
A << 1.0/nr_neighbors * X.t() * X;
EigenValues(A, D, U);
e1 = D(1);
e2 = D(2);
e3 = D(3);
//We take the particular k if the second maximum eigen value
//is at least 25 percent of the maximum eigen value
if ((e1 > 0.25 * e2) && (fabs(1.0 - (double)e2/(double)e3) < 0.25))
break;
}
//normal = eigenvector corresponding to lowest
//eigen value that is the 1rd column of matrix U
ColumnVector n(3);
n(1) = U(1,1);
n(2) = U(2,1);
n(3) = U(3,1);
ColumnVector point_vector(3);
point_vector(1) = p[0] - rPos(1);
point_vector(2) = p[1] - rPos(2);
point_vector(3) = p[2] - rPos(3);
point_vector = point_vector / point_vector.NormFrobenius();
Real angle = (n.t() * point_vector).AsScalar();
if (angle < 0) {
n *= -1.0;
}
n = n / n.NormFrobenius();
normals.push_back(Point(n(1), n(2), n(3)));
}
for (size_t i = 0; i < points.size(); ++i)
{
delete[] pa[i];
}
delete[] pa;
}
///////////////////////////////////////////////////////
/////////////NORMALS USING IMAGE NEIGHBORS ////////////
///////////////////////////////////////////////////////
void calculateNormalsPANORAMA(vector<Point> &normals,
vector<Point> &points,
vector< vector< vector< cv::Vec3f > > > extendedMap,
const double _rPos[3])
{
ColumnVector rPos(3);
for (int i = 0; i < 3; ++i)
rPos(i+1) = _rPos[i];
cout<<"Total number of points: "<<points.size()<<endl;
points.clear();
int nr_neighbors = 0;
cout << "height of Image: "<<extendedMap.size()<<endl;
cout << "width of Image: "<<extendedMap[0].size()<<endl;
// as the nearest neighbors and then the same PCA method as done in AKNN
//temporary dynamic array for all the neighbors of a given point
vector<cv::Vec3f> neighbors;
for (size_t i=0; i< extendedMap.size(); i++)
{
for (size_t j=0; j<extendedMap[i].size(); j++)
{
if (extendedMap[i][j].size() == 0) continue;
neighbors.clear();
Point mean(0.0,0.0,0.0);
// Offset for neighbor computation
int offset[2][5] = {{-1,0,1,0,0},{0,-1,0,1,0}};
// Traversing all the cells in the extended map
for (int n = 0; n < 5; ++n) {
int x = i + offset[0][n];
int y = j + offset[1][n];
// Copy the neighboring buckets into the vector
if (x >= 0 && x < (int)extendedMap.size() &&
y >= 0 && y < (int)extendedMap[x].size()) {
for (unsigned int k = 0; k < extendedMap[x][y].size(); k++) {
neighbors.push_back(extendedMap[x][y][k]);
}
}
}
nr_neighbors = neighbors.size();
cv::Vec3f p = extendedMap[i][j][0];
//if no neighbor point is found in the 4-neighboring pixels then normal is set to zero
if (nr_neighbors < 3)
{
points.push_back(Point(p[0], p[1], p[2]));
normals.push_back(Point(0.0,0.0,0.0));
continue;
}
//calculate mean for all the points
Matrix X(nr_neighbors,3);
SymmetricMatrix A(3);
Matrix U(3,3);
DiagonalMatrix D(3);
//calculate mean for all the points
for(int k = 0; k < nr_neighbors; k++)
{
cv::Vec3f pp = neighbors[k];
mean.x += pp[0];
mean.y += pp[1];
mean.z += pp[2];
}
mean.x /= nr_neighbors;
mean.y /= nr_neighbors;
mean.z /= nr_neighbors;
//calculate covariance = A for all the points
for (int n = 0; n < nr_neighbors; ++n) {
cv::Vec3f pp = neighbors[n];
X(n+1, 1) = pp[0] - mean.x;
X(n+1, 2) = pp[1] - mean.y;
X(n+1, 3) = pp[2] - mean.z;
}
A << 1.0/nr_neighbors * X.t() * X;
EigenValues(A, D, U);
//normal = eigenvector corresponding to lowest
//eigen value that is the 1st column of matrix U
ColumnVector n(3);
n(1) = U(1,1);
n(2) = U(2,1);
n(3) = U(3,1);
ColumnVector point_vector(3);
point_vector(1) = p[0] - rPos(1);
point_vector(2) = p[1] - rPos(2);
point_vector(3) = p[2] - rPos(3);
point_vector = point_vector / point_vector.NormFrobenius();
Real angle = (n.t() * point_vector).AsScalar();
if (angle < 0) {
n *= -1.0;
}
n = n / n.NormFrobenius();
for (unsigned int k = 0; k < extendedMap[i][j].size(); k++) {
cv::Vec3f p = extendedMap[i][j][k];
points.push_back(Point(p[0], p[1], p[2]));
normals.push_back(Point(n(1), n(2), n(3)));
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
///////////FAST NORMALS USING PANORAMA EQUIRECTANGULAR RANGE IMAGE //////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
/*
void calculateNormalsFAST(vector<Point> &normals,vector<Point> &points,cv::Mat &img,vector<vector<vector<cv::Vec3f>>> extendedMap)
{
cout<<"Total number of points: "<<points.size()<<endl;
points.clear();
int nr_points = 0;
//int nr_neighbors = 0,nr_neighbors_center = 0;
cout << "height of Image: "<<extendedMap.size()<<endl;
cout << "width of Image: "<<extendedMap[0].size()<<endl;
for (size_t i=0; i< extendedMap.size(); ++i)
{
for (size_t j=0; j<extendedMap[0].size(); j++)
{
double theta,phi,rho;
double x,y,z;
double dRdTheta,dRdPhi;
double n[3],m;
nr_points = extendedMap[i][j].size();
if (nr_points == 0 ) continue;
for (int k = 0; k< nr_points; k++)
{
cv::Vec3f p = extendedMap[i][j][k];
x = p[0];
y = p[1];
z = p[2];
rho = sqrt(x*x + y*y + z*z);
theta = atan(y/x);
phi = atan(z/x);
//Sobel Filter for the derivative
dRdTheta = dRdPhi = 0.0;
if (i == 0 || i == extendedMap.size()-1 || j == 0 || j == extendedMap[0].size()-1)
{
points.push_back(Point(x, y, z));
normals.push_back(Point(0.0,0.0,0.0));
continue;
}
dRdPhi += 10*img.at<uchar>(i-1,j);
dRdPhi += 3 *img.at<uchar>(i-1,j-1);
dRdPhi += 3 *img.at<uchar>(i-1,j+1);
dRdPhi -= 10*img.at<uchar>(i+1,j);
dRdPhi -= 3 *img.at<uchar>(i+1,j-1);
dRdPhi -= 3 *img.at<uchar>(i+1,j+1);
dRdTheta += 10*img.at<uchar>(i,j-1);
dRdTheta += 3 *img.at<uchar>(i-1,j-1);
dRdTheta += 3 *img.at<uchar>(i+1,j-1);
dRdTheta -= 10*img.at<uchar>(i,j+1);
dRdTheta -= 3 *img.at<uchar>(i-1,j+1);
dRdTheta -= 3 *img.at<uchar>(i+1,j+1);
n[0] = cos(theta) * sin(phi) - sin(theta) * dRdTheta / rho / sin(phi) +
cos(theta) * cos(phi) * dRdPhi / rho;
n[1] = sin(theta) * sin(phi) + cos(theta) * dRdTheta / rho / sin(phi) +
sin(theta) * cos(phi) * dRdPhi / rho;
n[2] = cos(phi) - sin(phi) * dRdPhi / rho;
//n[2] = -n[2];
m = sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);
n[0] /= m; n[1] /= m; n[2] /= m;
points.push_back(Point(x, y, z));
normals.push_back(Point(n[0],n[1],n[2]));
}
}
}
}
*/

View file

@ -0,0 +1,64 @@
This file describes the scanserver functionality, the code changes and its behaviour.
To run with the scanserver functionality, pass -S or --scanserver to the slam6D/show call. Start the scanserver with bin/scanserver & first. If you want to directly jump to usage examples, see the "USAGE" section below.
The scanserver is a new method to load and manage scans for 'slam6D', 'show' and some few other tools (so far). It removes all the IO code from the clients and handles it in the server process. This separation offers persistence of scan data and avoids unneccessary reloads of full scans or even reduced versions thereof. By using a caching framework it also transparently handles the available memory given and enables (nearly) endless amounts of data. The client is only required to open the interface, load a directory and start working on those scans without having to alter its workflow (e.g., pre-reduce them) to accomodate huge data volumes.
If you have questions or problems (or both), contact Thomas Escher <tescher@uos.de>.
USAGE:
1. General
Start the scanserver once (in another terminal, or in the same one as a background process):
bin/scanserver &
Do all the normal work as you would normally do, adding the parameter -S:
bin/slam6D dat -S
bin/show dat -S
2. Changing the available memory size
Changing the cache memory size used by scan data (about half the system memory usually works):
bin/scanserver -c 3500 (for 8GB RAM)
If you intend to not reload the full scans for different reduction parameters or don't have too much memory/disk space, disable binary scan caching. Binary scan caching saves the full scans as long as the range or height parameters aren't touched, which would cause a full reload:
bin/scanserver -b 0
If your dataset contains many scans and loops (e.g., 'hannover' with 468 scans), the default data memory (150M) won't be enough to hold all the animation frames and you need to increase it:
bin/scanserver -d 250
3. Altering the shared memory on your linux system (bus_error)
If you receive a bus_error, the size of your shared memory is too small and the requested allocation was too big. This is resolved via remounting your shm device. Default is half of the available RAM. This limit can be increased to nearly 90% of the RAM if required.
sudo mount -o remount,size=7000M /dev/shm (for 8GB RAM)
4. Locking the memory to avoid swapping (Linux only)
If a great portion of the RAM is used for the cache data, swapping will usually occur after 50% of usage. To avoid this, the scanserver tries to lock the whole memory in place. This will fail without superuser rights, as well as on a full shared memory (see 3.) even with rights. To solve this problem, add these two additional lines to '/etc/security/limits.conf':
* soft memlock unlimited
* hard memlock unlimited
After adding these lines and rebooting the system the scanserver can be started without superuser rights.
5. Using the octtree serialization feature in show with scanserver
The octtree serialization behaves slightly different than before. Since the scanserver caches octtrees between calls of 'show', the loading of octtrees only becomes relevant if no octtrees are in the cache and have to be created from the scan itself. If this has been done once before and the octtrees have been saved via --saveOct before this can be used to speed up the octtree loading with --loadOct.
bin/show dat --loadOct --saveOct
If octtrees are not cached, they are deserialized if available, created otherwise and then saved for future calls.
IMPLEMENTATION STATUS:
Currently only 'slam6D' and 'show' are working with the scanserver.
Since the scanserver handles the disk IO now and the filtering has been optimized, not all ScanIOs are updated yet. Just copy and paste and change the minor parts about reading the input lines.
Working: 'ls src/scanio' in a shell

Binary file not shown.

View file

@ -3,8 +3,6 @@ SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/3rdparty/CMakeModules" ${CMAKE_MODULE
project (3DTK) project (3DTK)
#include_directories(OPENGL_INCLUDE_DIR) #include_directories(OPENGL_INCLUDE_DIR)
IF(WIN32) IF(WIN32)
set(Boost_USE_STATIC_LIBS TRUE) set(Boost_USE_STATIC_LIBS TRUE)
@ -15,9 +13,9 @@ ENDIF(WIN32)
SET(Boost_ADDITIONAL_VERSIONS "1.42" "1.42.0" "1.44" "1.44.0" "1.45.0" "1.45" "1.46" "1.46.1" "1.47.0" "1.47" "1.48" "1.49") SET(Boost_ADDITIONAL_VERSIONS "1.42" "1.42.0" "1.44" "1.44.0" "1.45.0" "1.45" "1.46" "1.46.1" "1.47.0" "1.47" "1.48" "1.49")
IF(WIN32) IF(WIN32)
# for some unknown reason no one variant works on all windows platforms # for some unknown reason no one variant works on all windows platforms
find_package( Boost COMPONENTS serialization graph regex filesystem system thread date_time REQUIRED) find_package( Boost COMPONENTS serialization graph regex filesystem system thread date_time program_options REQUIRED)
ELSE(WIN32) ELSE(WIN32)
find_package( Boost COMPONENTS serialization graph regex filesystem system thread date_time REQUIRED) find_package( Boost COMPONENTS serialization graph regex filesystem system thread date_time program_options REQUIRED)
ENDIF(WIN32) ENDIF(WIN32)
if(Boost_FOUND) if(Boost_FOUND)
@ -26,6 +24,10 @@ if(Boost_FOUND)
add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS}) add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})
endif() endif()
FIND_PACKAGE(OpenCV REQUIRED)
include("3rdparty/CMakeModules/OpenCV.cmake")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ADDITIONAL_OPENCV_FLAGS}")
################################################# #################################################
# Declare Options and modify build accordingly ## # Declare Options and modify build accordingly ##
################################################# #################################################
@ -155,10 +157,6 @@ endif(WITH_MODEL)
## Thermo ## Thermo
OPT_DEP(WITH_THERMO "Whether to build executables for mutual calibration of laser scanner and camera. ON/OFF" OFF "WITH_SHAPE_DETECTION") OPT_DEP(WITH_THERMO "Whether to build executables for mutual calibration of laser scanner and camera. ON/OFF" OFF "WITH_SHAPE_DETECTION")
IF(WITH_THERMO) IF(WITH_THERMO)
#for OpenCV 2.1
FIND_PACKAGE(OpenCV REQUIRED)
include("3rdparty/CMakeModules/OpenCV.cmake")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ADDITIONAL_OPENCV_FLAGS}")
add_subdirectory(3rdparty/cvblob) add_subdirectory(3rdparty/cvblob)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob) include_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob)
link_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob) link_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob)
@ -237,16 +235,6 @@ ELSE(WITH_SEGMENTATION)
MESSAGE(STATUS "Without segmentation") MESSAGE(STATUS "Without segmentation")
ENDIF(WITH_SEGMENTATION) ENDIF(WITH_SEGMENTATION)
## Normals
OPT_DEP(WITH_NORMALS "Whether to build program for normal computation ON/OFF" OFF "WITH_FBR")
IF(WITH_NORMALS)
MESSAGE(STATUS "With normals")
ELSE(WITH_NORMALS)
MESSAGE(STATUS "Without normals")
ENDIF(WITH_NORMALS)
## RivLib ## RivLib
OPT_DEP(WITH_RIVLIB "Whether the RIEGL rivlib is present ON/OFF" OFF "") OPT_DEP(WITH_RIVLIB "Whether the RIEGL rivlib is present ON/OFF" OFF "")
@ -290,9 +278,6 @@ ENDIF(WITH_PMD)
OPT_DEP(WITH_FBR "Whether to compile feature based registration. ON/OFF" OFF "") OPT_DEP(WITH_FBR "Whether to compile feature based registration. ON/OFF" OFF "")
IF(WITH_FBR) IF(WITH_FBR)
FIND_PACKAGE(OpenCV REQUIRED)
include("3rdparty/CMakeModules/OpenCV.cmake")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${ADDITIONAL_OPENCV_FLAGS}")
MESSAGE(STATUS "With FBR ") MESSAGE(STATUS "With FBR ")
ELSE(WITH_FBR) ELSE(WITH_FBR)
MESSAGE(STATUS "Without FBR") MESSAGE(STATUS "Without FBR")

View file

@ -41,7 +41,7 @@ If you receive a bus_error, the size of your shared memory is too small and the
4. Locking the memory to avoid swapping (Linux only) 4. Locking the memory to avoid swapping (Linux only)
If a great portion of the RAM is used for the cache data, swapping will usually occur after 50% of usage. To avoid this, the scanserver tries to lock the whole memory in place. This will fail without superuser rights, as well as on a full shared memory (see 3.) even with rights. Add these two additional lines to '/etc/security/limits.conf': If a great portion of the RAM is used for the cache data, swapping will usually occur after 50% of usage. To avoid this, the scanserver tries to lock the whole memory in place. This will fail without superuser rights, as well as on a full shared memory (see 3.) even with rights. To solve this problem, add these two additional lines to '/etc/security/limits.conf':
* soft memlock unlimited * soft memlock unlimited
* hard memlock unlimited * hard memlock unlimited

155
include/normals/normals.h Normal file
View file

@ -0,0 +1,155 @@
#ifndef NORMALS_H
#define NORMALS_H
#include <vector>
#include <slam6d/scan.h>
#if (CV_MAJOR_VERSION == 2) && (CV_MINOR_VERSION < 2)
#include <opencv/cv.h>
#include <opencv/highgui.h>
#else
#include <opencv2/opencv.hpp>
#endif
void calculateNormalsApxKNN(std::vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3],
double eps = 0.0);
void calculateNormalsAdaptiveApxKNN(std::vector<Point> &normals,
vector<Point> &points,
int kmin,
int kmax,
const double _rPos[3],
double eps = 0.0);
void calculateNormalsKNN(std::vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3] );
void calculateNormalsAdaptiveKNN(vector<Point> &normals,
vector<Point> &points,
int kmin, int kmax,
const double _rPos[3]);
void calculateNormalsPANORAMA(vector<Point> &normals,
vector<Point> &points,
vector< vector< vector< cv::Vec3f > > > extendedMap,
const double _rPos[3]);
// TODO should be exported to separate library
/*
* retrieve a cv::Mat with x,y,z,r from a scan object
* functionality borrowed from scan_cv::convertScanToMat but this function
* does not allow a scanserver to be used, prints to stdout and can only
* handle a single scan
*/
static inline cv::Mat scan2mat(Scan *source)
{
DataXYZ xyz = source->get("xyz");
DataReflectance xyz_reflectance = source->get("reflectance");
unsigned int nPoints = xyz.size();
cv::Mat scan(nPoints,1,CV_32FC(4));
scan = cv::Scalar::all(0);
cv::MatIterator_<cv::Vec4f> it;
it = scan.begin<cv::Vec4f>();
for(unsigned int i = 0; i < nPoints; i++){
float x, y, z, reflectance;
x = xyz[i][0];
y = xyz[i][1];
z = xyz[i][2];
if(xyz_reflectance.size() != 0)
{
reflectance = xyz_reflectance[i];
//normalize the reflectance
reflectance += 32;
reflectance /= 64;
reflectance -= 0.2;
reflectance /= 0.3;
if (reflectance < 0) reflectance = 0;
if (reflectance > 1) reflectance = 1;
}
(*it)[0] = x;
(*it)[1] = y;
(*it)[2] = z;
if(xyz_reflectance.size() != 0)
(*it)[3] = reflectance;
else
(*it)[3] = 0;
++it;
}
return scan;
}
// TODO should be exported to separate library
/*
* convert a matrix of float values (range image) to a matrix of unsigned
* eight bit characters using different techniques
*/
static inline cv::Mat float2uchar(cv::Mat &source, bool logarithm, float cutoff)
{
cv::Mat result(source.size(), CV_8U, cv::Scalar::all(0));
float max = 0;
// find maximum value
if (cutoff == 0.0) {
// without cutoff, just iterate through all values to find the largest
for (cv::MatIterator_<float> it = source.begin<float>();
it != source.end<float>(); ++it) {
float val = *it;
if (val > max) {
max = val;
}
}
} else {
// when a cutoff is specified, sort all the points by value and then
// specify the max so that <cutoff> values are larger than it
vector<float> sorted(source.cols*source.rows);
int i = 0;
for (cv::MatIterator_<float> it = source.begin<float>();
it != source.end<float>(); ++it, ++i) {
sorted[i] = *it;
}
std::sort(sorted.begin(), sorted.end());
max = sorted[(int)(source.cols*source.rows*(1.0-cutoff))];
cout << "A cutoff of " << cutoff << " resulted in a max value of " << max << endl;
}
cv::MatIterator_<float> src = source.begin<float>();
cv::MatIterator_<uchar> dst = result.begin<uchar>();
cv::MatIterator_<float> end = source.end<float>();
if (logarithm) {
// stretch values from 0 to max logarithmically over 0 to 255
// using the logarithm allows to represent smaller values with more
// precision and larger values with less
max = log(max+1);
for (; src != end; ++src, ++dst) {
float val = (log(*src+1)*255.0)/max;
if (val > 255)
*dst = 255;
else
*dst = (uchar)val;
}
} else {
// stretch values from 0 to max linearly over 0 to 255
for (; src != end; ++src, ++dst) {
float val = (*src*255.0)/max;
if (val > 255)
*dst = 255;
else
*dst = (uchar)val;
}
}
return result;
}
#endif // NORMALS_H

View file

@ -0,0 +1,39 @@
/**
* @file
* @brief IO of a 3D scan given in ply format
* @author Andreas Nuechter
*/
#ifndef __SCAN_IO_PLY_H__
#define __SCAN_IO_PLY_H__
#include "scan_io.h"
/**
* @brief 3D scan loader for UOS scans
*
* The compiled class is available as shared object file
*/
class ScanIO_ply : public ScanIO {
public:
virtual std::list<std::string> readDirectory(const char* dir_path,
unsigned int start,
unsigned int end);
virtual void readPose(const char* dir_path,
const char* identifier,
double* pose);
virtual void readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation);
virtual bool supports(IODataType type);
};
#endif

View file

@ -0,0 +1,42 @@
/**
* @file scan_io_uosr.h
* @brief IO of a 3D scan in xyz file format plus an intensity
* @author Billy Okal
*/
#ifndef __SCAN_IO_XYZR_H__
#define __SCAN_IO_XYZR_H__
#include "scan_io.h"
/**
* @brief IO of a 3D scan in uos file format plus a
* reflectance/intensity/temperature value
*
* The compiled class is available as shared object file
*/
class ScanIO_xyzr : public ScanIO {
public:
virtual std::list<std::string> readDirectory(const char* dir_path,
unsigned int start,
unsigned int end);
virtual void readPose(const char* dir_path,
const char* identifier,
double* pose);
virtual void readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation);
virtual bool supports(IODataType type);
};
#endif

View file

@ -42,6 +42,7 @@ public:
protected: protected:
virtual void createSearchTreePrivate(); virtual void createSearchTreePrivate();
virtual void calcReducedOnDemandPrivate(); virtual void calcReducedOnDemandPrivate();
virtual void calcNormalsOnDemandPrivate();
virtual void addFrame(AlgoType type); virtual void addFrame(AlgoType type);
private: private:

View file

@ -217,6 +217,7 @@ private:
typedef TripleArray<double> DataXYZ; typedef TripleArray<double> DataXYZ;
typedef TripleArray<float> DataXYZFloat; typedef TripleArray<float> DataXYZFloat;
typedef TripleArray<unsigned char> DataRGB; typedef TripleArray<unsigned char> DataRGB;
typedef TripleArray<double> DataNormal;
typedef SingleArray<float> DataReflectance; typedef SingleArray<float> DataReflectance;
typedef SingleArray<float> DataTemperature; typedef SingleArray<float> DataTemperature;
typedef SingleArray<float> DataAmplitude; typedef SingleArray<float> DataAmplitude;

View file

@ -1301,6 +1301,18 @@ inline void transform3(const double *alignxf, double *point)
point[2] = z_neu + alignxf[14]; point[2] = z_neu + alignxf[14];
} }
inline void transform3normal(const double *alignxf, double *normal)
{
double x, y, z;
x = normal[0] * alignxf[0] + normal[1] * alignxf[1] + normal[2] * alignxf[2];
y = normal[0] * alignxf[4] + normal[1] * alignxf[5] + normal[2] * alignxf[6];
z = normal[0] * alignxf[8] + normal[1] * alignxf[9] + normal[2] * alignxf[10];
normal[0] = x;
normal[1] = y;
normal[2] = z;
}
inline void transform3(const double *alignxf, const double *point, double *tpoint) inline void transform3(const double *alignxf, const double *point, double *tpoint)
{ {
tpoint[0] = point[0] * alignxf[0] + point[1] * alignxf[4] + point[2] * alignxf[8] + alignxf[12]; tpoint[0] = point[0] * alignxf[0] + point[1] * alignxf[4] + point[2] * alignxf[8] + alignxf[12];
@ -1308,6 +1320,28 @@ inline void transform3(const double *alignxf, const double *point, double *tpoin
tpoint[2] = point[0] * alignxf[2] + point[1] * alignxf[6] + point[2] * alignxf[10] + alignxf[14]; tpoint[2] = point[0] * alignxf[2] + point[1] * alignxf[6] + point[2] * alignxf[10] + alignxf[14];
} }
inline void scal_mul3(const double *vec_in, const double scalar, double *vec_out)
{
vec_out[0] = vec_in[0] * scalar;
vec_out[1] = vec_in[1] * scalar;
vec_out[2] = vec_in[2] * scalar;
}
inline void sub3(const double *vec1_in, const double *vec2_in, double *vec_out)
{
vec_out[0] = vec1_in[0] - vec2_in[0];
vec_out[1] = vec1_in[1] - vec2_in[1];
vec_out[2] = vec1_in[2] - vec2_in[2];
}
inline void add3(const double *vec1_in, const double *vec2_in, double *vec_out)
{
vec_out[0] = vec1_in[0] + vec2_in[0];
vec_out[1] = vec1_in[1] + vec2_in[1];
vec_out[2] = vec1_in[2] + vec2_in[2];
}
inline std::string trim(const std::string& source) inline std::string trim(const std::string& source)
{ {
unsigned int start = 0, end = source.size() - 1; unsigned int start = 0, end = source.size() - 1;

View file

@ -15,6 +15,7 @@ using std::vector;
#include "slam6d/scan.h" #include "slam6d/scan.h"
#include "slam6d/icp6Dminimizer.h" #include "slam6d/icp6Dminimizer.h"
#include "slam6d/pairingMode.h"
/** /**
* @brief Representation of 3D scan matching with ICP. * @brief Representation of 3D scan matching with ICP.
@ -45,8 +46,8 @@ public:
*/ */
virtual ~icp6D() {}; virtual ~icp6D() {};
void doICP(vector <Scan *> allScans); void doICP(vector <Scan *> allScans, PairingMode pairing_mode = CLOSEST_POINT);
virtual int match(Scan* PreviousScan, Scan* CurrentScan); virtual int match(Scan* PreviousScan, Scan* CurrentScan, PairingMode pairing_mode = CLOSEST_POINT);
void covarianceEuler(Scan *scan1, Scan *scan2, NEWMAT::Matrix *C); void covarianceEuler(Scan *scan1, Scan *scan2, NEWMAT::Matrix *C);
void covarianceQuat(Scan *scan1, Scan *scan2, NEWMAT::Matrix *C); void covarianceQuat(Scan *scan1, Scan *scan2, NEWMAT::Matrix *C);
double Point_Point_Error(Scan* PreviousScan, Scan* CurrentScan, double max_dist_match, unsigned int *nrp=0); double Point_Point_Error(Scan* PreviousScan, Scan* CurrentScan, double max_dist_match, unsigned int *nrp=0);

View file

@ -38,13 +38,31 @@ struct PtrAccessor {
* capabilities (find nearest point to * capabilities (find nearest point to
* a given point, or to a ray). * a given point, or to a ray).
**/ **/
class KDtree : public SearchTree, private KDTreeImpl<Void, double*, PtrAccessor> { class KDtree : public SearchTree, private KDTreeImpl<Void, double*, PtrAccessor>
{
public: public:
KDtree(double **pts, int n); KDtree(double **pts, int n);
virtual ~KDtree(); virtual ~KDtree();
virtual double *FindClosest(double *_p, double maxdist2, int threadNum = 0) const; virtual double *FindClosest(double *_p,
double maxdist2,
int threadNum = 0) const;
virtual double *FindClosestAlongDir(double *_p,
double *_dir,
double maxdist2,
int threadNum = 0) const;
virtual vector<Point> kNearestNeighbors(double *_p,
int k,
double sqRad2,
int threadNum = 0) const;
virtual vector<Point> fixedRangeSearch(double *_p,
double sqRad2,
int threadNum = 0) const;
}; };
#endif #endif

View file

@ -55,6 +55,8 @@ public:
//! Aquires cached data first to pass on to the usual KDtree to process //! Aquires cached data first to pass on to the usual KDtree to process
virtual double* FindClosest(double *_p, double maxdist2, int threadNum = 0) const; virtual double* FindClosest(double *_p, double maxdist2, int threadNum = 0) const;
virtual double *FindClosestAlongDir(double *_p, double *_dir, double maxdist2, int threadNum = 0) const;
private: private:
Scan* m_scan; Scan* m_scan;
DataXYZ* m_data; DataXYZ* m_data;

View file

@ -62,6 +62,8 @@ public:
//! Aquires cached data first to pass on to the usual KDtree to process //! Aquires cached data first to pass on to the usual KDtree to process
virtual double* FindClosest(double *_p, double maxdist2, int threadNum = 0) const; virtual double* FindClosest(double *_p, double maxdist2, int threadNum = 0) const;
virtual double *FindClosestAlongDir(double *_p, double *_dir, double maxdist2, int threadNum = 0) const;
private: private:
Scan** m_scans; Scan** m_scans;
DataXYZ** m_data; DataXYZ** m_data;

View file

@ -2,9 +2,9 @@
* @brief Representation of the optimized k-d tree. * @brief Representation of the optimized k-d tree.
* @author Remus Dumitru. Jacobs University Bremen, Germany * @author Remus Dumitru. Jacobs University Bremen, Germany
* @author Corneliu-Claudiu Prodescu. Jacobs University Bremen, Germany * @author Corneliu-Claudiu Prodescu. Jacobs University Bremen, Germany
* @author Andreas Nuechter. Institute of Computer Science, University of Osnabrueck, Germany. * @author Andreas Nuechter. Jacobs University Bremen, Germany
* @author Kai Lingemann. Institute of Computer Science, University of Osnabrueck, Germany. * @author Kai Lingemann. Inst. of CS, University of Osnabrueck, Germany
* @author Thomas Escher. Institute of Computer Science, University of Osnabrueck, Germany. * @author Thomas Escher. Inst. of CS, University of Osnabrueck, Germany
*/ */
#ifndef __KD_TREE_IMPL_H__ #ifndef __KD_TREE_IMPL_H__
@ -23,6 +23,15 @@
#include <omp.h> #include <omp.h>
#endif #endif
class PointCompare {
public:
bool operator() (const std::pair<Point, double>& left,
const std::pair<Point, double>& right)
{
return left.second > right.second;
}
};
/** /**
* @brief The optimized k-d tree. * @brief The optimized k-d tree.
* *
@ -213,10 +222,12 @@ protected:
} }
// Quick check of whether to abort // Quick check of whether to abort
double approx_dist_bbox = max(max(fabs(params[threadNum].p[0]-node.center[0])-node.dx, double approx_dist_bbox =
max(max(fabs(params[threadNum].p[0]-node.center[0])-node.dx,
fabs(params[threadNum].p[1]-node.center[1])-node.dy), fabs(params[threadNum].p[1]-node.center[1])-node.dy),
fabs(params[threadNum].p[2]-node.center[2])-node.dz); fabs(params[threadNum].p[2]-node.center[2])-node.dz);
if (approx_dist_bbox >= 0 && sqr(approx_dist_bbox) >= params[threadNum].closest_d2) if (approx_dist_bbox >= 0 &&
sqr(approx_dist_bbox) >= params[threadNum].closest_d2)
return; return;
// Recursive case // Recursive case
@ -233,6 +244,143 @@ protected:
} }
} }
} }
void _FindClosestAlongDir(const PointData& pts, int threadNum) const {
AccessorFunc point;
// Leaf nodes
if (npts) {
for (int i=0; i < npts; i++) {
double p2p[] = { params[threadNum].p[0] - point(pts, leaf.p[i])[0],
params[threadNum].p[1] - point(pts, leaf.p[i])[1],
params[threadNum].p[2] - point(pts, leaf.p[i])[2] };
double myd2 = Len2(p2p) - sqr(Dot(p2p, params[threadNum].dir));
if ((myd2 < params[threadNum].closest_d2)) {
params[threadNum].closest_d2 = myd2;
params[threadNum].closest = point(pts, leaf.p[i]);
}
}
return;
}
// Quick check of whether to abort
double p2c[] = { params[threadNum].p[0] - node.center[0],
params[threadNum].p[1] - node.center[1],
params[threadNum].p[2] - node.center[2] };
double myd2center = Len2(p2c) - sqr(Dot(p2c, params[threadNum].dir));
if (myd2center > node.r2 + params[threadNum].closest_d2 + 2.0f * max(node.r2, params[threadNum].closest_d2))
return;
// Recursive case
if (params[threadNum].p[node.splitaxis] < node.center[node.splitaxis] ) {
node.child1->_FindClosestAlongDir(pts, threadNum);
node.child2->_FindClosestAlongDir(pts, threadNum);
} else {
node.child2->_FindClosestAlongDir(pts, threadNum);
node.child1->_FindClosestAlongDir(pts, threadNum);
}
}
void _FixedRangeSearch(const PointData& pts, int threadNum) const {
AccessorFunc point;
// Leaf nodes
if (npts) {
for (int i = 0; i < npts; i++) {
double myd2 = Dist2(params[threadNum].p, point(pts, leaf.p[i]));
if (myd2 < params[threadNum].closest_d2) {
params[threadNum].closest = point(pts, leaf.p[i]);
Point newPt;
double* currPt = point(pts, leaf.p[i]);
newPt.x = currPt[0];
newPt.y = currPt[1];
newPt.z = currPt[2];
params[threadNum].heap.push_back(std::make_pair(newPt, myd2));
std::push_heap(params[threadNum].heap.begin(),
params[threadNum].heap.end(),
PointCompare());
}
}
return;
}
// Quick check of whether to abort
double approx_dist_bbox =
max(max(fabs(params[threadNum].p[0]-node.center[0])-node.dx,
fabs(params[threadNum].p[1]-node.center[1])-node.dy),
fabs(params[threadNum].p[2]-node.center[2])-node.dz);
if (approx_dist_bbox >= 0 &&
sqr(approx_dist_bbox) >= params[threadNum].closest_d2)
return;
// Recursive case
double myd = node.center[node.splitaxis] - params[threadNum].p[node.splitaxis];
if (myd >= 0.0) {
node.child1->_FixedRangeSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child2->_FixedRangeSearch(pts, threadNum);
}
} else {
node.child2->_FixedRangeSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child1->_FixedRangeSearch(pts, threadNum);
}
}
}
void _KNNSearch(const PointData& pts, int threadNum) const {
AccessorFunc point;
// Leaf nodes
if (npts) {
for (int i = 0; i < npts; i++) {
double myd2 = Dist2(params[threadNum].p, point(pts, leaf.p[i]));
if (myd2 < params[threadNum].closest_d2) {
Point newPt;
double* currPt = point(pts, leaf.p[i]);
newPt.x = currPt[0];
newPt.y = currPt[1];
newPt.z = currPt[2];
params[threadNum].heap.push_back(std::make_pair(newPt, myd2));
std::push_heap(params[threadNum].heap.begin(),
params[threadNum].heap.end(),
PointCompare());
params[threadNum].closest = point(pts, leaf.p[i]);
}
}
return;
}
// Quick check of whether to abort
double approx_dist_bbox =
max(max(fabs(params[threadNum].p[0]-node.center[0])-node.dx,
fabs(params[threadNum].p[1]-node.center[1])-node.dy),
fabs(params[threadNum].p[2]-node.center[2])-node.dz);
if (approx_dist_bbox >= 0 &&
sqr(approx_dist_bbox) >= params[threadNum].closest_d2)
return;
// Recursive case
double myd = node.center[node.splitaxis] - params[threadNum].p[node.splitaxis];
if (myd >= 0.0) {
node.child1->_KNNSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child2->_KNNSearch(pts, threadNum);
}
} else {
node.child2->_KNNSearch(pts, threadNum);
if (sqr(myd) < params[threadNum].closest_d2) {
node.child1->_KNNSearch(pts, threadNum);
}
}
}
}; };
#endif #endif

View file

@ -1,14 +1,18 @@
/** /**
* @file * @file
* @brief Representation of the parameter of a k-d tree * @brief Representation of the parameter of a k-d tree
* @author Andreas Nuechter. Institute of Computer Science, University of Osnabrueck, Germany. * @author Andreas Nuechter. jacobs University Bremen, Germany.
*/ */
#ifndef __KDPARAMS_H__ #ifndef __KDPARAMS_H__
#define __KDPARAMS_H__ #define __KDPARAMS_H__
#include "slam6d/point.h"
#include <vector>
/** /**
* @brief Contains the intermediate (static) values of a k-d tree or a cached k-d tree * @brief Contains the intermediate (static) values of a k-d tree
* *
* A parameter class for the latter k-d tree. * A parameter class for the latter k-d tree.
* Includes the padding for parallelizetion * Includes the padding for parallelizetion
@ -32,6 +36,16 @@ public:
*/ */
double *p; double *p;
/**
* pointer to direction vector, if we're using FindClosestAlongDir
*/
double *dir;
/**
* heap for KNN.
*/
std::vector<std::pair<Point, double> > heap;
/** /**
* expand to 128 bytes to avoid false-sharing, 16 bytes from above + 28*4 bytes = 128 bytes * expand to 128 bytes to avoid false-sharing, 16 bytes from above + 28*4 bytes = 128 bytes
*/ */

View file

@ -43,6 +43,7 @@ public:
protected: protected:
virtual void createSearchTreePrivate(); virtual void createSearchTreePrivate();
virtual void calcReducedOnDemandPrivate(); virtual void calcReducedOnDemandPrivate();
virtual void calcNormalsOnDemandPrivate() {};
virtual void addFrame(AlgoType type); virtual void addFrame(AlgoType type);
private: private:

View file

@ -34,6 +34,7 @@ public:
protected: protected:
virtual void createSearchTreePrivate(); virtual void createSearchTreePrivate();
virtual void calcReducedOnDemandPrivate() {} virtual void calcReducedOnDemandPrivate() {}
virtual void calcNormalsOnDemandPrivate() {}
virtual void addFrame(AlgoType type) {} virtual void addFrame(AlgoType type) {}
private: private:
std::vector<Scan*> m_scans; std::vector<Scan*> m_scans;

View file

@ -0,0 +1,10 @@
#ifndef __PAIRINGMODE_H__
#define __PAIRINGMODE_H__
enum PairingMode {
CLOSEST_POINT,
CLOSEST_POINT_ALONG_NORMAL,
CLOSEST_PLANE
};
#endif // PAIRINGMODE_H

View file

@ -101,6 +101,12 @@ public:
double y; double y;
/// z coordinate in 3D space /// z coordinate in 3D space
double z; double z;
/// normal x direction in 3D space
double nx;
/// normal x direction in 3D space
double ny;
/// normal x direction in 3D space
double nz;
/// additional information about the point, e.g., semantic /// additional information about the point, e.g., semantic
/// also used in veloscan for distiuguish moving or static /// also used in veloscan for distiuguish moving or static
int type; int type;

View file

@ -30,6 +30,7 @@ public:
static const unsigned int USE_NONE; static const unsigned int USE_NONE;
static const unsigned int USE_REFLECTANCE; static const unsigned int USE_REFLECTANCE;
static const unsigned int USE_NORMAL;
static const unsigned int USE_TEMPERATURE; static const unsigned int USE_TEMPERATURE;
static const unsigned int USE_AMPLITUDE; static const unsigned int USE_AMPLITUDE;
static const unsigned int USE_DEVIATION; static const unsigned int USE_DEVIATION;
@ -44,6 +45,7 @@ public:
PointType(unsigned int _types); PointType(unsigned int _types);
bool hasReflectance(); bool hasReflectance();
bool hasNormal();
bool hasTemperature(); bool hasTemperature();
bool hasAmplitude(); bool hasAmplitude();
bool hasDeviation(); bool hasDeviation();
@ -114,6 +116,7 @@ private:
unsigned int getScanSize(Scan* scan); unsigned int getScanSize(Scan* scan);
DataXYZ* m_xyz; DataXYZ* m_xyz;
DataXYZ* m_normal;
DataRGB* m_rgb; DataRGB* m_rgb;
DataReflectance* m_reflectance; DataReflectance* m_reflectance;
DataTemperature* m_temperature; DataTemperature* m_temperature;
@ -134,6 +137,11 @@ T *PointType::createPoint(const Point &P, unsigned int index ) {
if (types & USE_REFLECTANCE) { if (types & USE_REFLECTANCE) {
p[counter++] = P.reflectance; p[counter++] = P.reflectance;
} }
if (types & USE_NORMAL) {
p[counter++] = P.nx;
p[counter++] = P.ny;
p[counter++] = P.nz;
}
if (types & USE_TEMPERATURE) { if (types & USE_TEMPERATURE) {
p[counter++] = P.temperature; p[counter++] = P.temperature;
} }
@ -171,6 +179,11 @@ Point PointType::createPoint(T *p) {
if (types & USE_REFLECTANCE) { if (types & USE_REFLECTANCE) {
P.reflectance = p[counter++]; P.reflectance = p[counter++];
} }
if (types & USE_NORMAL) {
p[counter++] = P.nx;
p[counter++] = P.ny;
p[counter++] = P.nz;
}
if (types & USE_TEMPERATURE) { if (types & USE_TEMPERATURE) {
P.temperature = p[counter++]; P.temperature = p[counter++];
} }
@ -206,6 +219,10 @@ T *PointType::createPoint(unsigned int i, unsigned int index) {
if (types & USE_REFLECTANCE) { if (types & USE_REFLECTANCE) {
p[counter++] = (m_reflectance? (*m_reflectance)[i]: 0); p[counter++] = (m_reflectance? (*m_reflectance)[i]: 0);
} }
if (types & USE_NORMAL) {
for(unsigned int j = 0; j < 3; ++j)
p[counter++] = (*m_normal)[i][j];
}
if (types & USE_TEMPERATURE) { if (types & USE_TEMPERATURE) {
p[counter++] = (m_temperature? (*m_temperature)[i]: 0); p[counter++] = (m_temperature? (*m_temperature)[i]: 0);
} }

View file

@ -5,6 +5,7 @@
#include "data_types.h" #include "data_types.h"
#include "point_type.h" #include "point_type.h"
#include "ptpair.h" #include "ptpair.h"
#include "pairingMode.h"
#include <string> #include <string>
#include <vector> #include <vector>
@ -97,10 +98,7 @@ Last, if program ends, clean up
class Scan { class Scan {
//friend class SearchTree; // TODO: is this neccessary? //friend class SearchTree; // TODO: is this neccessary?
public: public:
enum AlgoType { enum AlgoType { INVALID, ICP, ICPINACTIVE, LUM, ELCH };
INVALID, ICP, ICPINACTIVE, LUM, ELCH, LOOPTORO, LOOPHOGMAN, GRAPHTORO,
GRAPHHOGMAN
};
// delete copy-ctor and assignment, scans shouldn't be copied by basic class // delete copy-ctor and assignment, scans shouldn't be copied by basic class
Scan(const Scan& other) = delete; Scan(const Scan& other) = delete;
@ -108,7 +106,8 @@ public:
virtual ~Scan(); virtual ~Scan();
//! Holder of all scans - also used in transform for adding frames for each scan at the same time //! Holder of all scans
// also used in transform for adding frames for each scan at the same time
static std::vector<Scan*> allScans; static std::vector<Scan*> allScans;
/** /**
@ -286,7 +285,7 @@ public:
Scan* Source, Scan* Target, Scan* Source, Scan* Target,
int thread_num, int thread_num,
int rnd, double max_dist_match2, double &sum, int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d); double *centroid_m, double *centroid_d, PairingMode pairing_mode = CLOSEST_POINT);
static void getNoPairsSimple(std::vector<double*> &diff, static void getNoPairsSimple(std::vector<double*> &diff,
Scan* Source, Scan* Target, Scan* Source, Scan* Target,
int thread_num, int thread_num,
@ -302,7 +301,8 @@ public:
int rnd, double max_dist_match2, int rnd, double max_dist_match2,
double *sum, double *sum,
double centroid_m[OPENMP_NUM_THREADS][3], double centroid_m[OPENMP_NUM_THREADS][3],
double centroid_d[OPENMP_NUM_THREADS][3]); double centroid_d[OPENMP_NUM_THREADS][3],
PairingMode pairing_mode);
protected: protected:
/** /**
@ -352,6 +352,9 @@ protected:
//! Flag whether "xyz reduced" has been initialized for this Scan yet //! Flag whether "xyz reduced" has been initialized for this Scan yet
bool m_has_reduced; bool m_has_reduced;
//! Flag whether "normals" has been initialized for this Scan yet
bool m_has_normals;
//! Reduction value used for octtree input //! Reduction value used for octtree input
double octtree_reduction_voxelSize; double octtree_reduction_voxelSize;
@ -372,19 +375,31 @@ protected:
/** /**
* This function handles the reduction of points. It builds a lock for * This function handles the reduction of points. It builds a lock for
* multithread-safety and calls caldReducedOnDemandPrivate. * multithread-safety and calls calcReducedOnDemandPrivate.
* *
* The intention is to reduce points, transforme them to the initial pose and * The intention is to reduce points, transforme them to the initial pose and
* then copy them to original for the SearchTree. * then copy them to original for the SearchTree.
*/ */
void calcReducedOnDemand(); void calcReducedOnDemand();
/**
* This function handles the computation of the normals. It builds a lock for
* multithread-safety and calls caldNormalsOnDemandPrivate.
*/
void calcNormalsOnDemand();
//! Create specific SearchTree variants matching the capability of the Scan //! Create specific SearchTree variants matching the capability of the Scan
virtual void createSearchTreePrivate() = 0; virtual void createSearchTreePrivate() = 0;
//! Create reduced points in a multithread-safe environment matching the capability of the Scan //! Create reduced points in a multithread-safe environment matching the capability of the Scan
virtual void calcReducedOnDemandPrivate() = 0; virtual void calcReducedOnDemandPrivate() = 0;
//! Create normals in a multithread-safe environment matching the capability of the Scan
virtual void calcNormalsOnDemandPrivate() = 0;
//! Creating normals
void calcNormals();
//! Internal function of transform which alters the reduced points //! Internal function of transform which alters the reduced points
void transformReduced(const double alignxf[16]); void transformReduced(const double alignxf[16]);
@ -392,11 +407,11 @@ protected:
void transformMatrix(const double alignxf[16]); void transformMatrix(const double alignxf[16]);
//@FIXME //@FIXME
public: public:
//! Creating reduced points //! Creating reduced points
void calcReducedPoints(); void calcReducedPoints();
protected: protected:
//! Copies reduced points to original points without any transformation. //! Copies reduced points to original points without any transformation.
void copyReducedToOriginal(); void copyReducedToOriginal();
@ -410,7 +425,7 @@ private:
public: public:
//! Mutex for safely reducing points and creating the search tree just once in a multithreaded environment //! Mutex for safely reducing points and creating the search tree just once in a multithreaded environment
// it can not be compiled in win32 use boost 1.48, therefore we remeove it temporarily // it can not be compiled in win32 use boost 1.48, therefore we remeove it temporarily
boost::mutex m_mutex_reduction, m_mutex_create_tree; boost::mutex m_mutex_reduction, m_mutex_create_tree, m_mutex_normals;
}; };
#include "scan.icc" #include "scan.icc"

View file

@ -12,6 +12,7 @@ using std::vector;
#include "ptpair.h" #include "ptpair.h"
#include "data_types.h" #include "data_types.h"
#include "pairingMode.h"
/** /**
* @brief The tree structure * @brief The tree structure
@ -38,6 +39,7 @@ class Scan;
class SearchTree : public Tree { class SearchTree : public Tree {
friend class Scan; friend class Scan;
public: public:
/** /**
* Constructor (default) * Constructor (default)
*/ */
@ -77,7 +79,9 @@ public:
* @param threadNum If parallel threads share the search tree the thread num must be given * @param threadNum If parallel threads share the search tree the thread num must be given
* @return Pointer to closest point * @return Pointer to closest point
*/ */
virtual double *FindClosest(double *_p, double maxdist2, int threadNum = 0) const = 0 ; virtual double *FindClosest(double *_p, double maxdist2, int threadNum = 0) const = 0;
virtual double *FindClosestAlongDir(double *_p, double *_dir, double maxdist2, int threadNum) const;
virtual void getPtPairs(vector <PtPair> *pairs, virtual void getPtPairs(vector <PtPair> *pairs,
double *source_alignxf, double *source_alignxf,
@ -88,10 +92,10 @@ public:
virtual void getPtPairs(vector <PtPair> *pairs, virtual void getPtPairs(vector <PtPair> *pairs,
double *source_alignxf, double *source_alignxf,
const DataXYZ& xyz_r, unsigned int startindex, unsigned int endindex, const DataXYZ& xyz_r, const DataNormal& normal_r, unsigned int startindex, unsigned int endindex,
int thread_num, int thread_num,
int rnd, double max_dist_match2, double &sum, int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d); double *centroid_m, double *centroid_d, PairingMode pairing_mode = CLOSEST_POINT);
}; };
#endif #endif

35
know_issues.txt Normal file
View file

@ -0,0 +1,35 @@
1.
--metascan segfaults when destroying the allscanlist.
2.
scanserver segfaults whith reflectances sometimes.
E.g.,
bin/scanserver -c 3500
and
bin/show -s 0 -e 1 -f riegl_txt --reflectance ~/dat/bremen_city --scanserver
or
bin/scanserver
and
bin/slam6D -s 0 -e 1 -f uosr dat --scanserver
3.
scan_red with panorama range image and cylindrical coordinates does
not work correctly.
4.
fast_normals does not work on SRI yet. Commented out.
5.
reflectance_reduced not in managedScan/scanserver
6.
normals not integrated managedScan/scanserver
7.
kdMeta/kdManaged does not support kNN nor range search yet
8.
Make our own knn efficient, then get rid of ANN ;-)

View file

@ -1,7 +1,7 @@
IF(WITH_NORMALS) add_library(normals normals.cc)
add_executable(normals normals.cc) target_link_libraries(normals newmat scan ANN fbr_cv_io fbr_panorama ${OpenCV_LIBS})
FIND_PACKAGE(OpenCV REQUIRED) IF(WITH_TOOLS)
add_executable(calc_normals calc_normals.cc)
target_link_libraries(normals newmat scan ANN fbr_cv_io fbr_panorama ${Boost_LIBRARIES} ${OpenCV_LIBS}) target_link_libraries(calc_normals normals ${Boost_LIBRARIES})
ENDIF(WITH_NORMALS) ENDIF(WITH_TOOLS)

275
src/normals/calc_normals.cc Normal file
View file

@ -0,0 +1,275 @@
/**
*
* Copyright (C) Jacobs University Bremen
*
* @author Vaibhav Kumar Mehta
* @file calc_normals.cc
*/
#include <iostream>
#include <string>
#include <fstream>
#include <errno.h>
#include <boost/program_options.hpp>
#include <slam6d/io_types.h>
#include <slam6d/globals.icc>
#include <slam6d/scan.h>
#include "slam6d/fbr/panorama.h"
#include <scanserver/clientInterface.h>
#include <normals/normals.h>
#ifdef _MSC_VER
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#else
#include <strings.h>
#endif
namespace po = boost::program_options;
using namespace std;
enum normal_method {AKNN, ADAPTIVE_AKNN, PANORAMA, PANORAMA_FAST};
/*
* validates normal calculation method specification
*/
void validate(boost::any& v, const std::vector<std::string>& values,
normal_method*, int) {
if (values.size() == 0)
throw std::runtime_error("Invalid model specification");
string arg = values.at(0);
if(strcasecmp(arg.c_str(), "AKNN") == 0) v = AKNN;
else if(strcasecmp(arg.c_str(), "ADAPTIVE_AKNN") == 0) v = ADAPTIVE_AKNN;
else if(strcasecmp(arg.c_str(), "PANORAMA") == 0) v = PANORAMA;
else if(strcasecmp(arg.c_str(), "PANORAMA_FAST") == 0) v = PANORAMA_FAST;
else throw std::runtime_error(std::string("normal calculation method ") + arg + std::string(" is unknown"));
}
/// validate IO types
void validate(boost::any& v, const std::vector<std::string>& values,
IOType*, int) {
if (values.size() == 0)
throw std::runtime_error("Invalid model specification");
string arg = values.at(0);
try {
v = formatname_to_io_type(arg.c_str());
} catch (...) { // runtime_error
throw std::runtime_error("Format " + arg + " unknown.");
}
}
/// Parse commandline options
void parse_options(int argc, char **argv, int &start, int &end, bool &scanserver, int &max_dist, int &min_dist, string &dir,
IOType &iotype, int &k1, int &k2, normal_method &ntype,int &width,int &height)
{
/// ----------------------------------
/// set up program commandline options
/// ----------------------------------
po::options_description cmd_options("Usage: calculateNormals <options> where options are (default values in brackets)");
cmd_options.add_options()
("help,?", "Display this help message")
("start,s", po::value<int>(&start)->default_value(0), "Start at scan number <arg>")
("end,e", po::value<int>(&end)->default_value(-1), "Stop at scan number <arg>")
("scanserver,S", po::value<bool>(&scanserver)->default_value(false), "Use the scanserver as an input method")
("format,f", po::value<IOType>(&iotype)->default_value(UOS),
"using shared library <arg> for input. (chose format from [uos|uosr|uos_map|"
"uos_rgb|uos_frames|uos_map_frames|old|rts|rts_map|ifp|"
"riegl_txt|riegl_rgb|riegl_bin|zahn|ply])")
("max,M", po::value<int>(&max_dist)->default_value(-1),"neglegt all data points with a distance larger than <arg> 'units")
("min,m", po::value<int>(&min_dist)->default_value(-1),"neglegt all data points with a distance smaller than <arg> 'units")
("normal,g", po::value<normal_method>(&ntype)->default_value(AKNN), "normal calculation method "
"(AKNN, ADAPTIVE_AKNN, PANORAMA, PANORAMA_FAST)")
("K1,k", po::value<int>(&k1)->default_value(20), "<arg> value of K value used in the nearest neighbor search of ANN or" "kmin for k-adaptation")
("K2,K", po::value<int>(&k2)->default_value(20), "<arg> value of Kmax for k-adaptation")
("width,w", po::value<int>(&width)->default_value(1280),"width of panorama image")
("height,h", po::value<int>(&height)->default_value(960),"height of panorama image")
;
po::options_description hidden("Hidden options");
hidden.add_options()
("input-dir", po::value<string>(&dir), "input dir");
po::positional_options_description pd;
pd.add("input-dir", 1);
po::options_description all;
all.add(cmd_options).add(hidden);
po::variables_map vmap;
po::store(po::command_line_parser(argc, argv).options(all).positional(pd).run(), vmap);
po::notify(vmap);
if (vmap.count("help")) {
cout << cmd_options << endl << endl;
cout << "SAMPLE COMMAND FOR CALCULATING NORMALS" << endl;
cout << " bin/normals -s 0 -e 0 -f UOS -g AKNN -k 20 dat/" <<endl;
cout << endl << endl;
cout << "SAMPLE COMMAND FOR VIEWING CALCULATING NORMALS IN RGB SPACE" << endl;
cout << " bin/show -c -f UOS_RGB dat/normals/" << endl;
exit(-1);
}
// read scan path
if (dir[dir.length()-1] != '/') dir = dir + "/";
}
/// Write a pose file with the specofied name
void writePoseFiles(string dir, const double* rPos, const double* rPosTheta,int scanNumber)
{
string poseFileName = dir + "/scan" + to_string(scanNumber, 3) + ".pose";
ofstream posout(poseFileName.c_str());
posout << rPos[0] << " "
<< rPos[1] << " "
<< rPos[2] << endl
<< deg(rPosTheta[0]) << " "
<< deg(rPosTheta[1]) << " "
<< deg(rPosTheta[2]) << endl;
posout.clear();
posout.close();
}
/// write scan files for all segments
void writeScanFiles(string dir, vector<Point> &points, vector<Point> &normals, int scanNumber)
{
string ofilename = dir + "/scan" + to_string(scanNumber, 3) + ".3d";
ofstream normptsout(ofilename.c_str());
for (size_t i=0; i<points.size(); ++i)
{
int r,g,b;
r = (int)(normals[i].x * (127.5) + 127.5);
g = (int)(normals[i].y * (127.5) + 127.5);
b = (int)(fabs(normals[i].z) * (255.0));
normptsout <<points[i].x<<" "<<points[i].y<<" "<<points[i].z<<" "<<r<<" "<<g<<" "<<b<<" "<<endl;
}
normptsout.clear();
normptsout.close();
}
/// =============================================
/// Main
/// =============================================
int main(int argc, char** argv)
{
int start, end;
bool scanserver;
int max_dist, min_dist;
string dir;
IOType iotype;
int k1, k2;
normal_method ntype;
int width, height;
parse_options(argc, argv, start, end, scanserver, max_dist, min_dist,
dir, iotype, k1, k2, ntype, width, height);
/// ----------------------------------
/// Prepare and read scans
/// ----------------------------------
if (scanserver) {
try {
ClientInterface::create();
} catch(std::runtime_error& e) {
cerr << "ClientInterface could not be created: " << e.what() << endl;
cerr << "Start the scanserver first." << endl;
exit(-1);
}
}
/// Make directory for saving the scan segments
string normdir = dir + "normals";
#ifdef _MSC_VER
int success = mkdir(normdir.c_str());
#else
int success = mkdir(normdir.c_str(), S_IRWXU|S_IRWXG|S_IRWXO);
#endif
if(success == 0) {
cout << "Writing segments to " << normdir << endl;
} else if(errno == EEXIST) {
cout << "WARN: Directory " << normdir << " exists already. Contents will be overwriten" << endl;
} else {
cerr << "Creating directory " << normdir << " failed" << endl;
exit(1);
}
/// Read the scans
Scan::openDirectory(scanserver, dir, iotype, start, end);
if(Scan::allScans.size() == 0) {
cerr << "No scans found. Did you use the correct format?" << endl;
exit(-1);
}
cv::Mat img;
/// --------------------------------------------
/// Initialize and perform segmentation
/// --------------------------------------------
std::vector<Scan*>::iterator it = Scan::allScans.begin();
int scanNumber = 0;
for( ; it != Scan::allScans.end(); ++it) {
Scan* scan = *it;
// apply optional filtering
scan->setRangeFilter(max_dist, min_dist);
const double* rPos = scan->get_rPos();
const double* rPosTheta = scan->get_rPosTheta();
/// read scan into points
DataXYZ xyz(scan->get("xyz"));
vector<Point> points;
points.reserve(xyz.size());
vector<Point> normals;
normals.reserve(xyz.size());
for(unsigned int j = 0; j < xyz.size(); j++) {
points.push_back(Point(xyz[j][0], xyz[j][1], xyz[j][2]));
}
if(ntype == AKNN)
calculateNormalsApxKNN(normals,points, k1, rPos);
else if(ntype == ADAPTIVE_AKNN)
calculateNormalsAdaptiveApxKNN(normals,points, k1, k2, rPos);
else
{
// create panorama
fbr::panorama fPanorama(width, height, fbr::EQUIRECTANGULAR, 1, 0, fbr::EXTENDED);
fPanorama.createPanorama(scan2mat(scan));
// the range image has to be converted from float to uchar
img = fPanorama.getRangeImage();
img = float2uchar(img, 0, 0.0);
if(ntype == PANORAMA)
calculateNormalsPANORAMA(normals,points,fPanorama.getExtendedMap(), rPos);
else if(ntype == PANORAMA_FAST)
cout << "PANORAMA_FAST is not working yet" << endl;
// calculateNormalsFAST(normals,points,img,fPanorama.getExtendedMap());
}
// pose file (repeated for the number of segments
writePoseFiles(normdir, rPos, rPosTheta, scanNumber);
// scan files for all segments
writeScanFiles(normdir, points,normals,scanNumber);
scanNumber++;
}
// shutdown everything
if (scanserver)
ClientInterface::destroy();
Scan::closeDirectory();
cout << "Normal program end" << endl;
return 0;
}

View file

@ -3,127 +3,34 @@
* Copyright (C) Jacobs University Bremen * Copyright (C) Jacobs University Bremen
* *
* @author Vaibhav Kumar Mehta * @author Vaibhav Kumar Mehta
* @author Corneliu Claudiu Prodescu
* @file normals.cc * @file normals.cc
*/ */
#include <iostream> #include <vector>
#include <string>
#include <fstream>
#include <errno.h>
#include <boost/program_options.hpp>
#include <slam6d/io_types.h>
#include <slam6d/globals.icc>
#include <slam6d/scan.h>
#include "slam6d/fbr/panorama.h"
#include <scanserver/clientInterface.h>
#include <ANN/ANN.h> #include <ANN/ANN.h>
#include "slam6d/io_types.h"
#include "slam6d/globals.icc"
#include "slam6d/scan.h"
#include "slam6d/fbr/panorama.h"
#include "slam6d/kd.h"
#include <scanserver/clientInterface.h>
#include "newmat/newmat.h" #include "newmat/newmat.h"
#include "newmat/newmatap.h" #include "newmat/newmatap.h"
#include "normals/normals.h"
using namespace NEWMAT; using namespace NEWMAT;
#ifdef _MSC_VER
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#else
#include <strings.h>
#endif
namespace po = boost::program_options;
using namespace std; using namespace std;
enum normal_method {AKNN, ADAPTIVE_AKNN, PANORAMA, PANORAMA_FAST}; //////////////////////////////////////////////////////
/*
* validates normal calculation method specification
*/
void validate(boost::any& v, const std::vector<std::string>& values,
normal_method*, int) {
if (values.size() == 0)
throw std::runtime_error("Invalid model specification");
string arg = values.at(0);
if(strcasecmp(arg.c_str(), "AKNN") == 0) v = AKNN;
else if(strcasecmp(arg.c_str(), "ADAPTIVE_AKNN") == 0) v = ADAPTIVE_AKNN;
else if(strcasecmp(arg.c_str(), "PANORAMA") == 0) v = PANORAMA;
else if(strcasecmp(arg.c_str(), "PANORAMA_FAST") == 0) v = PANORAMA_FAST;
else throw std::runtime_error(std::string("normal calculation method ") + arg + std::string(" is unknown"));
}
/// validate IO types
void validate(boost::any& v, const std::vector<std::string>& values,
IOType*, int) {
if (values.size() == 0)
throw std::runtime_error("Invalid model specification");
string arg = values.at(0);
try {
v = formatname_to_io_type(arg.c_str());
} catch (...) { // runtime_error
throw std::runtime_error("Format " + arg + " unknown.");
}
}
/// Parse commandline options
void parse_options(int argc, char **argv, int &start, int &end, bool &scanserver, int &max_dist, int &min_dist, string &dir,
IOType &iotype, int &k1, int &k2, normal_method &ntype,int &width,int &height)
{
/// ----------------------------------
/// set up program commandline options
/// ----------------------------------
po::options_description cmd_options("Usage: calculateNormals <options> where options are (default values in brackets)");
cmd_options.add_options()
("help,?", "Display this help message")
("start,s", po::value<int>(&start)->default_value(0), "Start at scan number <arg>")
("end,e", po::value<int>(&end)->default_value(-1), "Stop at scan number <arg>")
("scanserver,S", po::value<bool>(&scanserver)->default_value(false), "Use the scanserver as an input method")
("format,f", po::value<IOType>(&iotype)->default_value(UOS),
"using shared library <arg> for input. (chose format from [uos|uosr|uos_map|"
"uos_rgb|uos_frames|uos_map_frames|old|rts|rts_map|ifp|"
"riegl_txt|riegl_rgb|riegl_bin|zahn|ply])")
("max,M", po::value<int>(&max_dist)->default_value(-1),"neglegt all data points with a distance larger than <arg> 'units")
("min,m", po::value<int>(&min_dist)->default_value(-1),"neglegt all data points with a distance smaller than <arg> 'units")
("normal,g", po::value<normal_method>(&ntype)->default_value(AKNN), "normal calculation method "
"(AKNN, ADAPTIVE_AKNN, PANORAMA, PANORAMA_FAST)")
("K1,k", po::value<int>(&k1)->default_value(20), "<arg> value of K value used in the nearest neighbor search of ANN or" "kmin for k-adaptation")
("K2,K", po::value<int>(&k2)->default_value(20), "<arg> value of Kmax for k-adaptation")
("width,w", po::value<int>(&width)->default_value(1280),"width of panorama image")
("height,h", po::value<int>(&height)->default_value(960),"height of panorama image")
;
po::options_description hidden("Hidden options");
hidden.add_options()
("input-dir", po::value<string>(&dir), "input dir");
po::positional_options_description pd;
pd.add("input-dir", 1);
po::options_description all;
all.add(cmd_options).add(hidden);
po::variables_map vmap;
po::store(po::command_line_parser(argc, argv).options(all).positional(pd).run(), vmap);
po::notify(vmap);
if (vmap.count("help")) {
cout << cmd_options << endl << endl;
cout << "SAMPLE COMMAND FOR CALCULATING NORMALS" << endl;
cout << " bin/normals -s 0 -e 0 -f UOS -g AKNN -k 20 dat/" <<endl;
cout << endl << endl;
cout << "SAMPLE COMMAND FOR VIEWING CALCULATING NORMALS IN RGB SPACE" << endl;
cout << " bin/show -c -f UOS_RGB dat/normals/" << endl;
exit(-1);
}
// read scan path
if (dir[dir.length()-1] != '/') dir = dir + "/";
}
///////////////////////////////////////////////////////
/////////////NORMALS USING AKNN METHOD //////////////// /////////////NORMALS USING AKNN METHOD ////////////////
/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
void calculateNormalsAKNN(vector<Point> &normals,vector<Point> &points, int k, const double _rPos[3] ) void calculateNormalsApxKNN(vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3],
double eps)
{ {
cout<<"Total number of points: "<<points.size()<<endl; cout<<"Total number of points: "<<points.size()<<endl;
int nr_neighbors = k; int nr_neighbors = k;
@ -138,6 +45,7 @@ void calculateNormalsAKNN(vector<Point> &normals,vector<Point> &points, int k, c
pa[i][0] = points[i].x; pa[i][0] = points[i].x;
pa[i][1] = points[i].y; pa[i][1] = points[i].y;
pa[i][2] = points[i].z; pa[i][2] = points[i].z;
} }
ANNkd_tree t(pa, points.size(), 3); ANNkd_tree t(pa, points.size(), 3);
ANNidxArray nidx = new ANNidx[nr_neighbors]; ANNidxArray nidx = new ANNidx[nr_neighbors];
@ -149,7 +57,7 @@ void calculateNormalsAKNN(vector<Point> &normals,vector<Point> &points, int k, c
//ANN search for k nearest neighbors //ANN search for k nearest neighbors
//indexes of the neighbors along with the query point //indexes of the neighbors along with the query point
//stored in the array n //stored in the array n
t.annkSearch(p, nr_neighbors, nidx, d, 0.0); t.annkSearch(p, nr_neighbors, nidx, d, eps);
Point mean(0.0,0.0,0.0); Point mean(0.0,0.0,0.0);
Matrix X(nr_neighbors,3); Matrix X(nr_neighbors,3);
SymmetricMatrix A(3); SymmetricMatrix A(3);
@ -202,8 +110,12 @@ void calculateNormalsAKNN(vector<Point> &normals,vector<Point> &points, int k, c
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
/////////////NORMALS USING ADAPTIVE AKNN METHOD //////////////// /////////////NORMALS USING ADAPTIVE AKNN METHOD ////////////////
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
void calculateNormalsAdaptiveAKNN(vector<Point> &normals,vector<Point> &points, void calculateNormalsAdaptiveApxKNN(vector<Point> &normals,
int kmin, int kmax, const double _rPos[3]) vector<Point> &points,
int kmin,
int kmax,
const double _rPos[3],
double eps)
{ {
ColumnVector rPos(3); ColumnVector rPos(3);
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
@ -213,15 +125,16 @@ void calculateNormalsAdaptiveAKNN(vector<Point> &normals,vector<Point> &points,
int nr_neighbors; int nr_neighbors;
ANNpointArray pa = annAllocPts(points.size(), 3); ANNpointArray pa = annAllocPts(points.size(), 3);
for (size_t i=0; i<points.size(); ++i) for (size_t i=0; i<points.size(); ++i)
{ {
pa[i][0] = points[i].x; pa[i][0] = points[i].x;
pa[i][1] = points[i].y; pa[i][1] = points[i].y;
pa[i][2] = points[i].z; pa[i][2] = points[i].z;
} }
ANNkd_tree t(pa, points.size(), 3); ANNkd_tree t(pa, points.size(), 3);
Point mean(0.0,0.0,0.0); Point mean(0.0,0.0,0.0);
double temp_n[3],norm_n = 0.0;
double e1,e2,e3; double e1,e2,e3;
for (size_t i=0; i<points.size(); ++i) for (size_t i=0; i<points.size(); ++i)
@ -236,7 +149,7 @@ void calculateNormalsAdaptiveAKNN(vector<Point> &normals,vector<Point> &points,
//ANN search for k nearest neighbors //ANN search for k nearest neighbors
//indexes of the neighbors along with the query point //indexes of the neighbors along with the query point
//stored in the array n //stored in the array n
t.annkSearch(p, nr_neighbors, nidx, d, 0.0); t.annkSearch(p, nr_neighbors, nidx, d, eps);
mean.x=0,mean.y=0,mean.z=0; mean.x=0,mean.y=0,mean.z=0;
//calculate mean for all the points //calculate mean for all the points
for (int j=0; j<nr_neighbors; ++j) for (int j=0; j<nr_neighbors; ++j)
@ -298,6 +211,216 @@ void calculateNormalsAdaptiveAKNN(vector<Point> &normals,vector<Point> &points,
annDeallocPts(pa); annDeallocPts(pa);
} }
///////////////////////////////////////////////////////
/////////////NORMALS USING AKNN METHOD ////////////////
///////////////////////////////////////////////////////
void calculateNormalsKNN(vector<Point> &normals,
vector<Point> &points,
int k,
const double _rPos[3] )
{
cout<<"Total number of points: "<<points.size()<<endl;
int nr_neighbors = k;
ColumnVector rPos(3);
for (int i = 0; i < 3; ++i)
rPos(i+1) = _rPos[i];
double** pa = new double*[points.size()];
for (size_t i = 0; i < points.size(); ++i)
{
pa[i] = new double[3];
pa[i][0] = points[i].x;
pa[i][1] = points[i].y;
pa[i][2] = points[i].z;
}
KDtree t(pa, points.size());
for (size_t i=0; i<points.size(); ++i)
{
double p[3] = {pa[i][0], pa[i][1], pa[i][2]};
//ANN search for k nearest neighbors
//indexes of the neighbors along with the query point
//stored in the array n
vector<Point> temp = t.kNearestNeighbors(p,
nr_neighbors,
numeric_limits<double>::max());
nr_neighbors = temp.size();
Point mean(0.0,0.0,0.0);
Matrix X(nr_neighbors,3);
SymmetricMatrix A(3);
Matrix U(3,3);
DiagonalMatrix D(3);
//calculate mean for all the points
for (int j = 0; j < nr_neighbors; ++j)
{
mean.x += temp[j].x;
mean.y += temp[j].y;
mean.z += temp[j].z;
}
mean.x /= nr_neighbors;
mean.y /= nr_neighbors;
mean.z /= nr_neighbors;
//calculate covariance = A for all the points
for (int i = 0; i < nr_neighbors; ++i) {
X(i+1, 1) = temp[i].x - mean.x;
X(i+1, 2) = temp[i].y - mean.y;
X(i+1, 3) = temp[i].z - mean.z;
}
A << 1.0/nr_neighbors * X.t() * X;
EigenValues(A, D, U);
//normal = eigenvector corresponding to lowest
//eigen value that is the 1st column of matrix U
ColumnVector n(3);
n(1) = U(1,1);
n(2) = U(2,1);
n(3) = U(3,1);
ColumnVector point_vector(3);
point_vector(1) = p[0] - rPos(1);
point_vector(2) = p[1] - rPos(2);
point_vector(3) = p[2] - rPos(3);
point_vector = point_vector / point_vector.NormFrobenius();
Real angle = (n.t() * point_vector).AsScalar();
if (angle < 0) {
n *= -1.0;
}
n = n / n.NormFrobenius();
normals.push_back(Point(n(1), n(2), n(3)));
}
for (size_t i = 0; i < points.size(); ++i)
{
delete[] pa[i];
}
delete[] pa;
}
////////////////////////////////////////////////////////////////
/////////////NORMALS USING ADAPTIVE AKNN METHOD ////////////////
////////////////////////////////////////////////////////////////
void calculateNormalsAdaptiveKNN(vector<Point> &normals,
vector<Point> &points,
int kmin,
int kmax,
const double _rPos[3])
{
ColumnVector rPos(3);
for (int i = 0; i < 3; ++i)
rPos(i+1) = _rPos[i];
cout<<"Total number of points: "<<points.size()<<endl;
int nr_neighbors;
double** pa = new double*[points.size()];
for (size_t i = 0; i < points.size(); ++i)
{
pa[i] = new double[3];
pa[i][0] = points[i].x;
pa[i][1] = points[i].y;
pa[i][2] = points[i].z;
}
KDtree t(pa, points.size());
Point mean(0.0,0.0,0.0);
double e1,e2,e3;
for (size_t i=0; i<points.size(); ++i)
{
Matrix U(3,3);
double p[3] = {pa[i][0], pa[i][1], pa[i][2]};
for(int kidx = kmin; kidx < kmax; kidx++)
{
nr_neighbors=kidx+1;
//ANN search for k nearest neighbors
//indexes of the neighbors along with the query point
//stored in the array n
vector<Point> temp = t.kNearestNeighbors(p,
nr_neighbors,
numeric_limits<double>::max());
nr_neighbors = temp.size();
mean.x=0,mean.y=0,mean.z=0;
//calculate mean for all the points
for (int j=0; j<nr_neighbors; ++j)
{
mean.x += temp[j].x;
mean.y += temp[j].y;
mean.z += temp[j].z;
}
mean.x /= nr_neighbors;
mean.y /= nr_neighbors;
mean.z /= nr_neighbors;
Matrix X(nr_neighbors,3);
SymmetricMatrix A(3);
DiagonalMatrix D(3);
//calculate covariance = A for all the points
for (int j = 0; j < nr_neighbors; ++j) {
X(j+1, 1) = temp[j].x - mean.x;
X(j+1, 2) = temp[j].y - mean.y;
X(j+1, 3) = temp[j].z - mean.z;
}
A << 1.0/nr_neighbors * X.t() * X;
EigenValues(A, D, U);
e1 = D(1);
e2 = D(2);
e3 = D(3);
//We take the particular k if the second maximum eigen value
//is at least 25 percent of the maximum eigen value
if ((e1 > 0.25 * e2) && (fabs(1.0 - (double)e2/(double)e3) < 0.25))
break;
}
//normal = eigenvector corresponding to lowest
//eigen value that is the 1rd column of matrix U
ColumnVector n(3);
n(1) = U(1,1);
n(2) = U(2,1);
n(3) = U(3,1);
ColumnVector point_vector(3);
point_vector(1) = p[0] - rPos(1);
point_vector(2) = p[1] - rPos(2);
point_vector(3) = p[2] - rPos(3);
point_vector = point_vector / point_vector.NormFrobenius();
Real angle = (n.t() * point_vector).AsScalar();
if (angle < 0) {
n *= -1.0;
}
n = n / n.NormFrobenius();
normals.push_back(Point(n(1), n(2), n(3)));
}
for (size_t i = 0; i < points.size(); ++i)
{
delete[] pa[i];
}
delete[] pa;
}
/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
/////////////NORMALS USING IMAGE NEIGHBORS //////////// /////////////NORMALS USING IMAGE NEIGHBORS ////////////
/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
@ -326,7 +449,6 @@ void calculateNormalsPANORAMA(vector<Point> &normals,
if (extendedMap[i][j].size() == 0) continue; if (extendedMap[i][j].size() == 0) continue;
neighbors.clear(); neighbors.clear();
Point mean(0.0,0.0,0.0); Point mean(0.0,0.0,0.0);
double temp_n[3],norm_n = 0.0;
// Offset for neighbor computation // Offset for neighbor computation
int offset[2][5] = {{-1,0,1,0,0},{0,-1,0,1,0}}; int offset[2][5] = {{-1,0,1,0,0},{0,-1,0,1,0}};
@ -375,11 +497,11 @@ void calculateNormalsPANORAMA(vector<Point> &normals,
mean.y /= nr_neighbors; mean.y /= nr_neighbors;
mean.z /= nr_neighbors; mean.z /= nr_neighbors;
//calculate covariance = A for all the points //calculate covariance = A for all the points
for (int i = 0; i < nr_neighbors; ++i) { for (int n = 0; n < nr_neighbors; ++n) {
cv::Vec3f pp = neighbors[i]; cv::Vec3f pp = neighbors[n];
X(i+1, 1) = pp[0] - mean.x; X(n+1, 1) = pp[0] - mean.x;
X(i+1, 2) = pp[1] - mean.y; X(n+1, 2) = pp[1] - mean.y;
X(i+1, 3) = pp[2] - mean.z; X(n+1, 3) = pp[2] - mean.z;
} }
A << 1.0/nr_neighbors * X.t() * X; A << 1.0/nr_neighbors * X.t() * X;
@ -486,268 +608,3 @@ void calculateNormalsPANORAMA(vector<Point> &normals,
} }
} }
*/ */
/*
* retrieve a cv::Mat with x,y,z,r from a scan object
* functionality borrowed from scan_cv::convertScanToMat but this function
* does not allow a scanserver to be used, prints to stdout and can only
* handle a single scan
*/
cv::Mat scan2mat(Scan *source)
{
DataXYZ xyz = source->get("xyz");
DataReflectance xyz_reflectance = source->get("reflectance");
unsigned int nPoints = xyz.size();
cv::Mat scan(nPoints,1,CV_32FC(4));
scan = cv::Scalar::all(0);
cv::MatIterator_<cv::Vec4f> it;
it = scan.begin<cv::Vec4f>();
for(unsigned int i = 0; i < nPoints; i++){
float x, y, z, reflectance;
x = xyz[i][0];
y = xyz[i][1];
z = xyz[i][2];
if(xyz_reflectance.size() != 0)
{
reflectance = xyz_reflectance[i];
//normalize the reflectance
reflectance += 32;
reflectance /= 64;
reflectance -= 0.2;
reflectance /= 0.3;
if (reflectance < 0) reflectance = 0;
if (reflectance > 1) reflectance = 1;
}
(*it)[0] = x;
(*it)[1] = y;
(*it)[2] = z;
if(xyz_reflectance.size() != 0)
(*it)[3] = reflectance;
else
(*it)[3] = 0;
++it;
}
return scan;
}
/*
* convert a matrix of float values (range image) to a matrix of unsigned
* eight bit characters using different techniques
*/
cv::Mat float2uchar(cv::Mat &source, bool logarithm, float cutoff)
{
cv::Mat result(source.size(), CV_8U, cv::Scalar::all(0));
float max = 0;
// find maximum value
if (cutoff == 0.0) {
// without cutoff, just iterate through all values to find the largest
for (cv::MatIterator_<float> it = source.begin<float>();
it != source.end<float>(); ++it) {
float val = *it;
if (val > max) {
max = val;
}
}
} else {
// when a cutoff is specified, sort all the points by value and then
// specify the max so that <cutoff> values are larger than it
vector<float> sorted(source.cols*source.rows);
int i = 0;
for (cv::MatIterator_<float> it = source.begin<float>();
it != source.end<float>(); ++it, ++i) {
sorted[i] = *it;
}
std::sort(sorted.begin(), sorted.end());
max = sorted[(int)(source.cols*source.rows*(1.0-cutoff))];
cout << "A cutoff of " << cutoff << " resulted in a max value of " << max << endl;
}
cv::MatIterator_<float> src = source.begin<float>();
cv::MatIterator_<uchar> dst = result.begin<uchar>();
cv::MatIterator_<float> end = source.end<float>();
if (logarithm) {
// stretch values from 0 to max logarithmically over 0 to 255
// using the logarithm allows to represent smaller values with more
// precision and larger values with less
max = log(max+1);
for (; src != end; ++src, ++dst) {
float val = (log(*src+1)*255.0)/max;
if (val > 255)
*dst = 255;
else
*dst = (uchar)val;
}
} else {
// stretch values from 0 to max linearly over 0 to 255
for (; src != end; ++src, ++dst) {
float val = (*src*255.0)/max;
if (val > 255)
*dst = 255;
else
*dst = (uchar)val;
}
}
return result;
}
/// Write a pose file with the specofied name
void writePoseFiles(string dir, const double* rPos, const double* rPosTheta,int scanNumber)
{
string poseFileName = dir + "/scan" + to_string(scanNumber, 3) + ".pose";
ofstream posout(poseFileName.c_str());
posout << rPos[0] << " "
<< rPos[1] << " "
<< rPos[2] << endl
<< deg(rPosTheta[0]) << " "
<< deg(rPosTheta[1]) << " "
<< deg(rPosTheta[2]) << endl;
posout.clear();
posout.close();
}
/// write scan files for all segments
void writeScanFiles(string dir, vector<Point> &points, vector<Point> &normals, int scanNumber)
{
string ofilename = dir + "/scan" + to_string(scanNumber, 3) + ".3d";
ofstream normptsout(ofilename.c_str());
for (size_t i=0; i<points.size(); ++i)
{
int r,g,b;
r = (int)(normals[i].x * (127.5) + 127.5);
g = (int)(normals[i].y * (127.5) + 127.5);
b = (int)(fabs(normals[i].z) * (255.0));
normptsout <<points[i].x<<" "<<points[i].y<<" "<<points[i].z<<" "<<r<<" "<<g<<" "<<b<<" "<<endl;
}
normptsout.clear();
normptsout.close();
}
/// =============================================
/// Main
/// =============================================
int main(int argc, char** argv)
{
int start, end;
bool scanserver;
int max_dist, min_dist;
string dir;
IOType iotype;
int k1, k2;
normal_method ntype;
int width, height;
parse_options(argc, argv, start, end, scanserver, max_dist, min_dist,
dir, iotype, k1, k2, ntype, width, height);
/// ----------------------------------
/// Prepare and read scans
/// ----------------------------------
if (scanserver) {
try {
ClientInterface::create();
} catch(std::runtime_error& e) {
cerr << "ClientInterface could not be created: " << e.what() << endl;
cerr << "Start the scanserver first." << endl;
exit(-1);
}
}
/// Make directory for saving the scan segments
string normdir = dir + "normals";
#ifdef _MSC_VER
int success = mkdir(normdir.c_str());
#else
int success = mkdir(normdir.c_str(), S_IRWXU|S_IRWXG|S_IRWXO);
#endif
if(success == 0) {
cout << "Writing segments to " << normdir << endl;
} else if(errno == EEXIST) {
cout << "WARN: Directory " << normdir << " exists already. Contents will be overwriten" << endl;
} else {
cerr << "Creating directory " << normdir << " failed" << endl;
exit(1);
}
/// Read the scans
Scan::openDirectory(scanserver, dir, iotype, start, end);
if(Scan::allScans.size() == 0) {
cerr << "No scans found. Did you use the correct format?" << endl;
exit(-1);
}
cv::Mat img;
/// --------------------------------------------
/// Initialize and perform segmentation
/// --------------------------------------------
std::vector<Scan*>::iterator it = Scan::allScans.begin();
int scanNumber = 0;
for( ; it != Scan::allScans.end(); ++it) {
Scan* scan = *it;
// apply optional filtering
scan->setRangeFilter(max_dist, min_dist);
const double* rPos = scan->get_rPos();
const double* rPosTheta = scan->get_rPosTheta();
/// read scan into points
DataXYZ xyz(scan->get("xyz"));
vector<Point> points;
points.reserve(xyz.size());
vector<Point> normals;
normals.reserve(xyz.size());
for(unsigned int j = 0; j < xyz.size(); j++) {
points.push_back(Point(xyz[j][0], xyz[j][1], xyz[j][2]));
}
if(ntype == AKNN)
calculateNormalsAKNN(normals,points, k1, rPos);
else if(ntype == ADAPTIVE_AKNN)
calculateNormalsAdaptiveAKNN(normals,points, k1, k2, rPos);
else
{
// create panorama
fbr::panorama fPanorama(width, height, fbr::EQUIRECTANGULAR, 1, 0, fbr::EXTENDED);
fPanorama.createPanorama(scan2mat(scan));
// the range image has to be converted from float to uchar
img = fPanorama.getRangeImage();
img = float2uchar(img, 0, 0.0);
if(ntype == PANORAMA)
calculateNormalsPANORAMA(normals,points,fPanorama.getExtendedMap(), rPos);
else if(ntype == PANORAMA_FAST)
cout << "PANORAMA_FAST is not working yet" << endl;
// calculateNormalsFAST(normals,points,img,fPanorama.getExtendedMap());
}
// pose file (repeated for the number of segments
writePoseFiles(normdir, rPos, rPosTheta, scanNumber);
// scan files for all segments
writeScanFiles(normdir, points,normals,scanNumber);
scanNumber++;
}
// shutdown everything
if (scanserver)
ClientInterface::destroy();
else
Scan::closeDirectory();
cout << "Normal program end" << endl;
return 0;
}

View file

@ -5,7 +5,7 @@ else(WIN32)
endif(WIN32) endif(WIN32)
set(SCANIO_LIBNAMES set(SCANIO_LIBNAMES
uos uosr uos_rgb uos_rrgbt ks ks_rgb riegl_txt riegl_rgb rts velodyne uos uosr uos_rgb uos_rrgbt xyzr ply ks ks_rgb riegl_txt riegl_rgb rts velodyne
) )
if(WITH_RIVLIB) if(WITH_RIVLIB)

227
src/scanio/scan_io_ply.cc Normal file
View file

@ -0,0 +1,227 @@
/*
* scan_io_ply implementation
*
* Copyright (C) Dorit Borrmann, Thomas Escher, Kai Lingemann, Andreas Nuechter
*
* Released under the GPL version 3.
*
*/
/**
* @file
* @brief Implementation of reading 3D scans
* @author Dorit Borrmann. Jacobs University Bremen, Germany.
* @author Kai Lingemann. Inst. of CS, University of Osnabrueck, Germany.
* @author Andreas Nuechter. Jacobs University Bremen, Germany.
* @author Thomas Escher. Inst. of CS, University of Osnabrueck, Germany.
*/
#include "scanio/scan_io_ply.h"
#include "slam6d/point.h"
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <vector>
#include <string.h>
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
#include "slam6d/globals.icc"
#define DATA_PATH_PREFIX "scan"
#define DATA_PATH_SUFFIX ".ply"
std::list<std::string> ScanIO_ply::readDirectory(const char* dir_path,
unsigned int start,
unsigned int end)
{
std::list<std::string> identifiers;
for (unsigned int i = start; i <= end; ++i) {
// identifier is /d/d/d (000-999)
std::string identifier(to_string(i,3));
// scan consists of data (.3d) and pose (.pose) files
path data(dir_path);
data /= path(std::string(DATA_PATH_PREFIX) + identifier + DATA_PATH_SUFFIX);
// stop if part of a scan is missing or end by absence is detected
if (!exists(data))
break;
identifiers.push_back(identifier);
}
return identifiers;
}
void ScanIO_ply::readPose(const char* dir_path,
const char* identifier,
double* pose)
{
for (unsigned int i = 0; i < 6; ++i) pose[i] = 0.0;
}
bool ScanIO_ply::supports(IODataType type)
{
return !!(type & (DATA_XYZ | DATA_REFLECTANCE | DATA_RGB));
}
void ScanIO_ply::readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation)
{
unsigned int i;
// error handling
path data_path(dir_path);
data_path /= path(std::string(DATA_PATH_PREFIX) +
identifier + DATA_PATH_SUFFIX);
if(!exists(data_path))
throw std::runtime_error(std::string("There is no scan file for [")
+ identifier + "] in [" + dir_path + "]");
// open data file
ifstream data_file;
data_file.open(data_path);
data_file.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
if(xyz != 0 && rgb != 0 && reflectance != 0) {
// read ply file
bool binary = false;
char dummy[256];
char str[20]; // whatever size
double matrix[16];
int matrixPos = 0;
int nr;
float d1,d2,d3,d4;
// header
int counter = -2;
do {
if (counter > -2) counter++;
if (data_file.good()) {
data_file.getline(dummy, 255);
}
if (strncmp(dummy, "format", 6) == 0) {
if (dummy[7] == 'a') binary = false;
else if (dummy[7] == 'b') binary = true;
else { cerr << "Don't recognize the format!" << endl; exit(1); }
}
else if (strncmp(dummy, "element vertex", 14) == 0) {
sscanf(dummy,"%s %*s %d",str,&nr);
counter++;
}
else if (strncmp(dummy, "matrix", 6) == 0) {
sscanf(dummy,"%s %f %f %f %f", str, &d1, &d2, &d3, &d4);
matrix[matrixPos++] = d1;
matrix[matrixPos++] = d2;
matrix[matrixPos++] = d3;
matrix[matrixPos++] = d4;
}
} while (!(strncmp(dummy, "end_header",10) == 0 || !data_file.good()));
if (matrixPos > 0) {
double rPosTheta[3];
double rPos[3];
Matrix4ToEuler(matrix, rPosTheta, rPos);
}
for (int i=0; i < nr; i++) {
Point p;
float data, confidence, intensity;
float dummy;
int r, g, b;
if (!binary) {
switch(counter) {
case 6:
case 12:
data_file >> p.z >> p.y >> p.x >> r >> g >> b;
break;
case 9:
data_file >> p.z >> p.y >> p.x
>> dummy >> dummy >> dummy
>> r >> g >> b;
break;
default:
data_file >> p.z >> p.x >> p.y >> confidence >> intensity;
break;
}
if(counter == 6 || counter == 9 || counter == 12) {
p.rgb[0] = (char)r;
p.rgb[1] = (char)g;
p.rgb[2] = (char)b;
} else {
p.reflectance = intensity;
}
} else {
data_file.read((char*)&data, sizeof(float));
p.z = (double)data;
data_file.read((char*)&data, sizeof(float));
p.x = (double)data;
data_file.read((char*)&data, sizeof(float));
p.y = (double)data;
data_file.read((char*)&confidence, sizeof(float));
data_file.read((char*)&intensity, sizeof(float));
}
reflectance->push_back(p.reflectance);
xyz->push_back(p.x * 100);
xyz->push_back(p.y * 100);
xyz->push_back(p.z * 100);
rgb->push_back(static_cast<unsigned char>(p.rgb[0]));
rgb->push_back(static_cast<unsigned char>(p.rgb[1]));
rgb->push_back(static_cast<unsigned char>(p.rgb[2]));
}
}
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) ScanIO* create()
#else
extern "C" ScanIO* create()
#endif
{
return new ScanIO_ply;
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) void destroy(ScanIO *sio)
#else
extern "C" void destroy(ScanIO *sio)
#endif
{
delete sio;
}
#ifdef _MSC_VER
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
return TRUE;
}
#endif

194
src/scanio/scan_io_xyzr.cc Normal file
View file

@ -0,0 +1,194 @@
/*
* scan_io_xyzr implementation
*
* Copyright (C) Andreas Nuechter
*
* Released under the GPL version 3.
*
*/
/**
* @file scan_io_xyzr.cc
* @brief IO of a 3D scan in xyz file format plus a reflectance/intensity
* @author Andreas Nuechter. Jacobs University Bremen, Germany.
*/
#include "scanio/scan_io_xyzr.h"
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <vector>
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
#include "slam6d/globals.icc"
#define DATA_PATH_PREFIX "scan"
#define DATA_PATH_SUFFIX ".3d"
#define POSE_PATH_PREFIX "scan"
#define POSE_PATH_SUFFIX ".pose"
std::list<std::string> ScanIO_xyzr::readDirectory(const char* dir_path,
unsigned int start,
unsigned int end)
{
std::list<std::string> identifiers;
for(unsigned int i = start; i <= end; ++i) {
// identifier is /d/d/d (000-999)
std::string identifier(to_string(i,3));
// scan consists of data (.3d) and pose (.pose) files
path data(dir_path);
data /= path(std::string(DATA_PATH_PREFIX) + identifier + DATA_PATH_SUFFIX);
path pose(dir_path);
pose /= path(std::string(POSE_PATH_PREFIX) + identifier + POSE_PATH_SUFFIX);
// stop if part of a scan is missing or end by absence is detected
if(!exists(data) || !exists(pose))
break;
identifiers.push_back(identifier);
}
return identifiers;
}
void ScanIO_xyzr::readPose(const char* dir_path,
const char* identifier,
double* pose)
{
unsigned int i;
path pose_path(dir_path);
pose_path /= path(std::string(POSE_PATH_PREFIX)
+ identifier +
POSE_PATH_SUFFIX);
if(!exists(pose_path))
throw std::runtime_error(std::string("There is no pose file for [")
+ identifier + "] in [" + dir_path + "]");
// open pose file
ifstream pose_file(pose_path);
// if the file is open, read contents
if(pose_file.good()) {
// read 6 plain doubles
for(i = 0; i < 6; ++i) pose_file >> pose[i];
pose_file.close();
// convert angles from deg to rad
for(i = 3; i < 6; ++i) pose[i] = rad(pose[i]);
} else {
throw std::runtime_error(std::string("Pose file could not be opened for [")
+ identifier + "] in ["
+ dir_path + "]");
}
}
bool ScanIO_xyzr::supports(IODataType type)
{
return !!(type & ( DATA_REFLECTANCE | DATA_XYZ ));
}
void ScanIO_xyzr::readScan(const char* dir_path,
const char* identifier,
PointFilter& filter,
std::vector<double>* xyz,
std::vector<unsigned char>* rgb,
std::vector<float>* reflectance,
std::vector<float>* temperature,
std::vector<float>* amplitude,
std::vector<int>* type,
std::vector<float>* deviation)
{
unsigned int i;
// error handling
path data_path(dir_path);
data_path /= path(std::string(DATA_PATH_PREFIX)
+ identifier
+ DATA_PATH_SUFFIX);
if(!exists(data_path))
throw std::runtime_error(std::string("There is no scan file for [")
+ identifier + "] in ["
+ dir_path + "]");
if(xyz != 0) {
// open data file
ifstream data_file(data_path);
data_file.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
// overread the first line ignoring the header information
char dummy[255];
data_file.getline(dummy, 255);
// read points and reflectance/intensity/temperature value
double point[3];
float reflection;
while(data_file.good()) {
try {
for(i = 0; i < 3; ++i) data_file >> point[i];
/*
point[0] -= 485531.0;
point[1] -= 5882078.400;
point[2] -= 52;
*/
std::swap(point[2], point[1]);
data_file >> reflection;
} catch(std::ios_base::failure& e) {
break;
}
// apply filter then insert point and reflectance
if(filter.check(point)) {
for(i = 0; i < 3; ++i) xyz->push_back(point[i]);
reflectance->push_back(reflection);
}
}
data_file.close();
}
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) ScanIO* create()
#else
extern "C" ScanIO* create()
#endif
{
return new ScanIO_xyzr;
}
/**
* class factory for object construction
*
* @return Pointer to new object
*/
#ifdef _MSC_VER
extern "C" __declspec(dllexport) void destroy(ScanIO *sio)
#else
extern "C" void destroy(ScanIO *sio)
#endif
{
delete sio;
}
#ifdef _MSC_VER
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
return TRUE;
}
#endif

View file

@ -1,10 +1,12 @@
IF(WITH_SEGMENTATION) IF(WITH_SEGMENTATION)
IF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
add_executable(scan2segments scan2segments.cc ../slam6d/fbr/fbr_global.cc) add_executable(scan2segments scan2segments.cc ../slam6d/fbr/fbr_global.cc)
target_link_libraries(scan2segments scan ANN fbr_cv_io fbr_panorama fbr_feature fbr_feature_matcher fbr_registration ${Boost_LIBRARIES} ${OpenCV_LIBS})
ELSE(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
MESSAGE("OpenCV Version > 2.2 required for scan2segmentation")
ENDIF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
add_executable(fhsegmentation fhsegmentation.cc FHGraph.cc disjoint-set.cc segment-graph.cc) add_executable(fhsegmentation fhsegmentation.cc FHGraph.cc disjoint-set.cc segment-graph.cc)
FIND_PACKAGE(OpenCV REQUIRED)
target_link_libraries(scan2segments scan ANN fbr_cv_io fbr_panorama fbr_feature fbr_feature_matcher fbr_registration ${Boost_LIBRARIES} ${OpenCV_LIBS})
target_link_libraries(fhsegmentation scan ANN ${Boost_LIBRARIES} ${OpenCV_LIBS}) target_link_libraries(fhsegmentation scan ANN ${Boost_LIBRARIES} ${OpenCV_LIBS})

View file

@ -1,4 +1,4 @@
SET(SHOW_LIBS glui scan ANN ${OPENGL_LIBRARIES}) SET(SHOW_LIBS glui scan ANN ${OPENGL_LIBRARIES} normals newmat)
IF(WIN32) IF(WIN32)
IF( CMAKE_SIZEOF_VOID_P EQUAL 8 ) IF( CMAKE_SIZEOF_VOID_P EQUAL 8 )
SET(SHOW_LIBS ${SHOW_LIBS} ${CMAKE_SOURCE_DIR}/3rdparty/windows/x64/freeglut.lib XGetopt) SET(SHOW_LIBS ${SHOW_LIBS} ${CMAKE_SOURCE_DIR}/3rdparty/windows/x64/freeglut.lib XGetopt)

View file

@ -686,7 +686,9 @@ shortpointrep* compactTree::createPoints(lint length) {
shortpointrep *points = alloc->allocate<shortpointrep> (POINTDIM*length); shortpointrep *points = alloc->allocate<shortpointrep> (POINTDIM*length);
return points; return points;
} }
void compactTree::deserialize(std::string filename ) {
void compactTree::deserialize(std::string filename)
{
char buffer[sizeof(float) * 20]; char buffer[sizeof(float) * 20];
float *p = reinterpret_cast<float*>(buffer); float *p = reinterpret_cast<float*>(buffer);

View file

@ -160,18 +160,6 @@ ScanColorManager::ScanColorManager(unsigned int _buckets, PointType type, bool a
case Scan::ELCH: case Scan::ELCH:
glColor4d(0.0, 1.0,0.0, 1.0); glColor4d(0.0, 1.0,0.0, 1.0);
break; break;
case Scan::LOOPTORO:
glColor4d(0.0, 0.0, 1.0, 1.0);
break;
case Scan::LOOPHOGMAN:
glColor4d(0.0, 1.0, 1.0, 1.0);
break;
case Scan::GRAPHTORO:
glColor4d(1.0, 0.0, 1.0, 1.0);
break;
case Scan::GRAPHHOGMAN:
glColor4d(1.0, 1.0, 0.0, 1.0);
break;
default: default:
glColor4d(1.0, 1.0, 1.0, 1.0); glColor4d(1.0, 1.0, 1.0, 1.0);
break; break;

View file

@ -626,9 +626,7 @@ void setResetView(int origin) {
// set origin to the center of mass of all scans // set origin to the center of mass of all scans
for (size_t i = 0; i < octpts.size(); ++i) { for (size_t i = 0; i < octpts.size(); ++i) {
vector <sfloat*> points; vector <sfloat*> points;
#ifdef USE_COMPACT_TREE #ifndef USE_COMPACT_TREE
((compactTree*)octpts[i])->AllPoints( points );
#else
BOctTree<sfloat>* cur_tree = ((Show_BOctTree<sfloat>*)octpts[i])->getTree(); BOctTree<sfloat>* cur_tree = ((Show_BOctTree<sfloat>*)octpts[i])->getTree();
cur_tree->AllPoints( points ); cur_tree->AllPoints( points );
#endif #endif
@ -849,8 +847,6 @@ void initShow(int argc, char **argv){
string scanFileName = dir + "scan" + to_string(start,3) + ".oct"; string scanFileName = dir + "scan" + to_string(start,3) + ".oct";
cout << "Getting point information from " << scanFileName << endl; cout << "Getting point information from " << scanFileName << endl;
cout << "Attention! All subsequent oct-files must be of the same type!" << endl; cout << "Attention! All subsequent oct-files must be of the same type!" << endl;
pointtype = BOctTree<sfloat>::readType(scanFileName);
} }
scan_dir = dir; scan_dir = dir;
@ -893,7 +889,7 @@ void initShow(int argc, char **argv){
cout << "Creating display octrees.." << endl; cout << "Creating display octrees.." << endl;
#endif #endif
if(loadOct) cout << "Loading octtrees from file where possible instead of creating them from scans." << endl; if (loadOct) cout << "Loading octtrees from file where possible instead of creating them from scans." << endl;
// for managed scans the input phase needs to know how much it can handle // for managed scans the input phase needs to know how much it can handle
std::size_t free_mem = 0; std::size_t free_mem = 0;
@ -907,6 +903,12 @@ void initShow(int argc, char **argv){
#ifdef USE_COMPACT_TREE // FIXME: change compact tree, then this case can be removed #ifdef USE_COMPACT_TREE // FIXME: change compact tree, then this case can be removed
compactTree* tree; compactTree* tree;
try { try {
if (loadOct) {
string sfName = dir + "scan" + to_string(i,3) + ".oct";
cout << "Load " << sfName;
tree = new compactTree(sfName, cm);
cout << " done." << endl;
} else {
if (red > 0) { // with reduction, only xyz points if (red > 0) { // with reduction, only xyz points
DataXYZ xyz_r(scan->get("xyz reduced show")); DataXYZ xyz_r(scan->get("xyz reduced show"));
tree = new compactTree(PointerArray<double>(xyz_r).get(), xyz_r.size(), voxelSize, pointtype, cm); tree = new compactTree(PointerArray<double>(xyz_r).get(), xyz_r.size(), voxelSize, pointtype, cm);
@ -914,7 +916,13 @@ void initShow(int argc, char **argv){
sfloat** pts = pointtype.createPointArray<sfloat>(scan); sfloat** pts = pointtype.createPointArray<sfloat>(scan);
unsigned int nrpts = scan->size<DataXYZ>("xyz"); unsigned int nrpts = scan->size<DataXYZ>("xyz");
tree = new compactTree(pts, nrpts, voxelSize, pointtype, cm); tree = new compactTree(pts, nrpts, voxelSize, pointtype, cm);
for(unsigned int i = 0; i < nrpts; ++i) delete[] pts[i]; delete[] pts; for(unsigned int i = 0; i < nrpts; ++i) delete[] pts[i];
delete[] pts;
if (saveOct) {
string sfName = dir + "scan" + to_string(i,3) + ".oct";
tree->serialize(sfName);
}
}
} }
} catch(...) { } catch(...) {
cout << "Scan " << i << " could not be loaded into memory, stopping here." << endl; cout << "Scan " << i << " could not be loaded into memory, stopping here." << endl;

View file

@ -1,7 +1,6 @@
### TOOLS ### TOOLS
IF(WITH_TOOLS) IF(WITH_TOOLS)
FIND_PACKAGE(OpenCV REQUIRED)
### SCAN_RED ### SCAN_RED
add_executable(scan_red scan_red.cc fbr/fbr_global.cc fbr/panorama.cc fbr/scan_cv.cc) add_executable(scan_red scan_red.cc fbr/fbr_global.cc fbr/panorama.cc fbr/scan_cv.cc)
@ -55,13 +54,14 @@ IF(WITH_TOOLS)
target_link_libraries(riegl2frames XGetopt ${Boost_LIBRARIES}) target_link_libraries(riegl2frames XGetopt ${Boost_LIBRARIES})
target_link_libraries(toGlobal XGetopt ${Boost_LIBRARIES}) target_link_libraries(toGlobal XGetopt ${Boost_LIBRARIES})
ENDIF(WIN32) ENDIF(WIN32)
ENDIF(WITH_TOOLS) ENDIF(WITH_TOOLS)
### SCANLIB ### SCANLIB
SET(SCANLIB_SRCS SET(SCANLIB_SRCS
kd.cc kdManaged.cc kdMeta.cc graphSlam6D.cc kd.cc kdManaged.cc kdMeta.cc graphSlam6D.cc
graph.cc icp6Dapx.cc icp6D.cc icp6Dsvd.cc graph.cc icp6D.cc icp6Dapx.cc icp6Dsvd.cc
icp6Dortho.cc icp6Dquat.cc icp6Dhelix.cc icp6Dlumeuler.cc icp6Dortho.cc icp6Dquat.cc icp6Dhelix.cc icp6Dlumeuler.cc
icp6Dlumquat.cc icp6Ddual.cc lum6Deuler.cc lum6Dquat.cc icp6Dlumquat.cc icp6Ddual.cc lum6Deuler.cc lum6Dquat.cc
ghelix6DQ2.cc gapx6D.cc ann_kd.cc elch6D.cc ghelix6DQ2.cc gapx6D.cc ann_kd.cc elch6D.cc
@ -77,7 +77,9 @@ endif(WITH_METRICS)
add_library(scan STATIC ${SCANLIB_SRCS}) add_library(scan STATIC ${SCANLIB_SRCS})
target_link_libraries(scan scanclient scanio) FIND_PACKAGE(OpenCV REQUIRED)
target_link_libraries(scan scanclient scanio normals)
IF(UNIX) IF(UNIX)
target_link_libraries(scan dl) target_link_libraries(scan dl)

View file

@ -242,6 +242,8 @@ DataPointer BasicScan::get(const std::string& identifier)
if(identifier == "amplitude") get(DATA_AMPLITUDE); else if(identifier == "amplitude") get(DATA_AMPLITUDE); else
if(identifier == "type") get(DATA_TYPE); else if(identifier == "type") get(DATA_TYPE); else
if(identifier == "deviation") get(DATA_DEVIATION); else if(identifier == "deviation") get(DATA_DEVIATION); else
// normals on demand
if(identifier == "normal") calcNormalsOnDemand(); else
// reduce on demand // reduce on demand
if(identifier == "xyz reduced") calcReducedOnDemand(); else if(identifier == "xyz reduced") calcReducedOnDemand(); else
if(identifier == "xyz reduced original") calcReducedOnDemand(); else if(identifier == "xyz reduced original") calcReducedOnDemand(); else
@ -326,12 +328,20 @@ void BasicScan::createSearchTreePrivate()
void BasicScan::calcReducedOnDemandPrivate() void BasicScan::calcReducedOnDemandPrivate()
{ {
// create reduced points and transform to initial position, save a copy of this for SearchTree // create reduced points and transform to initial position,
// save a copy of this for SearchTree
calcReducedPoints(); calcReducedPoints();
transformReduced(transMatOrg); transformReduced(transMatOrg);
copyReducedToOriginal(); copyReducedToOriginal();
} }
void BasicScan::calcNormalsOnDemandPrivate()
{
// create normals
calcNormals();
}
void BasicScan::createANNTree() void BasicScan::createANNTree()
{ {
// TODO: metrics // TODO: metrics

View file

@ -1,14 +1,11 @@
IF(WITH_FBR)
FIND_PACKAGE(OpenCV REQUIRED)
SET(FBR_IO_SRC scan_cv.cc) SET(FBR_IO_SRC scan_cv.cc)
add_library(fbr_cv_io STATIC ${FBR_IO_SRC}) add_library(fbr_cv_io STATIC ${FBR_IO_SRC})
SET(FBR_PANORAMA_SRC panorama.cc) SET(FBR_PANORAMA_SRC panorama.cc)
#add_library(fbr_panorama STATIC ${FBR_PANORAMA_SRC})
add_library(fbr_panorama STATIC ${FBR_PANORAMA_SRC} fbr_global.cc) add_library(fbr_panorama STATIC ${FBR_PANORAMA_SRC} fbr_global.cc)
IF(WITH_FBR)
IF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
SET(FBR_FEATURE_SRC feature.cc) SET(FBR_FEATURE_SRC feature.cc)
add_library(fbr_feature STATIC ${FBR_FEATURE_SRC}) add_library(fbr_feature STATIC ${FBR_FEATURE_SRC})
@ -34,4 +31,7 @@ add_library(fbr_s SHARED ${FBR_SRC})
target_link_libraries(fbr_s scan_s ANN_s ${OpenCV_LIBS}) target_link_libraries(fbr_s scan_s ANN_s ${OpenCV_LIBS})
ENDIF(EXPORT_SHARED_LIBS) ENDIF(EXPORT_SHARED_LIBS)
ELSE(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
MESSAGE("OpenCV Version > 2.2 required for FBR")
ENDIF(OpenCV_VERSION_MAJOR GREATER 1 AND OpenCV_VERSION_MINOR GREATER 2)
ENDIF(WITH_FBR) ENDIF(WITH_FBR)

View file

@ -92,7 +92,8 @@ icp6D::icp6D(icp6Dminimizer *my_icp6Dminimizer, double max_dist_match,
* @param CurrentScan The current scan thas is to be matched * @param CurrentScan The current scan thas is to be matched
* @return The number of iterations done in this matching run * @return The number of iterations done in this matching run
*/ */
int icp6D::match(Scan* PreviousScan, Scan* CurrentScan) int icp6D::match(Scan* PreviousScan, Scan* CurrentScan,
PairingMode pairing_mode)
{ {
// If ICP shall not be applied, then just write // If ICP shall not be applied, then just write
// the identity matrix // the identity matrix
@ -148,7 +149,7 @@ int icp6D::match(Scan* PreviousScan, Scan* CurrentScan)
Scan::getPtPairsParallel(pairs, PreviousScan, CurrentScan, Scan::getPtPairsParallel(pairs, PreviousScan, CurrentScan,
thread_num, step, thread_num, step,
rnd, max_dist_match2, rnd, max_dist_match2,
sum, centroid_m, centroid_d); sum, centroid_m, centroid_d, pairing_mode);
n[thread_num] = (unsigned int)pairs[thread_num].size(); n[thread_num] = (unsigned int)pairs[thread_num].size();
@ -214,7 +215,7 @@ int icp6D::match(Scan* PreviousScan, Scan* CurrentScan)
vector<PtPair> pairs; vector<PtPair> pairs;
Scan::getPtPairs(&pairs, PreviousScan, CurrentScan, 0, rnd, Scan::getPtPairs(&pairs, PreviousScan, CurrentScan, 0, rnd,
max_dist_match2, ret, centroid_m, centroid_d); max_dist_match2, ret, centroid_m, centroid_d, pairing_mode);
// do we have enough point pairs? // do we have enough point pairs?
if (pairs.size() > 3) { if (pairs.size() > 3) {
@ -281,7 +282,7 @@ double icp6D::Point_Point_Error(Scan* PreviousScan, Scan* CurrentScan, double ma
Scan::getPtPairsParallel(pairs, PreviousScan, CurrentScan, Scan::getPtPairsParallel(pairs, PreviousScan, CurrentScan,
thread_num, step, thread_num, step,
rnd, sqr(max_dist_match), rnd, sqr(max_dist_match),
sum, centroid_m, centroid_d); sum, centroid_m, centroid_d, CLOSEST_POINT);
} }
@ -299,7 +300,8 @@ double icp6D::Point_Point_Error(Scan* PreviousScan, Scan* CurrentScan, double ma
double centroid_d[3] = {0.0, 0.0, 0.0}; double centroid_d[3] = {0.0, 0.0, 0.0};
vector<PtPair> pairs; vector<PtPair> pairs;
Scan::getPtPairs(&pairs, PreviousScan, CurrentScan, 0, rnd, sqr(max_dist_match),error, centroid_m, centroid_d); Scan::getPtPairs(&pairs, PreviousScan, CurrentScan, 0, rnd, sqr(max_dist_match),
error, centroid_m, centroid_d, CLOSEST_POINT);
// getPtPairs computes error as sum of squared distances // getPtPairs computes error as sum of squared distances
error = 0; error = 0;
@ -322,7 +324,7 @@ double icp6D::Point_Point_Error(Scan* PreviousScan, Scan* CurrentScan, double ma
* *
* @param allScans Contains all necessary scans. * @param allScans Contains all necessary scans.
*/ */
void icp6D::doICP(vector <Scan *> allScans) void icp6D::doICP(vector <Scan *> allScans, PairingMode pairing_mode)
{ {
double id[16]; double id[16];
M4identity(id); M4identity(id);
@ -346,12 +348,12 @@ void icp6D::doICP(vector <Scan *> allScans)
if (i > 0) { if (i > 0) {
if (meta) { if (meta) {
match(my_MetaScan, CurrentScan); match(my_MetaScan, CurrentScan, pairing_mode);
} else } else
if (cad_matching) { if (cad_matching) {
match(allScans[0], CurrentScan); match(allScans[0], CurrentScan, pairing_mode);
} else { } else {
match(PreviousScan, CurrentScan); match(PreviousScan, CurrentScan, pairing_mode);
} }
} }

View file

@ -9,9 +9,11 @@
/** @file /** @file
* @brief An optimized k-d tree implementation * @brief An optimized k-d tree implementation
* @author Andreas Nuechter. Institute of Computer Science, University of Osnabrueck, Germany. * @author Remus Dumitru. Jacobs University Bremen, Germany
* @author Kai Lingemann. Institute of Computer Science, University of Osnabrueck, Germany. * @author Corneliu-Claudiu Prodescu. Jacobs University Bremen, Germany
* @author Thomas Escher Institute of Computer Science, University of Osnabrueck, Germany. * @author Andreas Nuechter. Jacobs University Bremen, Germany.
* @author Kai Lingemann. Inst. of CS, University of Osnabrueck, Germany.
* @author Thomas Escher Inst. of CS, University of Osnabrueck, Germany.
*/ */
#ifdef _MSC_VER #ifdef _MSC_VER
@ -29,6 +31,8 @@ using std::endl;
using std::swap; using std::swap;
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
#include <limits>
#include <vector>
// KDtree class static variables // KDtree class static variables
template<class PointData, class AccessorData, class AccessorFunc> template<class PointData, class AccessorData, class AccessorFunc>
@ -59,7 +63,9 @@ KDtree::~KDtree()
* @param threadNum Thread number, for parallelization * @param threadNum Thread number, for parallelization
* @return Pointer to the closest point * @return Pointer to the closest point
*/ */
double *KDtree::FindClosest(double *_p, double maxdist2, int threadNum) const double *KDtree::FindClosest(double *_p,
double maxdist2,
int threadNum) const
{ {
params[threadNum].closest = 0; params[threadNum].closest = 0;
params[threadNum].closest_d2 = maxdist2; params[threadNum].closest_d2 = maxdist2;
@ -67,3 +73,57 @@ double *KDtree::FindClosest(double *_p, double maxdist2, int threadNum) const
_FindClosest(Void(), threadNum); _FindClosest(Void(), threadNum);
return params[threadNum].closest; return params[threadNum].closest;
} }
double *KDtree::FindClosestAlongDir(double *_p,
double *_dir,
double maxdist2,
int threadNum) const
{
params[threadNum].closest = NULL;
params[threadNum].closest_d2 = maxdist2;
params[threadNum].p = _p;
params[threadNum].dir = _dir;
_FindClosestAlongDir(Void(), threadNum);
return params[threadNum].closest;
}
vector<Point> KDtree::kNearestNeighbors(double *_p,
int k,
double sqRad2,
int threadNum) const
{
vector<Point> result;
params[threadNum].closest = 0;
params[threadNum].closest_d2 = sqRad2;
params[threadNum].p = _p;
params[threadNum].heap.clear();
_KNNSearch(Void(), threadNum);
while (k > 0 && params[threadNum].heap.empty() == false) {
Point pt = params[threadNum].heap.front().first;
result.push_back(pt);
std::pop_heap(params[threadNum].heap.begin(), params[threadNum].heap.end(), PointCompare());
params[threadNum].heap.pop_back();
k--;
}
return result;
}
vector<Point> KDtree::fixedRangeSearch(double *_p,
double sqRad2,
int threadNum) const
{
vector<Point> result;
params[threadNum].closest = 0;
params[threadNum].closest_d2 = sqRad2;
params[threadNum].p = _p;
params[threadNum].heap.clear();
_FixedRangeSearch(Void(), threadNum);
for (vector<std::pair<Point, double> >::iterator it = params[threadNum].heap.begin(); it != params[threadNum].heap.end(); ++it) {
result.push_back(it->first);
}
return result;
}

View file

@ -60,6 +60,16 @@ double* KDtreeManaged::FindClosest(double *_p, double maxdist2, int threadNum) c
return params[threadNum].closest; return params[threadNum].closest;
} }
double* KDtreeManaged::FindClosestAlongDir(double *_p, double *_dir, double maxdist2, int threadNum) const
{
params[threadNum].closest = NULL;
params[threadNum].closest_d2 = maxdist2;
params[threadNum].p = _p;
params[threadNum].dir = _dir;
_FindClosestAlongDir(*m_data, threadNum);
return params[threadNum].closest;
}
void KDtreeManaged::lock() void KDtreeManaged::lock()
{ {
boost::lock_guard<boost::mutex> lock(m_mutex_locking); boost::lock_guard<boost::mutex> lock(m_mutex_locking);

View file

@ -97,6 +97,16 @@ double* KDtreeMetaManaged::FindClosest(double *_p, double maxdist2, int threadNu
return params[threadNum].closest; return params[threadNum].closest;
} }
double* KDtreeMetaManaged::FindClosestAlongDir(double *_p, double *_dir, double maxdist2, int threadNum) const
{
params[threadNum].closest = NULL;
params[threadNum].closest_d2 = maxdist2;
params[threadNum].p = _p;
params[threadNum].dir = _dir;
_FindClosestAlongDir(m_data, threadNum);
return params[threadNum].closest;
}
void KDtreeMetaManaged::lock() void KDtreeMetaManaged::lock()
{ {
boost::lock_guard<boost::mutex> lock(m_mutex_locking); boost::lock_guard<boost::mutex> lock(m_mutex_locking);

View file

@ -46,18 +46,25 @@ PointType::PointType(unsigned int _types) : types(_types) {
pointdim = 3; pointdim = 3;
if (types & PointType::USE_REFLECTANCE) dimensionmap[1] = pointdim++; if (types & PointType::USE_REFLECTANCE) dimensionmap[1] = pointdim++;
if (types & PointType::USE_TEMPERATURE) dimensionmap[2] = pointdim++; if (types & PointType::USE_NORMAL) {
if (types & PointType::USE_AMPLITUDE) dimensionmap[3] = pointdim++; pointdim += 3;
if (types & PointType::USE_DEVIATION) dimensionmap[4] = pointdim++; dimensionmap[2] = pointdim;
if (types & PointType::USE_TYPE) dimensionmap[5] = pointdim++; }
if (types & PointType::USE_COLOR) dimensionmap[6] = pointdim++; if (types & PointType::USE_TEMPERATURE) dimensionmap[3] = pointdim++;
if (types & PointType::USE_TIME) dimensionmap[7] = pointdim++; if (types & PointType::USE_AMPLITUDE) dimensionmap[4] = pointdim++;
if (types & PointType::USE_INDEX) dimensionmap[8] = pointdim++; if (types & PointType::USE_DEVIATION) dimensionmap[5] = pointdim++;
if (types & PointType::USE_TYPE) dimensionmap[6] = pointdim++;
if (types & PointType::USE_COLOR) dimensionmap[7] = pointdim++;
if (types & PointType::USE_TIME) dimensionmap[8] = pointdim++;
if (types & PointType::USE_INDEX) dimensionmap[9] = pointdim++;
} }
bool PointType::hasReflectance() { bool PointType::hasReflectance() {
return hasType(USE_REFLECTANCE); return hasType(USE_REFLECTANCE);
} }
bool PointType::hasNormal() {
return hasType(USE_NORMAL);
}
bool PointType::hasTemperature() { bool PointType::hasTemperature() {
return hasType(USE_TEMPERATURE); return hasType(USE_TEMPERATURE);
} }
@ -116,18 +123,20 @@ unsigned int PointType::getType(unsigned int type) {
return dimensionmap[0]; return dimensionmap[0];
} else if (type == USE_REFLECTANCE) { } else if (type == USE_REFLECTANCE) {
return dimensionmap[1]; return dimensionmap[1];
} else if (type == USE_TEMPERATURE) { } else if (type == USE_NORMAL) {
return dimensionmap[2]; return dimensionmap[2];
} else if (type == USE_AMPLITUDE) { } else if (type == USE_TEMPERATURE) {
return dimensionmap[3]; return dimensionmap[3];
} else if (type == USE_DEVIATION) { } else if (type == USE_AMPLITUDE) {
return dimensionmap[4]; return dimensionmap[4];
} else if (type == USE_TYPE) { } else if (type == USE_DEVIATION) {
return dimensionmap[5]; return dimensionmap[5];
} else if (type == USE_COLOR) { } else if (type == USE_TYPE) {
return dimensionmap[6]; return dimensionmap[6];
} else if (type == USE_TIME) { } else if (type == USE_COLOR) {
return dimensionmap[7]; return dimensionmap[7];
} else if (type == USE_TIME) {
return dimensionmap[8];
} else { } else {
return 0; return 0;
} }
@ -155,14 +164,15 @@ bool PointType::hasType(unsigned int type) {
const unsigned int PointType::USE_NONE = 0; const unsigned int PointType::USE_NONE = 0;
const unsigned int PointType::USE_REFLECTANCE = 1; const unsigned int PointType::USE_REFLECTANCE = 1;
const unsigned int PointType::USE_TEMPERATURE = 2; const unsigned int PointType::USE_NORMAL = 2;
const unsigned int PointType::USE_AMPLITUDE = 4; const unsigned int PointType::USE_TEMPERATURE = 4;
const unsigned int PointType::USE_DEVIATION = 8; const unsigned int PointType::USE_AMPLITUDE = 8;
const unsigned int PointType::USE_HEIGHT = 16; const unsigned int PointType::USE_DEVIATION = 16;
const unsigned int PointType::USE_TYPE = 32; const unsigned int PointType::USE_HEIGHT = 32;
const unsigned int PointType::USE_COLOR = 64; const unsigned int PointType::USE_TYPE = 64;
const unsigned int PointType::USE_TIME = 128; const unsigned int PointType::USE_COLOR = 128;
const unsigned int PointType::USE_INDEX = 256; const unsigned int PointType::USE_TIME = 256;
const unsigned int PointType::USE_INDEX = 512;
void PointType::useScan(Scan* scan) void PointType::useScan(Scan* scan)

View file

@ -17,6 +17,8 @@
#include "slam6d/Boctree.h" #include "slam6d/Boctree.h"
#include "slam6d/globals.icc" #include "slam6d/globals.icc"
#include "normals/normals.h"
#ifdef WITH_METRICS #ifdef WITH_METRICS
#include "slam6d/metrics.h" #include "slam6d/metrics.h"
#endif #endif
@ -145,7 +147,9 @@ void Scan::toGlobal() {
*/ */
void Scan::createSearchTree() void Scan::createSearchTree()
{ {
// multiple threads will call this function at the same time because they all work on one pair of Scans, just let the first one (who sees a nullpointer) do the creation // multiple threads will call this function at the same time because they
// all work on one pair of Scans, just let the first one (who sees a nullpointer)
// do the creation
boost::lock_guard<boost::mutex> lock(m_mutex_create_tree); boost::lock_guard<boost::mutex> lock(m_mutex_create_tree);
if(kd != 0) return; if(kd != 0) return;
@ -165,7 +169,9 @@ void Scan::createSearchTree()
void Scan::calcReducedOnDemand() void Scan::calcReducedOnDemand()
{ {
// multiple threads will call this function at the same time because they all work on one pair of Scans, just let the first one (who sees count as zero) do the reduction // multiple threads will call this function at the same time
// because they all work on one pair of Scans,
// just let the first one (who sees count as zero) do the reduction
boost::lock_guard<boost::mutex> lock(m_mutex_reduction); boost::lock_guard<boost::mutex> lock(m_mutex_reduction);
if(m_has_reduced) return; if(m_has_reduced) return;
@ -182,6 +188,17 @@ void Scan::calcReducedOnDemand()
#endif //WITH_METRICS #endif //WITH_METRICS
} }
void Scan::calcNormalsOnDemand()
{
// multiple threads will call this function at the same time
// because they all work on one pair of Scans,
// just let the first one (who sees count as zero) do the reduction
boost::lock_guard<boost::mutex> lock(m_mutex_normals);
if(m_has_normals) return;
calcNormalsOnDemandPrivate();
m_has_normals = true;
}
void Scan::copyReducedToOriginal() void Scan::copyReducedToOriginal()
{ {
#ifdef WITH_METRICS #ifdef WITH_METRICS
@ -223,6 +240,32 @@ void Scan::copyOriginalToReduced()
} }
/**
* Computes normals for all points
*/
void Scan::calcNormals()
{
cout << "calcNormals" << endl;
DataXYZ xyz(get("xyz"));
DataNormal xyz_normals(create("normal", sizeof(double)*3*xyz.size()));
if(xyz.size() == 0)
throw runtime_error("Could not calculate reduced points, XYZ data is empty");
vector<Point> points;
points.reserve(xyz.size());
vector<Point> normals;
normals.reserve(xyz.size());
for(unsigned int j = 0; j < xyz.size(); j++) {
points.push_back(Point(xyz[j][0], xyz[j][1], xyz[j][2]));
}
const int K_NEIGHBOURS = 10;
calculateNormalsApxKNN(normals, points, K_NEIGHBOURS, get_rPos(), 1.0);
for (unsigned int i = 0; i < normals.size(); ++i) {
xyz_normals[i][0] = normals[i].x;
xyz_normals[i][1] = normals[i].y;
xyz_normals[i][2] = normals[i].z;
}
}
/** /**
* Computes an octtree of the current scan, then getting the * Computes an octtree of the current scan, then getting the
@ -236,17 +279,23 @@ void Scan::calcReducedPoints()
// get xyz to start the scan load, separated here for time measurement // get xyz to start the scan load, separated here for time measurement
DataXYZ xyz(get("xyz")); DataXYZ xyz(get("xyz"));
DataReflectance reflectance(get("reflectance")); DataXYZ xyz_normals(get(""));
if(xyz.size() == 0) if (reduction_pointtype.hasNormal()) {
throw runtime_error("Could not calculate reduced points, XYZ data is empty"); DataXYZ my_xyz_normals(get("normal"));
xyz_normals = my_xyz_normals;
}
DataReflectance reflectance(get(""));
if (reduction_pointtype.hasReflectance()) {
DataReflectance my_reflectance(get("reflectance"));
reflectance = my_reflectance;
}
if (reflectance.size()==0) { #ifdef WITH_METRICS
ClientMetric::scan_load_time.end(t);
Timer tl = ClientMetric::calc_reduced_points_time.start();
#endif //WITH_METRICS
// no reduction needed
// copy vector of points to array of points to avoid
// further copying
if(reduction_voxelSize <= 0.0) { if(reduction_voxelSize <= 0.0) {
// copy the points // copy the points
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*xyz.size())); DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*xyz.size()));
@ -255,12 +304,43 @@ void Scan::calcReducedPoints()
xyz_reduced[i][j] = xyz[i][j]; xyz_reduced[i][j] = xyz[i][j];
} }
} }
if (reduction_pointtype.hasReflectance()) {
DataReflectance reflectance_reduced(create("reflectance reduced", sizeof(float)*reflectance.size()));
for(unsigned int i = 0; i < xyz.size(); ++i) {
reflectance_reduced[i] = reflectance[i];
}
}
if (reduction_pointtype.hasNormal()) {
DataNormal normal_reduced(create("normal reduced", sizeof(double)*3*xyz.size()));
for(unsigned int i = 0; i < xyz.size(); ++i) {
for(unsigned int j = 0; j < 3; ++j) {
normal_reduced[i][j] = xyz_normals[i][j];
}
}
}
} else { } else {
double **xyz_in = new double*[xyz.size()];
for (unsigned int i = 0; i < xyz.size(); ++i) {
xyz_in[i] = new double[reduction_pointtype.getPointDim()];
unsigned int j = 0;
for (; j < 3; ++j)
xyz_in[i][j] = xyz[i][j];
if (reduction_pointtype.hasReflectance())
xyz_in[i][j++] = reflectance[i];
if (reduction_pointtype.hasNormal())
for (unsigned int l = 0; l < 3; ++l)
xyz_in[i][j] = xyz_normals[i][l];
}
// start reduction // start reduction
// build octree-tree from CurrentScan // build octree-tree from CurrentScan
// put full data into the octtree // put full data into the octtree
BOctTree<double> *oct = new BOctTree<double>(PointerArray<double>(xyz).get(), BOctTree<double> *oct = new BOctTree<double>(xyz_in,
xyz.size(), reduction_voxelSize, reduction_pointtype); xyz.size(),
reduction_voxelSize,
reduction_pointtype);
vector<double*> center; vector<double*> center;
center.clear(); center.clear();
@ -277,96 +357,32 @@ void Scan::calcReducedPoints()
// storing it as reduced scan // storing it as reduced scan
unsigned int size = center.size(); unsigned int size = center.size();
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*size)); DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*size));
DataReflectance reflectance_reduced(get(""));
DataNormal normal_reduced(get(""));
if (reduction_pointtype.hasReflectance()) {
DataReflectance my_reflectance_reduced(create("reflectance reduced",
sizeof(float)*size));
reflectance_reduced = my_reflectance_reduced;
}
if (reduction_pointtype.hasNormal()) {
DataNormal my_normal_reduced(create("normal reduced", sizeof(double)*3*size));
normal_reduced = my_normal_reduced;
}
for(unsigned int i = 0; i < size; ++i) { for(unsigned int i = 0; i < size; ++i) {
for(unsigned int j = 0; j < 3; ++j) { unsigned int j = 0;
for (; j < 3; ++j)
xyz_reduced[i][j] = center[i][j]; xyz_reduced[i][j] = center[i][j];
if (reduction_pointtype.hasReflectance())
reflectance_reduced[i] = center[i][j++];
if (reduction_pointtype.hasNormal())
for (unsigned int l = 0; l < 3; ++l)
normal_reduced[i][l] = center[i][j++];
} }
} }
delete oct;
}
} else {
if(xyz.size() != reflectance.size())
throw runtime_error("Could not calculate reduced reflectance, reflectance size is different from points size");
double **xyz_reflectance = new double*[xyz.size()];
for (unsigned int i = 0; i < xyz.size(); ++i) {
xyz_reflectance[i] = new double[4];
for (unsigned int j = 0; j < 3; ++j)
xyz_reflectance[i][j] = xyz[i][j];
xyz_reflectance[i][3] = reflectance[i];
}
#ifdef WITH_METRICS
ClientMetric::scan_load_time.end(t);
Timer tl = ClientMetric::calc_reduced_points_time.start();
#endif //WITH_METRICS
// no reduction needed
// copy vector of points to array of points to avoid
// further copying
if(reduction_voxelSize <= 0.0) {
// copy the points
if (reduction_pointtype.hasReflectance()) {
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*xyz.size()));
DataReflectance reflectance_reduced(create("reflectance reduced", sizeof(double)*reflectance.size()));
for(unsigned int i = 0; i < xyz.size(); ++i) {
for(unsigned int j = 0; j < 3; ++j)
xyz_reduced[i][j] = xyz[i][j];
reflectance_reduced[i] = reflectance[i];
}
} else {
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*xyz.size()));
for(unsigned int i = 0; i < xyz.size(); ++i) {
for(unsigned int j = 0; j < 3; ++j) {
xyz_reduced[i][j] = xyz[i][j];
}
}
}
} else {
// start reduction
// build octree-tree from CurrentScan
// put full data into the octtree
BOctTree<double> *oct = new BOctTree<double>(xyz_reflectance, xyz.size(), reduction_voxelSize, reduction_pointtype);
vector<double*> reduced;
reduced.clear();
if (reduction_nrpts > 0) {
if (reduction_nrpts == 1) {
oct->GetOctTreeRandom(reduced);
} else {
oct->GetOctTreeRandom(reduced, reduction_nrpts);
}
} else {
oct->GetOctTreeCenter(reduced);
}
// storing it as reduced scan
unsigned int size = reduced.size();
if (reduction_pointtype.hasReflectance()) {
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*size));
for(unsigned int i = 0; i < size; ++i) {
for(unsigned int j = 0; j < 3; ++j) {
xyz_reduced[i][j] = reduced[i][j];
}
}
DataReflectance reflectance_reduced(create("reflectance reduced", sizeof(float)*size));
for(unsigned int i = 0; i < size; ++i)
reflectance_reduced[i] = reduced[i][3];
} else {
DataXYZ xyz_reduced(create("xyz reduced", sizeof(double)*3*size));
for(unsigned int i = 0; i < size; ++i)
for(unsigned int j = 0; j < 3; ++j)
xyz_reduced[i][j] = reduced[i][j];
}
delete oct;
}
for (unsigned int i = 0; i < xyz.size(); ++i) {
delete[] xyz_reflectance[i];
}
delete[] xyz_reflectance;
#ifdef WITH_METRICS #ifdef WITH_METRICS
ClientMetric::calc_reduced_points_time.end(tl); ClientMetric::calc_reduced_points_time.end(tl);
#endif //WITH_METRICS #endif //WITH_METRICS
}
} }
@ -399,7 +415,7 @@ void Scan::transformAll(const double alignxf[16])
{ {
DataXYZ xyz(get("xyz")); DataXYZ xyz(get("xyz"));
unsigned int i=0 ; unsigned int i=0 ;
// #pragma omp parallel for // #pragma omp parallel for
for(; i < xyz.size(); ++i) { for(; i < xyz.size(); ++i) {
transform3(alignxf, xyz[i]); transform3(alignxf, xyz[i]);
} }
@ -420,6 +436,12 @@ void Scan::transformReduced(const double alignxf[16])
transform3(alignxf, xyz_reduced[i]); transform3(alignxf, xyz_reduced[i]);
} }
DataNormal normal_reduced(get("normal reduced"));
for (unsigned int i = 0; i < normal_reduced.size(); ++i) {
transform3normal(alignxf, normal_reduced[i]);
}
#ifdef WITH_METRICS #ifdef WITH_METRICS
ClientMetric::transform_time.end(t); ClientMetric::transform_time.end(t);
#endif //WITH_METRICS #endif //WITH_METRICS
@ -754,7 +776,7 @@ void Scan::getPtPairs(vector <PtPair> *pairs,
Scan* Source, Scan* Target, Scan* Source, Scan* Target,
int thread_num, int thread_num,
int rnd, double max_dist_match2, double &sum, int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d) double *centroid_m, double *centroid_d, PairingMode pairing_mode)
{ {
// initialize centroids // initialize centroids
for(unsigned int i = 0; i < 3; ++i) { for(unsigned int i = 0; i < 3; ++i) {
@ -764,10 +786,12 @@ void Scan::getPtPairs(vector <PtPair> *pairs,
// get point pairs // get point pairs
DataXYZ xyz_reduced(Target->get("xyz reduced")); DataXYZ xyz_reduced(Target->get("xyz reduced"));
DataNormal normal_reduced(Target->get("normal reduced"));
Source->getSearchTree()->getPtPairs(pairs, Source->dalignxf, Source->getSearchTree()->getPtPairs(pairs, Source->dalignxf,
xyz_reduced, 0, xyz_reduced.size(), xyz_reduced, normal_reduced, 0, xyz_reduced.size(),
thread_num, thread_num,
rnd, max_dist_match2, sum, centroid_m, centroid_d); rnd, max_dist_match2, sum, centroid_m, centroid_d,
pairing_mode);
// normalize centroids // normalize centroids
unsigned int size = pairs->size(); unsigned int size = pairs->size();
@ -801,11 +825,14 @@ void Scan::getPtPairs(vector <PtPair> *pairs,
* by Langis / Greenspan / Godin, IEEE 3DIM 2001 * by Langis / Greenspan / Godin, IEEE 3DIM 2001
* *
*/ */
void Scan::getPtPairsParallel(vector <PtPair> *pairs, Scan* Source, Scan* Target, void Scan::getPtPairsParallel(vector <PtPair> *pairs,
Scan* Source, Scan* Target,
int thread_num, int step, int thread_num, int step,
int rnd, double max_dist_match2, int rnd, double max_dist_match2,
double *sum, double *sum,
double centroid_m[OPENMP_NUM_THREADS][3], double centroid_d[OPENMP_NUM_THREADS][3]) double centroid_m[OPENMP_NUM_THREADS][3],
double centroid_d[OPENMP_NUM_THREADS][3],
PairingMode pairing_mode)
{ {
// initialize centroids // initialize centroids
for(unsigned int i = 0; i < 3; ++i) { for(unsigned int i = 0; i < 3; ++i) {
@ -822,22 +849,26 @@ void Scan::getPtPairsParallel(vector <PtPair> *pairs, Scan* Source, Scan* Target
for(unsigned int i = 0; i < meta->size(); ++i) { for(unsigned int i = 0; i < meta->size(); ++i) {
// determine step for each scan individually // determine step for each scan individually
DataXYZ xyz_reduced(meta->getScan(i)->get("xyz reduced")); DataXYZ xyz_reduced(meta->getScan(i)->get("xyz reduced"));
DataNormal normal_reduced(Target->get("normal reduced"));
unsigned int max = xyz_reduced.size(); unsigned int max = xyz_reduced.size();
unsigned int step = max / OPENMP_NUM_THREADS; unsigned int step = max / OPENMP_NUM_THREADS;
// call ptpairs for each scan and accumulate ptpairs, centroids and sum // call ptpairs for each scan and accumulate ptpairs, centroids and sum
search->getPtPairs(&pairs[thread_num], Source->dalignxf, search->getPtPairs(&pairs[thread_num], Source->dalignxf,
xyz_reduced, step * thread_num, step * thread_num + step, xyz_reduced, normal_reduced,
step * thread_num, step * thread_num + step,
thread_num, thread_num,
rnd, max_dist_match2, sum[thread_num], rnd, max_dist_match2, sum[thread_num],
centroid_m[thread_num], centroid_d[thread_num]); centroid_m[thread_num], centroid_d[thread_num], pairing_mode);
} }
} else { } else {
DataXYZ xyz_reduced(Target->get("xyz reduced")); DataXYZ xyz_reduced(Target->get("xyz reduced"));
DataNormal normal_reduced(Target->get("normal reduced"));
search->getPtPairs(&pairs[thread_num], Source->dalignxf, search->getPtPairs(&pairs[thread_num], Source->dalignxf,
xyz_reduced, thread_num * step, thread_num * step + step, xyz_reduced, normal_reduced,
thread_num * step, thread_num * step + step,
thread_num, thread_num,
rnd, max_dist_match2, sum[thread_num], rnd, max_dist_match2, sum[thread_num],
centroid_m[thread_num], centroid_d[thread_num]); centroid_m[thread_num], centroid_d[thread_num], pairing_mode);
} }
// normalize centroids // normalize centroids

View file

@ -18,9 +18,17 @@
#include "slam6d/scan.h" #include "slam6d/scan.h"
#include "slam6d/globals.icc" #include "slam6d/globals.icc"
#include <stdexcept>
double *SearchTree::FindClosestAlongDir(double *_p, double *_dir, double maxdist2, int threadNum) const
{
throw std::runtime_error("Method FindClosestAlongDir is not implemented");
}
void SearchTree::getPtPairs(vector <PtPair> *pairs, void SearchTree::getPtPairs(vector <PtPair> *pairs,
double *source_alignxf, // source double *source_alignxf, // source
double * const *q_points, unsigned int startindex, unsigned int endindex, // target double * const *q_points,
unsigned int startindex, unsigned int endindex, // target
int thread_num, int thread_num,
int rnd, double max_dist_match2, double &sum, int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d) double *centroid_m, double *centroid_d)
@ -82,10 +90,12 @@ void SearchTree::getPtPairs(vector <PtPair> *pairs,
void SearchTree::getPtPairs(vector <PtPair> *pairs, void SearchTree::getPtPairs(vector <PtPair> *pairs,
double *source_alignxf, // source double *source_alignxf, // source
const DataXYZ& xyz_r, unsigned int startindex, unsigned int endindex, // target const DataXYZ& xyz_r, const DataNormal& normal_r,
unsigned int startindex, unsigned int endindex, // target
int thread_num, int thread_num,
int rnd, double max_dist_match2, double &sum, int rnd, double max_dist_match2, double &sum,
double *centroid_m, double *centroid_d) double *centroid_m, double *centroid_d,
PairingMode pairing_mode)
{ {
// prepare this tree for resource access in FindClosest // prepare this tree for resource access in FindClosest
lock(); lock();
@ -95,7 +105,7 @@ void SearchTree::getPtPairs(vector <PtPair> *pairs,
// t is the original point from target, s is the (inverted) query point from target and then // t is the original point from target, s is the (inverted) query point from target and then
// the closest point in source // the closest point in source
double t[3], s[3]; double t[3], s[3], normal[3];
for (unsigned int i = startindex; i < endindex; i++) { for (unsigned int i = startindex; i < endindex; i++) {
if (rnd > 1 && rand(rnd) != 0) continue; // take about 1/rnd-th of the numbers only if (rnd > 1 && rand(rnd) != 0) continue; // take about 1/rnd-th of the numbers only
@ -105,10 +115,43 @@ void SearchTree::getPtPairs(vector <PtPair> *pairs,
transform3(local_alignxf_inv, t, s); transform3(local_alignxf_inv, t, s);
double *closest = this->FindClosest(s, max_dist_match2, thread_num); double *closest;
if (pairing_mode != CLOSEST_POINT) {
normal[0] = normal_r[i][0];
normal[1] = normal_r[i][1];
normal[2] = normal_r[i][2];
Normalize3(normal);
}
if (pairing_mode == CLOSEST_POINT_ALONG_NORMAL) {
transform3normal(local_alignxf_inv, normal);
closest = this->FindClosestAlongDir(s, normal, max_dist_match2, thread_num);
// discard points farther than 20 cm
if (closest && sqrt(Dist2(closest, s)) > 20) closest = NULL;
} else {
closest = this->FindClosest(s, max_dist_match2, thread_num);
}
if (closest) { if (closest) {
transform3(source_alignxf, closest, s); transform3(source_alignxf, closest, s);
if (pairing_mode == CLOSEST_PLANE) {
// need to mutate s if we are looking for closest point-to-plane
// s_ = (n,s-t)*n + t
// to find the projection of s onto plane formed by normal n and point t
double tmp[3], s_[3];
double dot;
sub3(s, t, tmp);
dot = Dot(normal, tmp);
scal_mul3(normal, dot, tmp);
add3(tmp, t, s_);
s[0] = s_[0];
s[1] = s_[1];
s[2] = s_[2];
}
// This should be right, model=Source=First=not moving // This should be right, model=Source=First=not moving
centroid_m[0] += s[0]; centroid_m[0] += s[0];
centroid_m[1] += s[1]; centroid_m[1] += s[1];

View file

@ -194,7 +194,6 @@ void usage(char* prog)
<< " 2 = Lu & Milios extension using using unit quaternions" << endl << " 2 = Lu & Milios extension using using unit quaternions" << endl
<< " 3 = HELIX approximation by Hofer and Pottmann" << endl << " 3 = HELIX approximation by Hofer and Pottmann" << endl
<< " 4 = small angle approximation" << endl << " 4 = small angle approximation" << endl
<< endl
<< bold << " -i" << normal << " NR, " << bold << "--iter=" << normal << "NR [default: 50]" << endl << bold << " -i" << normal << " NR, " << bold << "--iter=" << normal << "NR [default: 50]" << endl
<< " sets the maximal number of ICP iterations to <NR>" << endl << " sets the maximal number of ICP iterations to <NR>" << endl
<< endl << endl
@ -306,7 +305,7 @@ int parseArgs(int argc, char **argv, string &dir, double &red, int &rand,
int &mni_lum, string &net, double &cldist, int &clpairs, int &loopsize, int &mni_lum, string &net, double &cldist, int &clpairs, int &loopsize,
double &epsilonICP, double &epsilonSLAM, int &nns_method, bool &exportPts, double &distLoop, double &epsilonICP, double &epsilonSLAM, int &nns_method, bool &exportPts, double &distLoop,
int &iterLoop, double &graphDist, int &octree, bool &cuda_enabled, IOType &type, int &iterLoop, double &graphDist, int &octree, bool &cuda_enabled, IOType &type,
bool& scanserver) bool& scanserver, PairingMode& pairing_mode)
{ {
int c; int c;
// from unistd.h: // from unistd.h:
@ -347,6 +346,8 @@ int parseArgs(int argc, char **argv, string &dir, double &red, int &rand,
{ "DlastSLAM", required_argument, 0, '4' }, // use the long format only { "DlastSLAM", required_argument, 0, '4' }, // use the long format only
{ "epsICP", required_argument, 0, '5' }, // use the long format only { "epsICP", required_argument, 0, '5' }, // use the long format only
{ "epsSLAM", required_argument, 0, '6' }, // use the long format only { "epsSLAM", required_argument, 0, '6' }, // use the long format only
{ "normalshoot", no_argument, 0, '7' }, // use the long format only
{ "point-to-plane", no_argument, 0, 'z' }, // use the long format only
{ "exportAllPoints", no_argument, 0, '8' }, { "exportAllPoints", no_argument, 0, '8' },
{ "distLoop", required_argument, 0, '9' }, // use the long format only { "distLoop", required_argument, 0, '9' }, // use the long format only
{ "iterLoop", required_argument, 0, '1' }, // use the long format only { "iterLoop", required_argument, 0, '1' }, // use the long format only
@ -475,6 +476,12 @@ int parseArgs(int argc, char **argv, string &dir, double &red, int &rand,
case '3': // = --graphDist case '3': // = --graphDist
graphDist = atof(optarg); graphDist = atof(optarg);
break; break;
case '7': // = --normalshoot
pairing_mode = CLOSEST_POINT_ALONG_NORMAL;
break;
case 'z': // = --point-to-plane
pairing_mode = CLOSEST_PLANE;
break;
case 'f': case 'f':
try { try {
w_type = formatname_to_io_type(optarg); w_type = formatname_to_io_type(optarg);
@ -693,7 +700,7 @@ int main(int argc, char **argv)
cout << "slam6D - A highly efficient SLAM implementation based on scan matching" << endl cout << "slam6D - A highly efficient SLAM implementation based on scan matching" << endl
<< " with 6 degrees of freedom" << endl << " with 6 degrees of freedom" << endl
<< "(c) Jacobs University Bremen gGmbH, Germany, since 2009" << endl << "(c) Jacobs University Bremen gGmbH, Germany, since 2009" << endl
<< " University of Osnabrueck, Germany, 2006 - 2009" << endl << endl; << " University of Osnabrueck, Germany, since 2006" << endl << endl;
if (argc <= 1) { if (argc <= 1) {
usage(argv[0]); usage(argv[0]);
@ -731,12 +738,13 @@ int main(int argc, char **argv)
bool cuda_enabled = false; bool cuda_enabled = false;
IOType type = UOS; IOType type = UOS;
bool scanserver = false; bool scanserver = false;
PairingMode pairing_mode = CLOSEST_POINT;
parseArgs(argc, argv, dir, red, rand, mdm, mdml, mdmll, mni, start, end, parseArgs(argc, argv, dir, red, rand, mdm, mdml, mdmll, mni, start, end,
maxDist, minDist, quiet, veryQuiet, eP, meta, algo, loopSlam6DAlgo, lum6DAlgo, anim, maxDist, minDist, quiet, veryQuiet, eP, meta, algo, loopSlam6DAlgo, lum6DAlgo, anim,
mni_lum, net, cldist, clpairs, loopsize, epsilonICP, epsilonSLAM, mni_lum, net, cldist, clpairs, loopsize, epsilonICP, epsilonSLAM,
nns_method, exportPts, distLoop, iterLoop, graphDist, octree, cuda_enabled, type, nns_method, exportPts, distLoop, iterLoop, graphDist, octree, cuda_enabled, type,
scanserver); scanserver, pairing_mode);
cout << "slam6D will proceed with the following parameters:" << endl; cout << "slam6D will proceed with the following parameters:" << endl;
//@@@ to do :-) //@@@ to do :-)
@ -752,7 +760,12 @@ int main(int argc, char **argv)
for(ScanVector::iterator it = Scan::allScans.begin(); it != Scan::allScans.end(); ++it) { for(ScanVector::iterator it = Scan::allScans.begin(); it != Scan::allScans.end(); ++it) {
Scan* scan = *it; Scan* scan = *it;
scan->setRangeFilter(maxDist, minDist); scan->setRangeFilter(maxDist, minDist);
scan->setReductionParameter(red, octree); unsigned int types = 0;
if ((pairing_mode == CLOSEST_POINT_ALONG_NORMAL) ||
(pairing_mode == CLOSEST_PLANE)) {
types = PointType::USE_NORMAL;
}
scan->setReductionParameter(red, octree, PointType(types));
scan->setSearchTreeParameter(nns_method, cuda_enabled); scan->setSearchTreeParameter(nns_method, cuda_enabled);
} }
@ -814,7 +827,7 @@ int main(int argc, char **argv)
my_icp->set_cad_matching (true); my_icp->set_cad_matching (true);
} }
if (my_icp) my_icp->doICP(Scan::allScans); if (my_icp) my_icp->doICP(Scan::allScans, pairing_mode);
delete my_icp; delete my_icp;
} else if (clpairs > -1) { } else if (clpairs > -1) {
//!!!!!!!!!!!!!!!!!!!!!!!! //!!!!!!!!!!!!!!!!!!!!!!!!
@ -830,7 +843,7 @@ int main(int argc, char **argv)
my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP, my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method, cuda_enabled); anim, epsilonICP, nns_method, cuda_enabled);
} }
my_icp->doICP(Scan::allScans); my_icp->doICP(Scan::allScans, pairing_mode);
graphSlam6D *my_graphSlam6D = new lum6DEuler(my_icp6Dminimizer, mdm, mdml, mni, quiet, meta, graphSlam6D *my_graphSlam6D = new lum6DEuler(my_icp6Dminimizer, mdm, mdml, mni, quiet, meta,
rand, eP, anim, epsilonICP, nns_method, epsilonSLAM); rand, eP, anim, epsilonICP, nns_method, epsilonSLAM);
my_graphSlam6D->matchGraph6Dautomatic(Scan::allScans, mni_lum, clpairs, loopsize); my_graphSlam6D->matchGraph6Dautomatic(Scan::allScans, mni_lum, clpairs, loopsize);
@ -869,7 +882,7 @@ int main(int argc, char **argv)
my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP, my_icp = new icp6D(my_icp6Dminimizer, mdm, mni, quiet, meta, rand, eP,
anim, epsilonICP, nns_method); anim, epsilonICP, nns_method);
} }
my_icp->doICP(Scan::allScans); my_icp->doICP(Scan::allScans, pairing_mode);
Graph* structure; Graph* structure;
structure = new Graph(net); structure = new Graph(net);
@ -940,11 +953,16 @@ int main(int argc, char **argv)
ofstream redptsout("points.pts"); ofstream redptsout("points.pts");
for(unsigned int i = 0; i < Scan::allScans.size(); i++) { for(unsigned int i = 0; i < Scan::allScans.size(); i++) {
DataXYZ xyz_r(Scan::allScans[i]->get("xyz reduced")); DataXYZ xyz_r(Scan::allScans[i]->get("xyz reduced"));
DataNormal normal_r(Scan::allScans[i]->get("normal reduced"));
for(unsigned int i = 0; i < xyz_r.size(); ++i) { for(unsigned int i = 0; i < xyz_r.size(); ++i) {
redptsout << xyz_r[i][0] << ' ' << xyz_r[i][1] << ' ' << xyz_r[i][2] << '\n'; int r,g,b;
r = (int)(normal_r[i][0] * (127.5) + 127.5);
g = (int)(normal_r[i][1] * (127.5) + 127.5);
b = (int)(fabs(normal_r[i][2]) * (255.0));
redptsout << xyz_r[i][0] << ' ' << xyz_r[i][1] << ' ' << xyz_r[i][2]
<< ' ' << r << ' ' << g << ' ' << b << '\n';
} }
redptsout << std::flush; redptsout << std::flush;
} }
redptsout.close(); redptsout.close();
redptsout.clear(); redptsout.clear();

View file

@ -1,5 +1,4 @@
IF (WITH_THERMO) IF (WITH_THERMO)
find_package(OpenCV REQUIRED)
include_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob) include_directories(${CMAKE_SOURCE_DIR}/3rdparty/cvblob)
include_directories(${CMAKE_SOURCE_DIR}/include/shapes/) include_directories(${CMAKE_SOURCE_DIR}/include/shapes/)