我在之前的一个专栏发过一个将地理坐标的数据转成3D的STL模型。我下面介绍一下如何将长方体转成STL文件。我提供两个方法。

第一个是matlab程序。与地理坐标不一样,长方体存在特殊的情况,比如需要把其分成上下、左右、前后6部分进行拼接。关于这部分的知识,可以参考这个up的专栏。我在此基础上,得到了一个方案。具体的代码如下:

bi = load('b01.txt');
scatter3(bi(1,:),bi(2,:),bi(3,:))
x = bi(1,:);
y = bi(2,:);
z = bi(3,:);
[Anum,index] = sort(x);
%% labeling
x1 = [Anum(1),Anum(3);Anum(5),Anum(7)];
y1 = [y(index(1)),y(index(3));y(index(5)),y(index(7))];
z1 = [z(index(1)),z(index(3));z(index(5)),z(index(7))];
xyz2stl('rectangular.stl',x1,y1,z1)

其中的 b01.txt为x,y,z三列数据。

18.6613959728922 3.14143675683556    3.02457703598341
20.3888047311257    -7.71573813292703   3.02457703598341
30.4000436850529    -6.12292029353781   3.02457703598341
28.6726349268193    4.73425459622477    3.02457703598341
28.6726349268193    4.73425459622477    -3.02457703598341
30.4000436850529    -6.12292029353781   -3.02457703598341
20.3888047311257    -7.71573813292703   -3.02457703598341
18.6613959728922    3.14143675683556    -3.02457703598341

而xyz2stl函数为

function f=xyz2stl(FileName,X,Y,Z)Nx=size(Z,2);Ny=size(Z,1);fid=fopen(FileName,'w');fprintf(fid,'solid\n');%top surfaceSurf_write(fid,X,Y,Z,0);%other surface assumed to be plane% %X=X(1,1) planeXs=repmat(X(1,:),2,1);Ys=repmat(Y(1,:),2,1);Zs=[zeros(1,Ny);Z(:,1)'];Surf_write(fid,Xs,Ys,Zs,0);%X=X(1,Nx) planeXs=repmat(X(2,:),2,1);Ys=repmat(Y(2,:),2,1);Zs=[zeros(1,Ny);Z(:,1)'];Surf_write(fid,Xs,Ys,Zs,0);% %Y=Y(1,1) planeXs=repmat(X(:,1)',2,1);Ys=repmat(Y(:,1)',2,1);Zs=[zeros(1,Ny);Z(:,1)'];Surf_write(fid,Xs,Ys,Zs,0);% %Y=Y(Ny,1) planeXs=repmat(X(:,2)',2,1);Ys=repmat(Y(:,2)',2,1);Zs=[zeros(1,Ny);Z(:,1)'];Surf_write(fid,Xs,Ys,Zs,0);%% %the bottom planeSurf_write(fid,X,Y,0*Z,0);fprintf(fid,'endsolid');fclose(fid);disp('xyz2stl finish!')
end

其中包含的函数为:

function f=Surf_write(fid,X,Y,Z,opt)
for i=1:size(Z,1)-1for j=1:size(Z,2)-1%splitting each small rectangular to 2 small triangularp1=[X(i,j),Y(i,j),Z(i,j)];p2=[X(i+1,j),Y(i+1,j),Z(i+1,j)];p3=[X(i+1,j+1),Y(i+1,j+1),Z(i+1,j+1)];local_write_facet(fid,p1,p2,p3,opt);p1=[X(i,j),Y(i,j),Z(i,j)];p3=[X(i,j+1),Y(i,j+1),Z(i,j+1)];p2=[X(i+1,j+1),Y(i+1,j+1),Z(i+1,j+1)];local_write_facet(fid,p1,p2,p3,opt);end
end
f=1;
end%to write a single small triangular to the file
function num = local_write_facet(fid,p1,p2,p3,opt)num = 1;n = local_find_normal(p1,p2,p3,opt);fprintf(fid,'facet normal %.7E %.7E %.7E\r\n', n(1),n(2),n(3) );fprintf(fid,'outer loop\r\n');fprintf(fid,'vertex %.7E %.7E %.7E\r\n', p1);fprintf(fid,'vertex %.7E %.7E %.7E\r\n', p2);fprintf(fid,'vertex %.7E %.7E %.7E\r\n', p3);fprintf(fid,'endloop\r\n');fprintf(fid,'endfacet\r\n');end%to generate the normal direction vector n, from the vertex of triangular
function n = local_find_normal(p1,p2,p3,opt)
if ~opt
v2 = p2-p1;
v1 = p3-p1;
v3 = cross(v1,v2);
n = v3 ./ sqrt(sum(v3.*v3));
elsen=opt;
end
end

第二个是一个matlab小程序包。具体的下载链接为:https://github.com/NWRichmond/xyz2stl.

经过本文的测试,运行该程序包,需要在这个文件目录下增加一个函数:stlWrite函数,如下:

function stlWrite(filename, varargin)
%STLWRITE   Write STL file from patch or surface data.
%
%   STLWRITE(FILE,fv) writes a stereolithography (STL) file to FILE for a triangulated
%   patch defined by FV (a structure with fields 'vertices' and 'faces').
%
%   STLWRITE(FILE,FACES,VERTICES) takes faces and vertices separately, rather than in an FV struct
%
%   STLWRITE(FILE,X,Y,Z) creates an STL file from surface data in X, Y, and Z. STLWRITE triangulates
%   this gridded data into a triangulated surface using triangulations options specified below. X, Y
%   and Z can be two-dimensional arrays with the same size. If X and Y are vectors with length equal
%   to SIZE(Z,2) and SIZE(Z,1), respectively, they are passed through MESHGRID to create gridded
%   data. If X or Y are scalar values, they are used to specify the X and Y spacing between grid
%   points.
%
%   STLWRITE(...,'PropertyName',VALUE,'PropertyName',VALUE,...) writes an STL file using the
%   following property values:
%
%   MODE          - File is written using 'binary' (default) or 'ascii'.
%
%   TITLE         - Header text (max 80 characters) written to the STL file.
%
%   TRIANGULATION - When used with gridded data, TRIANGULATION is either:
%                       'delaunay'  - (default) Delaunay triangulation of X, Y
%                       'f'         - Forward slash division of grid quadrilaterals
%                       'b'         - Back slash division of quadrilaterals
%                       'x'         - Cross division of quadrilaterals
%                   Note that 'f', 'b', or 't' triangulations require FEX entry 28327, "mesh2tri".
%
%   FACECOLOR     - (not currently implemented) When used with face/vertex input, specifies the
%                   colour of each triangle face. If users request this feature, I will attempt to
%                   implement it.
%
%   Example 1:
%       % Write binary STL from face/vertex data
%       tmpvol = zeros(20,20,20);       % Empty voxel volume
%       tmpvol(8:12,8:12,5:15) = 1;     % Turn some voxels on
%       fv = isosurface(tmpvol, 0.99);  % Create the patch object
%       stlwrite('test.stl',fv)         % Save to binary .stl
%
%   Example 2:
%       % Write ascii STL from gridded data
%       [X,Y] = deal(1:40);             % Create grid reference
%       Z = peaks(40);                  % Create grid height
%       stlwrite('test.stl',X,Y,Z,'mode','ascii')%   Original idea adapted from surf2stl by Bill McDonald. Huge speed
%   improvements implemented by Oliver Woodford. Non-Delaunay triangulation
%   of quadrilateral surface input requires mesh2tri by Kevin Moerman.
%
%   Author: Sven Holcombe, 11-24-11% Check valid filename path
narginchk(2, inf)
path = fileparts(filename);
if ~isempty(path) && ~exist(path,'dir')error('Directory "%s" does not exist.',path);
end% Get faces, vertices, and user-defined options for writing
[faces, vertices, options] = parseInputs(varargin{:});
asciiMode = strcmp( options.mode ,'ascii');% Create the facets
facets = single(vertices');
facets = reshape(facets(:,faces'), 3, 3, []);% Compute their normals
V1 = squeeze(facets(:,2,:) - facets(:,1,:));
V2 = squeeze(facets(:,3,:) - facets(:,1,:));
normals = V1([2 3 1],:) .* V2([3 1 2],:) - V2([2 3 1],:) .* V1([3 1 2],:);
clear V1 V2
normals = bsxfun(@times, normals, 1 ./ sqrt(sum(normals .* normals, 1)));
facets = cat(2, reshape(normals, 3, 1, []), facets);
clear normals% Open the file for writing
permissions = {'w','wb+'};
fid = fopen(filename, permissions{asciiMode+1});
if (fid == -1)error('stlwrite:cannotWriteFile', 'Unable to write to %s', filename);
end% Write the file contents
if asciiMode% Write HEADERfprintf(fid,'solid %s\r\n',options.title);% Write DATAfprintf(fid,[...'facet normal %.7E %.7E %.7E\r\n' ...'outer loop\r\n' ...'vertex %.7E %.7E %.7E\r\n' ...'vertex %.7E %.7E %.7E\r\n' ...'vertex %.7E %.7E %.7E\r\n' ...'endloop\r\n' ...'endfacet\r\n'], facets);% Write FOOTERfprintf(fid,'endsolid %s\r\n',options.title);else % BINARY% Write HEADERfprintf(fid, '%-80s', options.title);             % Titlefwrite(fid, size(facets, 3), 'uint32');           % Number of facets% Write DATA% Add one uint16(0) to the end of each facet using a typecasting trickfacets = reshape(typecast(facets(:), 'uint16'), 12*2, []);facets(end+1,:) = 0;fwrite(fid, facets, 'uint16');
end% Close the file
fclose(fid);
fprintf('Wrote %d facets\n',size(facets, 3));%% Input handling subfunctions
function [faces, vertices, options] = parseInputs(varargin)
% Determine input type
if isstruct(varargin{1}) % stlwrite('file', FVstruct, ...)if ~all(isfield(varargin{1},{'vertices','faces'}))error( 'Variable p must be a faces/vertices structure' );endfaces = varargin{1}.faces;vertices = varargin{1}.vertices;options = parseOptions(varargin{2:end});elseif isnumeric(varargin{1})firstNumInput = cellfun(@isnumeric,varargin);firstNumInput(find(~firstNumInput,1):end) = 0; % Only consider numerical input PRIOR to the first non-numericnumericInputCnt = nnz(firstNumInput);options = parseOptions(varargin{numericInputCnt+1:end});switch numericInputCntcase 3 % stlwrite('file', X, Y, Z, ...)% Extract the matrix ZZ = varargin{3};% Convert scalar XY to vectorsZsizeXY = fliplr(size(Z));for i = 1:2if isscalar(varargin{i})varargin{i} = (0:ZsizeXY(i)-1) * varargin{i};endend% Extract X and Yif isequal(size(Z), size(varargin{1}), size(varargin{2}))% X,Y,Z were all provided as matrices[X,Y] = varargin{1:2};elseif numel(varargin{1})==ZsizeXY(1) && numel(varargin{2})==ZsizeXY(2)% Convert vector XY to meshgrid[X,Y] = meshgrid(varargin{1}, varargin{2});elseerror('stlwrite:badinput', 'Unable to resolve X and Y variables');end% Convert to faces/verticesif strcmp(options.triangulation,'delaunay')faces = delaunay(X,Y);vertices = [X(:) Y(:) Z(:)];elseif ~exist('mesh2tri','file')error('stlwrite:missing', '"mesh2tri" is required to convert X,Y,Z matrices to STL. It can be downloaded from:\n%s\n',...'http://www.mathworks.com/matlabcentral/fileexchange/28327')end[faces, vertices] = mesh2tri(X, Y, Z, options.triangulation);endcase 2 % stlwrite('file', FACES, VERTICES, ...)faces = varargin{1};vertices = varargin{2};otherwiseerror('stlwrite:badinput', 'Unable to resolve input types.');endendfunction options = parseOptions(varargin)
IP = inputParser;
IP.addParamValue('mode', 'binary', @ischar)
IP.addParamValue('title', sprintf('Created by stlwrite.m %s',datestr(now)), @ischar);
IP.addParamValue('triangulation', 'delaunay', @ischar);
IP.addParamValue('facecolor',[], @isnumeric)
IP.parse(varargin{:});
options = IP.Results;

运行该程序包中的xyz2stl.mlapp,得到以下的界面:

(1)我读取的文件是csv格式,因此选择文件后,Field Delimiter选择Comma,文件头没有则为0,下面选择的参数默认即可。

(2)下一步选择输出的路径和文件名,其余参数默认,点击运行即可。

下面即为得到的stl文件。

致谢:感谢B站粉丝提供的问题。

MATLAB将xyz数据转换成STL文件相关推荐

  1. 利用MATLAB将图片转换成coe文件、TXT文件、mif文件、bin文件

    利用MATLAB将图片转换成coe文件.TXT文件.mif文件 利用MATLAB将图片转换成coe文件 利用MATLAB将图片转换成txt文件 利用MATLAB将图片转换成mif文件 利用MATLAB ...

  2. caffe将图像数据转换成lmdb文件

    一.caffe安装 安装步骤:https://blog.csdn.net/yql_617540298/article/details/82718889 二.caffe将图像数据转换成lmdb文件 之前 ...

  3. matlab中通过pcwrite将xyz数据转换成pcd格式文件

    一.处理激光雷达点云过程中的数据 例如pcData 是10000*3的点云坐标数组 ptCloud = pointCloud(pcData(:,1:3)); pcwrite(ptCloud, 'tes ...

  4. Matlab GUI程序封装成exe文件并在不安装Matlab的电脑上运行

    最近根据需求用Matlab写了一个简单的软件,但需要安装到其他电脑上运行,倒腾了很久最终成功在其他电脑上运行,现将方法共享给大家. 安装方法: ①程序封装 首先用Matlab写完程序并封装好(我用的是 ...

  5. 将文本数据转换成arff文件

    目的: 将类似下图的文本数据转换为arff文件.文本数据每一行是一个句子和该句子的类属性值(classValue),得到的arff文件中的一个实例(Instance)即为一个句子的单词向量和类属性值. ...

  6. matlab读取表格读成mat文件,MATLAB 视频读取 Excel读写 Excel2txt txt2mat 按文件夹读取文件...

    视频转图片,图片取大小 clc;clear; obj=VideoReader('双闪.avi'); numFrames = obj.NumberOfFrames;% 帧的总数 for i=1:numF ...

  7. python读取oracle数据转换成json文件_python 读取网页json数据库中

    数据挖掘敲门砖--Python爬虫入门 Python爬虫.jpg WHAT 数据挖掘是一门综合的技术,随着Ai的兴起,在国内的需求日渐增大. 数据挖掘的职业方向通常有三个,顺便概要地提一下所需的技能( ...

  8. Lua工具:Excel数据转换成Lua文件

    现在很多手游使用Cocos2dx + Lua 的开发模式,在这过程中,很多游戏的基础数据,放在哪里,什么格式,怎么做效率最高. 当然是你已经采用的开发模式了, 基础数据做成Lua 文件,才是最好的,读 ...

  9. matlab将mat数据转换成excel表格并保存到电脑

    clc close all clear allload('E:\train\EEG_DataTrain.mat') for mood = 1:4for people = 1:12# DataTrain ...

  10. python如何将表格数据转换成txt文件

    任务需求:将表格中每一行拼接在一起,输出. 直接见代码 import xlrd filenames="C:/Users/Shineion/Desktop/QC/题目调度规程.xls" ...

最新文章

  1. Python3 加载图片并保存图片
  2. php中获取ip的地域信息比较精准
  3. 蚌埠粮食经济技师学院计算机,安徽粮食经济技师学院2020年有哪些专业
  4. 【Java文件操作(五)】从txt文件中读取字符串、乱码原因
  5. xss 表单劫持(from通用明文记录)
  6. 2021 icme_2021第十届制造工程与工艺国际会议(ICMEP 2021)
  7. 【图像处理】——opencv常用函数
  8. Qt4_坐标系统变换
  9. 《恋上数据结构第1季》二叉树基础、真二叉树、满二叉树、完全二叉树、二叉树的遍历(重点)
  10. 摄像头上传文件服务器失败,vue打开摄像头拍照并上传至服务器
  11. [转]java 中的序列化是什么意思?有什么好处?
  12. Mac mysql 忘记 root 密码,phpmyadmin 登录 No such file or directory 错误处理
  13. TOGAF ADM指导
  14. 国内期刊 CCT 模板编译经验
  15. 通电后第一次开机黑屏_完美解决win10开机后一直黑屏问题
  16. ijkplayer源码---FFPlayer结构体4 SDL_Aout
  17. android遥控器管理,Android 遥控器适配
  18. MYSQL数据库- 修改数据表名称、列名称
  19. 2020CCPC绵阳D.Defuse the Bombs(二分)
  20. 【小白学习记录】渗透测试之信息收集

热门文章

  1. CSS动画案例--天空中云朵变化效果
  2. DAZ Studio 4—3D动画制作工具
  3. LSTM调参经验(细读)
  4. 2019牛客暑期多校训练营(第三场)----C-Guessing ETT
  5. C语言解决三色旗问题
  6. 二项分布 (Binomial Distribution)
  7. WARNING: disk usage in log directory [/home/.../.ros/log] is over 1GB. 问题解决办法
  8. 【英语四六级-必背单词】高中英语单词 (D)-MP3试听与下载
  9. [渝粤教育] 西南科技大学 民法学 在线考试复习资料
  10. 一个超级棒的 Chrome 翻译插件