Clear Filters
Clear Filters

How to aligning STL files and find the distance between them ?

11 views (last 30 days)
Hi,
Could anyone suggest the most efficient way to align two imported STL files into MATLAB?
I am trying to align the files at the origin, then use the Hausdorff Distance function to find the distance between two points.
So preferably, one file must be translated to best align/ match up with the other.
Attached is one of the codes I am using to import the stl files, find the vertices and faces. Alternate approaches would be greatly appreciated.
I have also attched 2 images from the stl files.
[F, xyz1] = stlread('MATxct.stl');
[vn] = STLVertexNormals(F,xyz1);
[F1, xyz2] = stlread('MATcad.stl');
[vn1] = STLVertexNormals(F1, xyz2);
norm1 = mean(vn);
norm2 = mean(vn1);
% Centre for (vn)
cx1 = mean(xyz1(:,1));
cy1 = mean(xyz1(:,2));
cz1 = mean(xyz1(:,3));
xyz(:,1)=xyz1(:,1)-cx1;
xyz(:,2)=xyz1(:,2)-cy1;
xyz(:,3)=xyz1(:,3)-cz1;
% Centre for (vn1)
cx2 = mean(xyz2(:,1));
cy2 = mean(xyz2(:,2));
cz2 = mean(xyz2(:,3));
xyz22(:,1)=xyz2(:,1)-cx2;
xyz22(:,2)=xyz2(:,2)-cy2;
xyz22(:,3)=xyz2(:,3)-cz2;
% Rotating the STL files so that thie principle axes align with the
% coordinates
r=vrrotvec(norm1,[0, 0, 1]);
Rot = vrrotvec2mat(r);
xyz=Rot*xyz';
xyz=xyz';
scatter3(xyz(:,1),xyz(:,2),xyz(:,3),'b')
r=vrrotvec(norm2,[0, 0, 1]);
Rot = vrrotvec2mat(r);
xyz22=Rot*xyz22';
xyz22=xyz22';
scatter3(xyz(:,1),xyz(:,2),xyz(:,3),'b')

Answers (1)

Adit Kirtani
Adit Kirtani on 15 May 2023
Edited: Adit Kirtani on 15 May 2023
Hi Ronnie,
I see you’ve used the ‘stlread’ function for importing STL files. You can also use the following methods:
  • The ‘importGeometry’ function will create a DiscreteGeometry object of your STL file. You can use the ‘rotate’ function to help align your 3D geometry. Here are some documentation links which you may find handy:
  • ‘import_stl_file’ is also a another option if you want a faster version of stlread. Keep in mind the current version of the program is ASCII only and will not support binary. You can find it on the MATLAB File Exchange here:
I hope this helps,
Adit Kirtani.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!