MeshLib Documentation
Loading...
Searching...
No Matches
Mesh ICP

Example of mesh ICP (finding transformation to match objects)

▶ See it live in the browser

  • C++
    #include <MRMesh/MRBox.h>
    #include <MRMesh/MRICP.h>
    #include <MRMesh/MRMesh.h>
    #include <iostream>
    int main()
    {
    // Load meshes
    auto meshFloatingRes = MR::MeshLoad::fromAnySupportedFormat( "meshA.stl" );
    if ( !meshFloatingRes.has_value() )
    {
    std::cerr << meshFloatingRes.error() << std::endl;
    return 1;
    }
    MR::Mesh& meshFloating = *meshFloatingRes;
    auto meshFixedRes = MR::MeshLoad::fromAnySupportedFormat( "meshB.stl" );
    if ( !meshFixedRes.has_value() )
    {
    std::cerr << meshFixedRes.error() << std::endl;
    return 1;
    }
    MR::Mesh& meshFixed = *meshFixedRes;
    // Prepare ICP parameters
    float diagonal = meshFixed.getBoundingBox().diagonal();
    float icpSamplingVoxelSize = diagonal * 0.01f; // To sample points from object
    MR::ICPProperties icpParams;
    icpParams.distThresholdSq = MR::sqr( diagonal * 0.1f ); // Use points pairs with maximum distance specified
    icpParams.exitVal = diagonal * 0.003f; // Stop when distance reached
    // Calculate transformation
    MR::ICP icp(
    MR::MeshOrPoints{ MR::MeshPart{ meshFloating } },
    MR::MeshOrPoints{ MR::MeshPart{ meshFixed } },
    MR::AffineXf3f(), MR::AffineXf3f(),
    icpSamplingVoxelSize );
    icp.setParams( icpParams );
    MR::AffineXf3f xf = icp.calculateTransformation();
    // Transform floating mesh
    meshFloating.transform( xf );
    // Output information string
    std::string info = icp.getStatusInfo();
    std::cerr << info << std::endl;
    // Save result
    if ( auto saveRes = MR::MeshSave::toAnySupportedFormat( meshFloating, "meshA_icp.stl" ); !saveRes )
    {
    std::cerr << saveRes.error() << std::endl;
    return 1;
    }
    }
    int main()
    Definition LaplacianDeformation.cpp:4
    constexpr auto sqr(T x) noexcept -> decltype(x *x)
    static constexpr SymMatrix2 diagonal(T diagVal) noexcept
    Expected< void > toAnySupportedFormat(const Mesh &mesh, const std::filesystem::path &file, const SaveSettings &settings={})
    Expected< Mesh > fromAnySupportedFormat(const std::filesystem::path &file, const MeshLoadSettings &settings={})
  • Python
    import meshlib.mrmeshpy as mrmeshpy
    # Load meshes
    meshFloating = mrmeshpy.loadMesh("meshA.stl")
    meshFixed = mrmeshpy.loadMesh("meshB.stl")
    # Prepare ICP parameters
    diagonal = meshFixed.getBoundingBox().diagonal()
    icp_sampling_voxel_size = diagonal * 0.01 # To sample points from object
    icp_params = mrmeshpy.ICPProperties()
    icp_params.distThresholdSq = (diagonal * 0.1) ** 2 # Use points pairs with maximum distance specified
    icp_params.exitVal = diagonal * 0.003 # Stop when this distance reached
    # Calculate transformation
    icp = mrmeshpy.ICP(meshFloating, meshFixed,
    mrmeshpy.AffineXf3f(), mrmeshpy.AffineXf3f(),
    icp_sampling_voxel_size)
    icp.setParams(icp_params)
    xf = icp.calculateTransformation()
    # Transform floating mesh
    meshFloating.transform(xf)
    # Output information string
    print(icp.getStatusInfo())
    # Save result
    mrmeshpy.saveMesh(meshFloating, "meshA_icp.stl")
  • C
    #include <MRCMesh/MRICP.h>
    #include <MRCMesh/MRMesh.h>
    #include <MRCMesh/MRMeshLoad.h>
    #include <MRCMesh/MRMeshOrPoints.h>
    #include <MRCMesh/MRMeshSave.h>
    #include <MRCMesh/MRString.h>
    #include <MRCMisc/expected_MR_Mesh_std_string.h>
    #include <MRCMisc/expected_void_std_string.h>
    #include <MRCMisc/std_string.h>
    #include <stdio.h>
    #include <stdlib.h>
    int main( void )
    {
    int rc = EXIT_FAILURE;
    // Load meshes:
    // First mesh, which will be moved.
    MR_expected_MR_Mesh_std_string* meshFloatingEx = MR_MeshLoad_fromAnySupportedFormat( "meshA.stl", NULL, NULL );
    MR_Mesh* meshFloating = MR_expected_MR_Mesh_std_string_value_mut( meshFloatingEx );
    if ( !meshFloating )
    {
    fprintf( stderr, "Failed to load mesh A: %s\n", MR_std_string_data( MR_expected_MR_Mesh_std_string_error( meshFloatingEx ) ) );
    goto fail_mesh_loading_a;
    }
    // Second mesh, static.
    MR_expected_MR_Mesh_std_string* meshReferenceEx = MR_MeshLoad_fromAnySupportedFormat( "meshB.stl", NULL, NULL );
    MR_Mesh* meshReference = MR_expected_MR_Mesh_std_string_value_mut( meshReferenceEx );
    if ( !meshReference )
    {
    fprintf( stderr, "Failed to load mesh B: %s\n", MR_std_string_data( MR_expected_MR_Mesh_std_string_error( meshReferenceEx ) ) );
    goto fail_mesh_loading_b;
    }
    // Prepare ICP parameters
    MR_Box3f bbox = MR_Mesh_computeBoundingBox( meshReference, NULL );
    float diagonal = MR_Box3f_diagonal( &bbox );
    float icpSamplingVoxelSize = diagonal * 0.01f; // To sample points from object
    MR_ICPProperties* icpParams = MR_ICPProperties_DefaultConstruct();
    MR_ICPProperties_Set_distThresholdSq( icpParams, diagonal * diagonal * 0.01f ); // Use points pairs with maximum distance specified
    MR_ICPProperties_Set_exitVal( icpParams, diagonal * 0.003f ); // Stop when distance reached
    // Calculate transformation
    MR_MeshOrPoints* fltMop = MR_MeshOrPoints_Construct_MR_Mesh( meshFloating );
    MR_MeshOrPoints* refMop = MR_MeshOrPoints_Construct_MR_Mesh( meshReference );
    MR_MeshOrPointsXf* flt = MR_MeshOrPointsXf_ConstructFrom( fltMop, MR_AffineXf3f_DefaultConstruct() );
    MR_MeshOrPointsXf* ref = MR_MeshOrPointsXf_ConstructFrom( refMop, MR_AffineXf3f_DefaultConstruct() );
    MR_MeshOrPoints_Destroy( fltMop );
    MR_MeshOrPoints_Destroy( refMop );
    MR_ICP* icp = MR_ICP_Construct( flt, ref, icpSamplingVoxelSize );
    MR_ICP_setParams( icp, icpParams );
    MR_ICPProperties_Destroy( icpParams );
    MR_AffineXf3f xf = MR_ICP_calculateTransformation( icp );
    // Transform floating mesh
    MR_Mesh_transform( meshFloating, &xf, NULL );
    // Output information string
    MR_std_string* info = MR_ICP_getStatusInfo( icp );
    fprintf( stderr, "%s\n", MR_std_string_data( info ) );
    MR_std_string_Destroy( info );
    MR_ICP_Destroy( icp );
    MR_MeshOrPointsXf_Destroy( flt );
    MR_MeshOrPointsXf_Destroy( ref );
    // Save result
    MR_expected_void_std_string* saveEx = MR_MeshSave_toAnySupportedFormat( meshFloating, "meshA_icp.stl", NULL, NULL);
    if ( MR_expected_void_std_string_error( saveEx ) )
    {
    fprintf( stderr, "Failed to save mesh: %s\n", MR_std_string_data( MR_expected_void_std_string_error( saveEx ) ) );
    goto fail_save;
    }
    rc = EXIT_SUCCESS;
    fail_save:
    MR_expected_void_std_string_Destroy( saveEx );
    fail_mesh_loading_b:
    MR_expected_MR_Mesh_std_string_Destroy( meshReferenceEx );
    fail_mesh_loading_a:
    MR_expected_MR_Mesh_std_string_Destroy( meshFloatingEx );
    return rc;
    }
  • C#
    public static class MeshICPExample
    {
    public static void Main(string[] args)
    {
    // Load meshes
    var meshFloating = MR.MeshLoad.fromAnySupportedFormat("meshA.stl");
    var meshFixed = MR.MeshLoad.fromAnySupportedFormat("meshB.stl");
    // Prepare ICP parameters
    float diagonal = meshFixed.getBoundingBox().diagonal();
    float icpSamplingVoxelSize = diagonal * 0.01f; // To sample points from object
    MR.ICPProperties icpParams = new();
    icpParams.distThresholdSq = (diagonal * 0.1f) * (diagonal * 0.1f); // Use points pairs with maximum distance specified
    icpParams.exitVal = diagonal * 0.003f; // Stop when distance reached
    // Calculate transformation
    MR.ICP icp = new(meshFloating, meshFixed, new MR.AffineXf3f(), new MR.AffineXf3f(), icpSamplingVoxelSize);
    icp.setParams(icpParams);
    var xf = icp.calculateTransformation();
    // Transform floating mesh
    meshFloating.transform(xf);
    // Output information string
    Console.Error.WriteLine(icp.getStatusInfo());
    // Save result
    MR.MeshSave.toAnySupportedFormat(meshFloating, "meshA_icp.stl");
    }
    }
  • JavaScript
    import createMeshLib from '@meshinspector/meshlib';
    const ml = await createMeshLib();
    // Load meshes
    using meshFloating = ml.MeshLoad.fromAnySupportedFormat('meshA.stl');
    using meshFixed = ml.MeshLoad.fromAnySupportedFormat('meshB.stl');
    // Prepare ICP parameters
    using box = meshFixed.computeBoundingBox();
    const diagonal = box.diagonal();
    const icpSamplingVoxelSize = diagonal * 0.01; // To sample points from object
    using icpParams = new ml.ICPProperties();
    icpParams.distThresholdSq = (diagonal * 0.1) ** 2; // Use point pairs with maximum distance specified
    icpParams.exitVal = diagonal * 0.003; // Stop when distance reached
    // Pair each mesh with an initial transformation (identity here). The JS ICP takes
    // MeshOrPointsXf; the source meshes back these wrappers, and the reverse-order disposal
    // of `using` guarantees the meshes outlive them.
    using floatingMop = ml.MeshOrPoints.fromMesh(meshFloating);
    using fixedMop = ml.MeshOrPoints.fromMesh(meshFixed);
    using identityXf = new ml.AffineXf3f();
    using floating = new ml.MeshOrPointsXf(floatingMop, identityXf);
    using fixed = new ml.MeshOrPointsXf(fixedMop, identityXf);
    // Calculate transformation
    using icp = new ml.ICP(floating, fixed, icpSamplingVoxelSize);
    icp.setParams(icpParams);
    using xf = icp.calculateTransformation();
    // Transform floating mesh
    meshFloating.transform(xf);
    // Output information string
    console.log(icp.getStatusInfo());
    // Save result
    ml.MeshSave.toAnySupportedFormat(meshFloating, 'meshA_icp.stl');
    Note
    The using declaration requires Node.js 24+ or a modern browser. On older runtimes, call .delete() on each object instead (see Memory Management in the JavaScript Setup Guide).
  • Rust
    use meshlib::{AffineXf3f, ICPProperties, MeshOrPoints, ICP};
    fn main() -> Result<(), String>
    {
    // Load meshes
    let mut mesh_floating = meshlib::mesh_load::from_any_supported_format("meshA.stl", None).into_result()?;
    let mesh_fixed = meshlib::mesh_load::from_any_supported_format("meshB.stl", None).into_result()?;
    // Prepare ICP parameters
    let diagonal = mesh_fixed.get_bounding_box().diagonal();
    let icp_sampling_voxel_size = diagonal * 0.01; // To sample points from object
    let mut icp_params = ICPProperties::new();
    icp_params.set_dist_threshold_sq((diagonal * 0.1).powi(2)); // Use points pairs with maximum distance specified
    icp_params.set_exit_val(diagonal * 0.003); // Stop when distance reached
    // Calculate transformation
    let mut icp = ICP::construct_5(
    &MeshOrPoints::construct_mr_mesh(&mesh_floating),
    &MeshOrPoints::construct_mr_mesh(&mesh_fixed),
    &AffineXf3f::new(), &AffineXf3f::new(),
    icp_sampling_voxel_size);
    icp.set_params(&icp_params);
    let xf = icp.calculate_transformation();
    // Transform floating mesh
    mesh_floating.transform(&xf, None);
    // Output information string
    let info = icp.get_status_info();
    eprintln!("{}", *info);
    // Save result
    meshlib::mesh_save::to_any_supported_format(&mesh_floating, "meshA_icp.stl", None).into_result()?;
    Ok(())
    }
  • Java
    import meshlib.AffineXf3f;
    import meshlib.ICP;
    import meshlib.ICPProperties;
    import meshlib.Mesh;
    import meshlib.MeshOrPoints;
    // The class isn't public because of the `.dox.java` file name, the launcher doesn't mind.
    class MeshICP
    {
    public static void main(String[] args)
    {
    // Load meshes. An error is thrown as `UnexpectedResultException`.
    Mesh meshFloating = meshlib.meshload.Functions.fromAnySupportedFormat("meshA.stl", null);
    Mesh meshFixed = meshlib.meshload.Functions.fromAnySupportedFormat("meshB.stl", null);
    // Prepare ICP parameters
    float diagonal = meshFixed.getBoundingBox().diagonal();
    float icpSamplingVoxelSize = diagonal * 0.01f; // To sample points from object
    ICPProperties icpParams = new ICPProperties();
    icpParams.setDistThresholdSq((diagonal * 0.1f) * (diagonal * 0.1f)); // Use points pairs with maximum distance specified
    icpParams.setExitVal(diagonal * 0.003f); // Stop when distance reached
    // Calculate transformation
    ICP icp = new ICP(
    new MeshOrPoints(meshFloating),
    new MeshOrPoints(meshFixed),
    new AffineXf3f(), new AffineXf3f(),
    icpSamplingVoxelSize);
    icp.setParams(icpParams);
    AffineXf3f xf = icp.calculateTransformation();
    // Transform floating mesh
    meshFloating.transform(xf, null);
    // Output information string
    String info = icp.getStatusInfo().toString();
    System.err.println(info);
    // Save result
    meshlib.meshsave.Functions.toAnySupportedFormat(meshFloating, "meshA_icp.stl", null);
    }
    }
    MeshOrPoints(const MeshPart &mp)
    ICP(const MeshOrPoints &flt, const MeshOrPoints &ref, const AffineXf3f &fltXf, const AffineXf3f &refXf, const VertBitSet &fltSamples={}, const VertBitSet &refSamples={})